blob: 25d567fc3af28d646091784fb734d3b97dfb6f17 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
38namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
Nick Lewycky134af912013-02-07 05:08:22 +000041/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000042static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000043CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000045 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000047 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000048 return ExprError();
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
51 // called on both.
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54 // being used.
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000056 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000057 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000058 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000061
62 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 ExprResult E = DRE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000065 E = S.DefaultFunctionArrayConversion(E.get());
John Wiegley01296292011-04-08 18:41:53 +000066 if (E.isInvalid())
67 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000068 return E;
John McCall7decc9e2010-11-18 06:31:45 +000069}
70
John McCall5c32be02010-08-24 20:38:10 +000071static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000073 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000074 bool CStyle,
75 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000076
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000077static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78 QualType &ToType,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
81 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000082static OverloadingResult
83IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000086 bool AllowExplicit,
87 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000088
89
90static ImplicitConversionSequence::CompareKind
91CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
94
95static ImplicitConversionSequence::CompareKind
96CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105
106
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107/// GetConversionCategory - Retrieve the implicit conversion
108/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +0000109ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110GetConversionCategory(ImplicitConversionKind Kind) {
111 static const ImplicitConversionCategory
112 Category[(int)ICK_Num_Conversion_Kinds] = {
113 ICC_Identity,
114 ICC_Lvalue_Transformation,
115 ICC_Lvalue_Transformation,
116 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000117 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000118 ICC_Qualification_Adjustment,
119 ICC_Promotion,
120 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000121 ICC_Promotion,
122 ICC_Conversion,
123 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000124 ICC_Conversion,
125 ICC_Conversion,
126 ICC_Conversion,
127 ICC_Conversion,
128 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000129 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000130 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000131 ICC_Conversion,
132 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000133 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 ICC_Conversion
135 };
136 return Category[(int)Kind];
137}
138
139/// GetConversionRank - Retrieve the implicit conversion rank
140/// corresponding to the given implicit conversion kind.
141ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
142 static const ImplicitConversionRank
143 Rank[(int)ICK_Num_Conversion_Kinds] = {
144 ICR_Exact_Match,
145 ICR_Exact_Match,
146 ICR_Exact_Match,
147 ICR_Exact_Match,
148 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000149 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 ICR_Promotion,
151 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000152 ICR_Promotion,
153 ICR_Conversion,
154 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
158 ICR_Conversion,
159 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000160 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000161 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000162 ICR_Conversion,
163 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000164 ICR_Complex_Real_Conversion,
165 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000166 ICR_Conversion,
167 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000168 };
169 return Rank[(int)Kind];
170}
171
172/// GetImplicitConversionName - Return the name of this kind of
173/// implicit conversion.
174const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000175 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000176 "No conversion",
177 "Lvalue-to-rvalue",
178 "Array-to-pointer",
179 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000180 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000181 "Qualification",
182 "Integral promotion",
183 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000184 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000185 "Integral conversion",
186 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000187 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000188 "Floating-integral conversion",
189 "Pointer conversion",
190 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000191 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000192 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000193 "Derived-to-base conversion",
194 "Vector conversion",
195 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000196 "Complex-real conversion",
197 "Block Pointer conversion",
198 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000199 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200 };
201 return Name[Kind];
202}
203
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000204/// StandardConversionSequence - Set the standard conversion
205/// sequence to the identity conversion.
206void StandardConversionSequence::setAsIdentityConversion() {
207 First = ICK_Identity;
208 Second = ICK_Identity;
209 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000210 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000211 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000212 ReferenceBinding = false;
213 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000214 IsLvalueReference = true;
215 BindsToFunctionLvalue = false;
216 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000217 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000218 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000220}
221
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222/// getRank - Retrieve the rank of this standard conversion sequence
223/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
224/// implicit conversions.
225ImplicitConversionRank StandardConversionSequence::getRank() const {
226 ImplicitConversionRank Rank = ICR_Exact_Match;
227 if (GetConversionRank(First) > Rank)
228 Rank = GetConversionRank(First);
229 if (GetConversionRank(Second) > Rank)
230 Rank = GetConversionRank(Second);
231 if (GetConversionRank(Third) > Rank)
232 Rank = GetConversionRank(Third);
233 return Rank;
234}
235
236/// isPointerConversionToBool - Determines whether this conversion is
237/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000238/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000239/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000240bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000241 // Note that FromType has not necessarily been transformed by the
242 // array-to-pointer or function-to-pointer implicit conversions, so
243 // check for their presence as well as checking whether FromType is
244 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000245 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000246 (getFromType()->isPointerType() ||
247 getFromType()->isObjCObjectPointerType() ||
248 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000249 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000250 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
251 return true;
252
253 return false;
254}
255
Douglas Gregor5c407d92008-10-23 00:40:37 +0000256/// isPointerConversionToVoidPointer - Determines whether this
257/// conversion is a conversion of a pointer to a void pointer. This is
258/// used as part of the ranking of standard conversion sequences (C++
259/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000260bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000261StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000262isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000263 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000264 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000265
266 // Note that FromType has not necessarily been transformed by the
267 // array-to-pointer implicit conversion, so check for its presence
268 // and redo the conversion to get a pointer.
269 if (First == ICK_Array_To_Pointer)
270 FromType = Context.getArrayDecayedType(FromType);
271
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000272 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000273 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000274 return ToPtrType->getPointeeType()->isVoidType();
275
276 return false;
277}
278
Richard Smith66e05fe2012-01-18 05:21:49 +0000279/// Skip any implicit casts which could be either part of a narrowing conversion
280/// or after one in an implicit conversion.
281static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
282 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
283 switch (ICE->getCastKind()) {
284 case CK_NoOp:
285 case CK_IntegralCast:
286 case CK_IntegralToBoolean:
287 case CK_IntegralToFloating:
288 case CK_FloatingToIntegral:
289 case CK_FloatingToBoolean:
290 case CK_FloatingCast:
291 Converted = ICE->getSubExpr();
292 continue;
293
294 default:
295 return Converted;
296 }
297 }
298
299 return Converted;
300}
301
302/// Check if this standard conversion sequence represents a narrowing
303/// conversion, according to C++11 [dcl.init.list]p7.
304///
305/// \param Ctx The AST context.
306/// \param Converted The result of applying this standard conversion sequence.
307/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
308/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000309/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
310/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000311NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000312StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
313 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000314 APValue &ConstantValue,
315 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000316 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000317
318 // C++11 [dcl.init.list]p7:
319 // A narrowing conversion is an implicit conversion ...
320 QualType FromType = getToType(0);
321 QualType ToType = getToType(1);
322 switch (Second) {
323 // -- from a floating-point type to an integer type, or
324 //
325 // -- from an integer type or unscoped enumeration type to a floating-point
326 // type, except where the source is a constant expression and the actual
327 // value after conversion will fit into the target type and will produce
328 // the original value when converted back to the original type, or
329 case ICK_Floating_Integral:
330 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
331 return NK_Type_Narrowing;
332 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
333 llvm::APSInt IntConstantValue;
334 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
335 if (Initializer &&
336 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
337 // Convert the integer to the floating type.
338 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
339 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
340 llvm::APFloat::rmNearestTiesToEven);
341 // And back.
342 llvm::APSInt ConvertedValue = IntConstantValue;
343 bool ignored;
344 Result.convertToInteger(ConvertedValue,
345 llvm::APFloat::rmTowardZero, &ignored);
346 // If the resulting value is different, this was a narrowing conversion.
347 if (IntConstantValue != ConvertedValue) {
348 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000349 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000350 return NK_Constant_Narrowing;
351 }
352 } else {
353 // Variables are always narrowings.
354 return NK_Variable_Narrowing;
355 }
356 }
357 return NK_Not_Narrowing;
358
359 // -- from long double to double or float, or from double to float, except
360 // where the source is a constant expression and the actual value after
361 // conversion is within the range of values that can be represented (even
362 // if it cannot be represented exactly), or
363 case ICK_Floating_Conversion:
364 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
365 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
366 // FromType is larger than ToType.
367 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
368 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
369 // Constant!
370 assert(ConstantValue.isFloat());
371 llvm::APFloat FloatVal = ConstantValue.getFloat();
372 // Convert the source value into the target type.
373 bool ignored;
374 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
375 Ctx.getFloatTypeSemantics(ToType),
376 llvm::APFloat::rmNearestTiesToEven, &ignored);
377 // If there was no overflow, the source value is within the range of
378 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000379 if (ConvertStatus & llvm::APFloat::opOverflow) {
380 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000381 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000382 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000383 } else {
384 return NK_Variable_Narrowing;
385 }
386 }
387 return NK_Not_Narrowing;
388
389 // -- from an integer type or unscoped enumeration type to an integer type
390 // that cannot represent all the values of the original type, except where
391 // the source is a constant expression and the actual value after
392 // conversion will fit into the target type and will produce the original
393 // value when converted back to the original type.
394 case ICK_Boolean_Conversion: // Bools are integers too.
395 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
396 // Boolean conversions can be from pointers and pointers to members
397 // [conv.bool], and those aren't considered narrowing conversions.
398 return NK_Not_Narrowing;
399 } // Otherwise, fall through to the integral case.
400 case ICK_Integral_Conversion: {
401 assert(FromType->isIntegralOrUnscopedEnumerationType());
402 assert(ToType->isIntegralOrUnscopedEnumerationType());
403 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
404 const unsigned FromWidth = Ctx.getIntWidth(FromType);
405 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
406 const unsigned ToWidth = Ctx.getIntWidth(ToType);
407
408 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000409 (FromWidth == ToWidth && FromSigned != ToSigned) ||
410 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000411 // Not all values of FromType can be represented in ToType.
412 llvm::APSInt InitializerValue;
413 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000414 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
415 // Such conversions on variables are always narrowing.
416 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000417 }
418 bool Narrowing = false;
419 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000420 // Negative -> unsigned is narrowing. Otherwise, more bits is never
421 // narrowing.
422 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000423 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000424 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000425 // Add a bit to the InitializerValue so we don't have to worry about
426 // signed vs. unsigned comparisons.
427 InitializerValue = InitializerValue.extend(
428 InitializerValue.getBitWidth() + 1);
429 // Convert the initializer to and from the target width and signed-ness.
430 llvm::APSInt ConvertedValue = InitializerValue;
431 ConvertedValue = ConvertedValue.trunc(ToWidth);
432 ConvertedValue.setIsSigned(ToSigned);
433 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
434 ConvertedValue.setIsSigned(InitializerValue.isSigned());
435 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000436 if (ConvertedValue != InitializerValue)
437 Narrowing = true;
438 }
439 if (Narrowing) {
440 ConstantType = Initializer->getType();
441 ConstantValue = APValue(InitializerValue);
442 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000443 }
444 }
445 return NK_Not_Narrowing;
446 }
447
448 default:
449 // Other kinds of conversions are not narrowings.
450 return NK_Not_Narrowing;
451 }
452}
453
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000454/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000456void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000457 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000458 bool PrintedSomething = false;
459 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000460 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461 PrintedSomething = true;
462 }
463
464 if (Second != ICK_Identity) {
465 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000466 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000469
470 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000472 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000474 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000475 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000476 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 PrintedSomething = true;
478 }
479
480 if (Third != ICK_Identity) {
481 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000484 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 PrintedSomething = true;
486 }
487
488 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 }
491}
492
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000493/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000495void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000496 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000498 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000501 if (ConversionFunction)
502 OS << '\'' << *ConversionFunction << '\'';
503 else
504 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000507 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 }
509}
510
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000511/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000513void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000514 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000515 if (isStdInitializerListElement())
516 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517 switch (ConversionKind) {
518 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000519 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000520 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000521 break;
522 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000523 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000524 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525 break;
526 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000527 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528 break;
John McCall0d1da222010-01-12 00:44:57 +0000529 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000530 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000531 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000533 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534 break;
535 }
536
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000537 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000538}
539
John McCall0d1da222010-01-12 00:44:57 +0000540void AmbiguousConversionSequence::construct() {
541 new (&conversions()) ConversionSet();
542}
543
544void AmbiguousConversionSequence::destruct() {
545 conversions().~ConversionSet();
546}
547
548void
549AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
550 FromTypePtr = O.FromTypePtr;
551 ToTypePtr = O.ToTypePtr;
552 new (&conversions()) ConversionSet(O.conversions());
553}
554
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000556 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000557 // template argument information.
558 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 TemplateArgument FirstArg;
560 TemplateArgument SecondArg;
561 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000562 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000563 // template parameter and template argument information.
564 struct DFIParamWithArguments : DFIArguments {
565 TemplateParameter Param;
566 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000569/// \brief Convert from Sema's representation of template deduction information
570/// to the form used in overload-candidate information.
Larisse Voufo98b20f12013-07-19 23:00:19 +0000571DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
572 Sema::TemplateDeductionResult TDK,
573 TemplateDeductionInfo &Info) {
574 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000575 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000576 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000577 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000578 switch (TDK) {
579 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000580 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000581 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000582 case Sema::TDK_TooManyArguments:
583 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000586 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000587 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588 Result.Data = Info.Param.getOpaqueValue();
589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Richard Smith44ecdbd2013-01-31 05:19:49 +0000591 case Sema::TDK_NonDeducedMismatch: {
592 // FIXME: Should allocate from normal heap so that we can free this later.
593 DFIArguments *Saved = new (Context) DFIArguments;
594 Saved->FirstArg = Info.FirstArg;
595 Saved->SecondArg = Info.SecondArg;
596 Result.Data = Saved;
597 break;
598 }
599
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000601 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000602 // FIXME: Should allocate from normal heap so that we can free this later.
603 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Saved->Param = Info.Param;
605 Saved->FirstArg = Info.FirstArg;
606 Saved->SecondArg = Info.SecondArg;
607 Result.Data = Saved;
608 break;
609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000611 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000612 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000613 if (Info.hasSFINAEDiagnostic()) {
614 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
615 SourceLocation(), PartialDiagnostic::NullDiagnostic());
616 Info.takeSFINAEDiagnostic(*Diag);
617 Result.HasDiagnostic = true;
618 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000621 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000622 Result.Data = Info.Expression;
623 break;
624
Richard Smith44ecdbd2013-01-31 05:19:49 +0000625 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000628
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 return Result;
630}
John McCall0d1da222010-01-12 00:44:57 +0000631
Larisse Voufo98b20f12013-07-19 23:00:19 +0000632void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000633 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
634 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000635 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000636 case Sema::TDK_InstantiationDepth:
637 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000638 case Sema::TDK_TooManyArguments:
639 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000640 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000641 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000642 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000643
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000644 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000645 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000646 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000647 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000648 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000650
651 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000652 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000653 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000654 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
655 Diag->~PartialDiagnosticAt();
656 HasDiagnostic = false;
657 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000658 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Douglas Gregor461761d2010-05-08 18:20:53 +0000660 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000661 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000662 break;
663 }
664}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Larisse Voufo98b20f12013-07-19 23:00:19 +0000666PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000667 if (HasDiagnostic)
668 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000669 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000670}
671
Larisse Voufo98b20f12013-07-19 23:00:19 +0000672TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
674 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000675 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000676 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000677 case Sema::TDK_TooManyArguments:
678 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000679 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000680 case Sema::TDK_NonDeducedMismatch:
681 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000682 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000684 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000685 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000687
688 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000689 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000693 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 break;
695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 return TemplateParameter();
698}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Larisse Voufo98b20f12013-07-19 23:00:19 +0000700TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000702 case Sema::TDK_Success:
703 case Sema::TDK_Invalid:
704 case Sema::TDK_InstantiationDepth:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_Incomplete:
708 case Sema::TDK_InvalidExplicitArguments:
709 case Sema::TDK_Inconsistent:
710 case Sema::TDK_Underqualified:
711 case Sema::TDK_NonDeducedMismatch:
712 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000713 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000714
Richard Smith44ecdbd2013-01-31 05:19:49 +0000715 case Sema::TDK_SubstitutionFailure:
716 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 // Unhandled
719 case Sema::TDK_MiscellaneousDeductionFailure:
720 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000721 }
722
Craig Topperc3ec1492014-05-26 06:22:03 +0000723 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000724}
725
Larisse Voufo98b20f12013-07-19 23:00:19 +0000726const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000727 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
728 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000729 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000730 case Sema::TDK_InstantiationDepth:
731 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000732 case Sema::TDK_TooManyArguments:
733 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000734 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000735 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000736 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000737 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000740 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000741 case Sema::TDK_NonDeducedMismatch:
742 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000743
Douglas Gregor461761d2010-05-08 18:20:53 +0000744 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000745 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000746 break;
747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000748
Craig Topperc3ec1492014-05-26 06:22:03 +0000749 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000750}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000751
Larisse Voufo98b20f12013-07-19 23:00:19 +0000752const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000755 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000756 case Sema::TDK_InstantiationDepth:
757 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000758 case Sema::TDK_TooManyArguments:
759 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000760 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000761 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000762 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000763 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000764
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000765 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000766 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000767 case Sema::TDK_NonDeducedMismatch:
768 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000769
Douglas Gregor461761d2010-05-08 18:20:53 +0000770 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000771 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 break;
773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
Craig Topperc3ec1492014-05-26 06:22:03 +0000775 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776}
777
Larisse Voufo98b20f12013-07-19 23:00:19 +0000778Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000779 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
780 Sema::TDK_FailedOverloadResolution)
781 return static_cast<Expr*>(Data);
782
Craig Topperc3ec1492014-05-26 06:22:03 +0000783 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000784}
785
Benjamin Kramer97e59492012-10-09 15:52:25 +0000786void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000787 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000788 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
789 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000790 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
791 i->DeductionFailure.Destroy();
792 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000793}
794
795void OverloadCandidateSet::clear() {
796 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000797 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000798 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000799 Functions.clear();
800}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801
John McCall4124c492011-10-17 18:40:02 +0000802namespace {
803 class UnbridgedCastsSet {
804 struct Entry {
805 Expr **Addr;
806 Expr *Saved;
807 };
808 SmallVector<Entry, 2> Entries;
809
810 public:
811 void save(Sema &S, Expr *&E) {
812 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
813 Entry entry = { &E, E };
814 Entries.push_back(entry);
815 E = S.stripARCUnbridgedCast(E);
816 }
817
818 void restore() {
819 for (SmallVectorImpl<Entry>::iterator
820 i = Entries.begin(), e = Entries.end(); i != e; ++i)
821 *i->Addr = i->Saved;
822 }
823 };
824}
825
826/// checkPlaceholderForOverload - Do any interesting placeholder-like
827/// preprocessing on the given expression.
828///
829/// \param unbridgedCasts a collection to which to add unbridged casts;
830/// without this, they will be immediately diagnosed as errors
831///
832/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000833static bool
834checkPlaceholderForOverload(Sema &S, Expr *&E,
835 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
837 // We can't handle overloaded expressions here because overload
838 // resolution might reasonably tweak them.
839 if (placeholder->getKind() == BuiltinType::Overload) return false;
840
841 // If the context potentially accepts unbridged ARC casts, strip
842 // the unbridged cast and add it to the collection for later restoration.
843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
844 unbridgedCasts) {
845 unbridgedCasts->save(S, E);
846 return false;
847 }
848
849 // Go ahead and check everything else.
850 ExprResult result = S.CheckPlaceholderExpr(E);
851 if (result.isInvalid())
852 return true;
853
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000854 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000855 return false;
856 }
857
858 // Nothing to do.
859 return false;
860}
861
862/// checkArgPlaceholdersForOverload - Check a set of call operands for
863/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000864static bool checkArgPlaceholdersForOverload(Sema &S,
865 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000866 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000867 for (unsigned i = 0, e = Args.size(); i != e; ++i)
868 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000869 return true;
870
871 return false;
872}
873
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000874// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000875// overload of the declarations in Old. This routine returns false if
876// New and Old cannot be overloaded, e.g., if New has the same
877// signature as some function in Old (C++ 1.3.10) or if the Old
878// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000879// it does return false, MatchedDecl will point to the decl that New
880// cannot be overloaded with. This decl may be a UsingShadowDecl on
881// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000882//
883// Example: Given the following input:
884//
885// void f(int, float); // #1
886// void f(int, int); // #2
887// int f(int, int); // #3
888//
889// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000890// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000891//
John McCall3d988d92009-12-02 08:47:38 +0000892// When we process #2, Old contains only the FunctionDecl for #1. By
893// comparing the parameter types, we see that #1 and #2 are overloaded
894// (since they have different signatures), so this routine returns
895// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896//
John McCall3d988d92009-12-02 08:47:38 +0000897// When we process #3, Old is an overload set containing #1 and #2. We
898// compare the signatures of #3 to #1 (they're overloaded, so we do
899// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
900// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000901// signature), IsOverload returns false and MatchedDecl will be set to
902// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000903//
904// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
905// into a class by a using declaration. The rules for whether to hide
906// shadow declarations ignore some properties which otherwise figure
907// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000908Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000909Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
910 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000911 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000912 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000913 NamedDecl *OldD = *I;
914
915 bool OldIsUsingDecl = false;
916 if (isa<UsingShadowDecl>(OldD)) {
917 OldIsUsingDecl = true;
918
919 // We can always introduce two using declarations into the same
920 // context, even if they have identical signatures.
921 if (NewIsUsingDecl) continue;
922
923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
924 }
925
926 // If either declaration was introduced by a using declaration,
927 // we'll need to use slightly different rules for matching.
928 // Essentially, these rules are the normal rules, except that
929 // function templates hide function templates with different
930 // return types or template parameter lists.
931 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
933 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000934
Alp Tokera2794f92014-01-22 07:29:52 +0000935 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000936 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939 continue;
940 }
941
Alp Tokera2794f92014-01-22 07:29:52 +0000942 if (!isa<FunctionTemplateDecl>(OldD) &&
943 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000944 continue;
945
John McCalldaa3d6b2009-12-09 03:35:25 +0000946 Match = *I;
947 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000948 }
John McCalla8987a2942010-11-10 03:01:53 +0000949 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000950 // We can overload with these, which can show up when doing
951 // redeclaration checks for UsingDecls.
952 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000953 } else if (isa<TagDecl>(OldD)) {
954 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000955 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
956 // Optimistically assume that an unresolved using decl will
957 // overload; if it doesn't, we'll have to diagnose during
958 // template instantiation.
959 } else {
John McCall1f82f242009-11-18 22:49:29 +0000960 // (C++ 13p1):
961 // Only function declarations can be overloaded; object and type
962 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000963 Match = *I;
964 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000965 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000966 }
John McCall1f82f242009-11-18 22:49:29 +0000967
John McCalldaa3d6b2009-12-09 03:35:25 +0000968 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000969}
970
Richard Smithac974a32013-06-30 09:48:50 +0000971bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
972 bool UseUsingDeclRules) {
973 // C++ [basic.start.main]p2: This function shall not be overloaded.
974 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000975 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000976
David Majnemerc729b0b2013-09-16 22:44:20 +0000977 // MSVCRT user defined entry points cannot be overloaded.
978 if (New->isMSVCRTEntryPoint())
979 return false;
980
John McCall1f82f242009-11-18 22:49:29 +0000981 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
982 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
983
984 // C++ [temp.fct]p2:
985 // A function template can be overloaded with other function templates
986 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000987 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000988 return true;
989
990 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000991 QualType OldQType = Context.getCanonicalType(Old->getType());
992 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000993
994 // Compare the signatures (C++ 1.3.10) of the two functions to
995 // determine whether they are overloads. If we find any mismatch
996 // in the signature, they are overloads.
997
998 // If either of these functions is a K&R-style function (no
999 // prototype), then we consider them to have matching signatures.
1000 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1001 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1002 return false;
1003
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001004 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1005 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001006
1007 // The signature of a function includes the types of its
1008 // parameters (C++ 1.3.10), which includes the presence or absence
1009 // of the ellipsis; see C++ DR 357).
1010 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001011 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001012 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001013 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001014 return true;
1015
1016 // C++ [temp.over.link]p4:
1017 // The signature of a function template consists of its function
1018 // signature, its return type and its template parameter list. The names
1019 // of the template parameters are significant only for establishing the
1020 // relationship between the template parameters and the rest of the
1021 // signature.
1022 //
1023 // We check the return type and template parameter lists for function
1024 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001025 //
1026 // However, we don't consider either of these when deciding whether
1027 // a member introduced by a shadow declaration is hidden.
1028 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001029 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1030 OldTemplate->getTemplateParameters(),
1031 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001032 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001033 return true;
1034
1035 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001036 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001037 //
1038 // As part of this, also check whether one of the member functions
1039 // is static, in which case they are not overloads (C++
1040 // 13.1p2). While not part of the definition of the signature,
1041 // this check is important to determine whether these functions
1042 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001043 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1044 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001045 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001046 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1047 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1048 if (!UseUsingDeclRules &&
1049 (OldMethod->getRefQualifier() == RQ_None ||
1050 NewMethod->getRefQualifier() == RQ_None)) {
1051 // C++0x [over.load]p2:
1052 // - Member function declarations with the same name and the same
1053 // parameter-type-list as well as member function template
1054 // declarations with the same name, the same parameter-type-list, and
1055 // the same template parameter lists cannot be overloaded if any of
1056 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001057 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001058 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001059 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001060 }
1061 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001063
Richard Smith574f4f62013-01-14 05:37:29 +00001064 // We may not have applied the implicit const for a constexpr member
1065 // function yet (because we haven't yet resolved whether this is a static
1066 // or non-static member function). Add it now, on the assumption that this
1067 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001068 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001069 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001070 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001071 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001072 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001073
1074 // We do not allow overloading based off of '__restrict'.
1075 OldQuals &= ~Qualifiers::Restrict;
1076 NewQuals &= ~Qualifiers::Restrict;
1077 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001078 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001081 // enable_if attributes are an order-sensitive part of the signature.
1082 for (specific_attr_iterator<EnableIfAttr>
1083 NewI = New->specific_attr_begin<EnableIfAttr>(),
1084 NewE = New->specific_attr_end<EnableIfAttr>(),
1085 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1086 OldE = Old->specific_attr_end<EnableIfAttr>();
1087 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1088 if (NewI == NewE || OldI == OldE)
1089 return true;
1090 llvm::FoldingSetNodeID NewID, OldID;
1091 NewI->getCond()->Profile(NewID, Context, true);
1092 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001093 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001094 return true;
1095 }
1096
John McCall1f82f242009-11-18 22:49:29 +00001097 // The signatures match; this is not an overload.
1098 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001099}
1100
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001101/// \brief Checks availability of the function depending on the current
1102/// function context. Inside an unavailable function, unavailability is ignored.
1103///
1104/// \returns true if \arg FD is unavailable and current context is inside
1105/// an available function, false otherwise.
1106bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1107 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1108}
1109
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001110/// \brief Tries a user-defined conversion from From to ToType.
1111///
1112/// Produces an implicit conversion sequence for when a standard conversion
1113/// is not an option. See TryImplicitConversion for more information.
1114static ImplicitConversionSequence
1115TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1116 bool SuppressUserConversions,
1117 bool AllowExplicit,
1118 bool InOverloadResolution,
1119 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001120 bool AllowObjCWritebackConversion,
1121 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001122 ImplicitConversionSequence ICS;
1123
1124 if (SuppressUserConversions) {
1125 // We're not in the case above, so there is no conversion that
1126 // we can perform.
1127 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1128 return ICS;
1129 }
1130
1131 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001132 OverloadCandidateSet Conversions(From->getExprLoc(),
1133 OverloadCandidateSet::CSK_Normal);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001134 OverloadingResult UserDefResult
1135 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001136 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001137
1138 if (UserDefResult == OR_Success) {
1139 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001140 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001141 // C++ [over.ics.user]p4:
1142 // A conversion of an expression of class type to the same class
1143 // type is given Exact Match rank, and a conversion of an
1144 // expression of class type to a base class of that type is
1145 // given Conversion rank, in spite of the fact that a copy
1146 // constructor (i.e., a user-defined conversion function) is
1147 // called for those cases.
1148 if (CXXConstructorDecl *Constructor
1149 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1150 QualType FromCanon
1151 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1152 QualType ToCanon
1153 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1154 if (Constructor->isCopyConstructor() &&
1155 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1156 // Turn this into a "standard" conversion sequence, so that it
1157 // gets ranked with standard conversion sequences.
1158 ICS.setStandard();
1159 ICS.Standard.setAsIdentityConversion();
1160 ICS.Standard.setFromType(From->getType());
1161 ICS.Standard.setAllToTypes(ToType);
1162 ICS.Standard.CopyConstructor = Constructor;
1163 if (ToCanon != FromCanon)
1164 ICS.Standard.Second = ICK_Derived_To_Base;
1165 }
1166 }
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001167 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1168 ICS.setAmbiguous();
1169 ICS.Ambiguous.setFromType(From->getType());
1170 ICS.Ambiguous.setToType(ToType);
1171 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1172 Cand != Conversions.end(); ++Cand)
1173 if (Cand->Viable)
1174 ICS.Ambiguous.addConversion(Cand->Function);
1175 } else {
1176 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1177 }
1178
1179 return ICS;
1180}
1181
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001182/// TryImplicitConversion - Attempt to perform an implicit conversion
1183/// from the given expression (Expr) to the given type (ToType). This
1184/// function returns an implicit conversion sequence that can be used
1185/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001186///
1187/// void f(float f);
1188/// void g(int i) { f(i); }
1189///
1190/// this routine would produce an implicit conversion sequence to
1191/// describe the initialization of f from i, which will be a standard
1192/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1193/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1194//
1195/// Note that this routine only determines how the conversion can be
1196/// performed; it does not actually perform the conversion. As such,
1197/// it will not produce any diagnostics if no conversion is available,
1198/// but will instead return an implicit conversion sequence of kind
1199/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001200///
1201/// If @p SuppressUserConversions, then user-defined conversions are
1202/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001203/// If @p AllowExplicit, then explicit user-defined conversions are
1204/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001205///
1206/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1207/// writeback conversion, which allows __autoreleasing id* parameters to
1208/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001209static ImplicitConversionSequence
1210TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1211 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001212 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001213 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001214 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001215 bool AllowObjCWritebackConversion,
1216 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001218 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001219 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001220 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001221 return ICS;
1222 }
1223
David Blaikiebbafb8a2012-03-11 07:00:24 +00001224 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001226 return ICS;
1227 }
1228
Douglas Gregor836a7e82010-08-11 02:15:33 +00001229 // C++ [over.ics.user]p4:
1230 // A conversion of an expression of class type to the same class
1231 // type is given Exact Match rank, and a conversion of an
1232 // expression of class type to a base class of that type is
1233 // given Conversion rank, in spite of the fact that a copy/move
1234 // constructor (i.e., a user-defined conversion function) is
1235 // called for those cases.
1236 QualType FromType = From->getType();
1237 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001238 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1239 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001240 ICS.setStandard();
1241 ICS.Standard.setAsIdentityConversion();
1242 ICS.Standard.setFromType(FromType);
1243 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244
Douglas Gregor5ab11652010-04-17 22:01:05 +00001245 // We don't actually check at this point whether there is a valid
1246 // copy/move constructor, since overloading just assumes that it
1247 // exists. When we actually perform initialization, we'll find the
1248 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001249 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250
Douglas Gregor5ab11652010-04-17 22:01:05 +00001251 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001252 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001253 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
Douglas Gregor836a7e82010-08-11 02:15:33 +00001255 return ICS;
1256 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001257
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001258 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1259 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001260 AllowObjCWritebackConversion,
1261 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001262}
1263
John McCall31168b02011-06-15 23:02:42 +00001264ImplicitConversionSequence
1265Sema::TryImplicitConversion(Expr *From, QualType ToType,
1266 bool SuppressUserConversions,
1267 bool AllowExplicit,
1268 bool InOverloadResolution,
1269 bool CStyle,
1270 bool AllowObjCWritebackConversion) {
1271 return clang::TryImplicitConversion(*this, From, ToType,
1272 SuppressUserConversions, AllowExplicit,
1273 InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001274 AllowObjCWritebackConversion,
1275 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001276}
1277
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001278/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001279/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001280/// converted expression. Flavor is the kind of conversion we're
1281/// performing, used in the error message. If @p AllowExplicit,
1282/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001283ExprResult
1284Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001285 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001286 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001287 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001288}
1289
John Wiegley01296292011-04-08 18:41:53 +00001290ExprResult
1291Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001292 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001293 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001294 if (checkPlaceholderForOverload(*this, From))
1295 return ExprError();
1296
John McCall31168b02011-06-15 23:02:42 +00001297 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1298 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001299 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001300 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001301 if (getLangOpts().ObjC1)
1302 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1303 ToType, From->getType(), From);
John McCall5c32be02010-08-24 20:38:10 +00001304 ICS = clang::TryImplicitConversion(*this, From, ToType,
1305 /*SuppressUserConversions=*/false,
1306 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001307 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001308 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001309 AllowObjCWritebackConversion,
1310 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001311 return PerformImplicitConversion(From, ToType, ICS, Action);
1312}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313
1314/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001315/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001316bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1317 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001318 if (Context.hasSameUnqualifiedType(FromType, ToType))
1319 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320
John McCall991eb4b2010-12-21 00:44:39 +00001321 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1322 // where F adds one of the following at most once:
1323 // - a pointer
1324 // - a member pointer
1325 // - a block pointer
1326 CanQualType CanTo = Context.getCanonicalType(ToType);
1327 CanQualType CanFrom = Context.getCanonicalType(FromType);
1328 Type::TypeClass TyClass = CanTo->getTypeClass();
1329 if (TyClass != CanFrom->getTypeClass()) return false;
1330 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1331 if (TyClass == Type::Pointer) {
1332 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1333 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1334 } else if (TyClass == Type::BlockPointer) {
1335 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1336 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1337 } else if (TyClass == Type::MemberPointer) {
1338 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1339 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1340 } else {
1341 return false;
1342 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001343
John McCall991eb4b2010-12-21 00:44:39 +00001344 TyClass = CanTo->getTypeClass();
1345 if (TyClass != CanFrom->getTypeClass()) return false;
1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1347 return false;
1348 }
1349
1350 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1351 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1352 if (!EInfo.getNoReturn()) return false;
1353
1354 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1355 assert(QualType(FromFn, 0).isCanonical());
1356 if (QualType(FromFn, 0) != CanTo) return false;
1357
1358 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001359 return true;
1360}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361
Douglas Gregor46188682010-05-18 22:42:18 +00001362/// \brief Determine whether the conversion from FromType to ToType is a valid
1363/// vector conversion.
1364///
1365/// \param ICK Will be set to the vector conversion kind, if this is a vector
1366/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001367static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001369 // We need at least one of these types to be a vector type to have a vector
1370 // conversion.
1371 if (!ToType->isVectorType() && !FromType->isVectorType())
1372 return false;
1373
1374 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001375 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001376 return false;
1377
1378 // There are no conversions between extended vector types, only identity.
1379 if (ToType->isExtVectorType()) {
1380 // There are no conversions between extended vector types other than the
1381 // identity conversion.
1382 if (FromType->isExtVectorType())
1383 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384
Douglas Gregor46188682010-05-18 22:42:18 +00001385 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001386 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001387 ICK = ICK_Vector_Splat;
1388 return true;
1389 }
1390 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001391
1392 // We can perform the conversion between vector types in the following cases:
1393 // 1)vector types are equivalent AltiVec and GCC vector types
1394 // 2)lax vector conversions are permitted and the vector types are of the
1395 // same size
1396 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001397 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1398 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001399 ICK = ICK_Vector_Conversion;
1400 return true;
1401 }
Douglas Gregor46188682010-05-18 22:42:18 +00001402 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001403
Douglas Gregor46188682010-05-18 22:42:18 +00001404 return false;
1405}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001407static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1408 bool InOverloadResolution,
1409 StandardConversionSequence &SCS,
1410 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001411
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001412/// IsStandardConversion - Determines whether there is a standard
1413/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1414/// expression From to the type ToType. Standard conversion sequences
1415/// only consider non-class types; for conversions that involve class
1416/// types, use TryImplicitConversion. If a conversion exists, SCS will
1417/// contain the standard conversion sequence required to perform this
1418/// conversion and this routine will return true. Otherwise, this
1419/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001420static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1421 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001422 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001423 bool CStyle,
1424 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001425 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001426
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001427 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001428 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001429 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001430 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001431 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001432
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001433 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001434 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001435 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001436 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001437 return false;
1438
Mike Stump11289f42009-09-09 15:08:12 +00001439 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001440 }
1441
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001442 // The first conversion can be an lvalue-to-rvalue conversion,
1443 // array-to-pointer conversion, or function-to-pointer conversion
1444 // (C++ 4p1).
1445
John McCall5c32be02010-08-24 20:38:10 +00001446 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001447 DeclAccessPair AccessPair;
1448 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001449 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001450 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001451 // We were able to resolve the address of the overloaded function,
1452 // so we can convert to the type of that function.
1453 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001454 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001455
1456 // we can sometimes resolve &foo<int> regardless of ToType, so check
1457 // if the type matches (identity) or we are converting to bool
1458 if (!S.Context.hasSameUnqualifiedType(
1459 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1460 QualType resultTy;
1461 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001462 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001463 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1464 // otherwise, only a boolean conversion is standard
1465 if (!ToType->isBooleanType())
1466 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
Chandler Carruthffce2452011-03-29 08:08:18 +00001469 // Check if the "from" expression is taking the address of an overloaded
1470 // function and recompute the FromType accordingly. Take advantage of the
1471 // fact that non-static member functions *must* have such an address-of
1472 // expression.
1473 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1474 if (Method && !Method->isStatic()) {
1475 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1476 "Non-unary operator on non-static member address");
1477 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1478 == UO_AddrOf &&
1479 "Non-address-of operator on non-static member address");
1480 const Type *ClassType
1481 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1482 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001483 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1484 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1485 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001486 "Non-address-of operator for overloaded function expression");
1487 FromType = S.Context.getPointerType(FromType);
1488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489
Douglas Gregor980fb162010-04-29 18:24:40 +00001490 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001491 assert(S.Context.hasSameType(
1492 FromType,
1493 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001494 } else {
1495 return false;
1496 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001497 }
John McCall154a2fd2011-08-30 00:57:29 +00001498 // Lvalue-to-rvalue conversion (C++11 4.1):
1499 // A glvalue (3.10) of a non-function, non-array type T can
1500 // be converted to a prvalue.
1501 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001502 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001503 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001504 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001505 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001506
Douglas Gregorc79862f2012-04-12 17:51:55 +00001507 // C11 6.3.2.1p2:
1508 // ... if the lvalue has atomic type, the value has the non-atomic version
1509 // of the type of the lvalue ...
1510 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1511 FromType = Atomic->getValueType();
1512
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001513 // If T is a non-class type, the type of the rvalue is the
1514 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001515 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1516 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001517 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001518 } else if (FromType->isArrayType()) {
1519 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001520 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001521
1522 // An lvalue or rvalue of type "array of N T" or "array of unknown
1523 // bound of T" can be converted to an rvalue of type "pointer to
1524 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001525 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001526
John McCall5c32be02010-08-24 20:38:10 +00001527 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001528 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001529 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001530
1531 // For the purpose of ranking in overload resolution
1532 // (13.3.3.1.1), this conversion is considered an
1533 // array-to-pointer conversion followed by a qualification
1534 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001535 SCS.Second = ICK_Identity;
1536 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001537 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001538 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001540 }
John McCall086a4642010-11-24 05:12:34 +00001541 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001542 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001543 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001544
1545 // An lvalue of function type T can be converted to an rvalue of
1546 // type "pointer to T." The result is a pointer to the
1547 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001548 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001549 } else {
1550 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001551 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001552 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001553 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001554
1555 // The second conversion can be an integral promotion, floating
1556 // point promotion, integral conversion, floating point conversion,
1557 // floating-integral conversion, pointer conversion,
1558 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001559 // For overloading in C, this can also be a "compatible-type"
1560 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001561 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001562 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001563 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001564 // The unqualified versions of the types are the same: there's no
1565 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001567 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001568 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001569 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001570 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001571 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001572 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001573 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001575 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001576 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001577 SCS.Second = ICK_Complex_Promotion;
1578 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001579 } else if (ToType->isBooleanType() &&
1580 (FromType->isArithmeticType() ||
1581 FromType->isAnyPointerType() ||
1582 FromType->isBlockPointerType() ||
1583 FromType->isMemberPointerType() ||
1584 FromType->isNullPtrType())) {
1585 // Boolean conversions (C++ 4.12).
1586 SCS.Second = ICK_Boolean_Conversion;
1587 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001588 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001589 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001590 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001591 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001592 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001593 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001594 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001595 SCS.Second = ICK_Complex_Conversion;
1596 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001597 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1598 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001599 // Complex-real conversions (C99 6.3.1.7)
1600 SCS.Second = ICK_Complex_Real;
1601 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001602 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001603 // Floating point conversions (C++ 4.8).
1604 SCS.Second = ICK_Floating_Conversion;
1605 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001606 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001607 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001608 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001609 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001610 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001611 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001613 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001614 SCS.Second = ICK_Block_Pointer_Conversion;
1615 } else if (AllowObjCWritebackConversion &&
1616 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1617 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001618 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1619 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001620 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001621 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001622 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001623 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001624 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001625 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001626 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001627 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001628 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001629 SCS.Second = SecondICK;
1630 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001631 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001632 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001633 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001634 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001635 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001636 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001637 // Treat a conversion that strips "noreturn" as an identity conversion.
1638 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001639 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1640 InOverloadResolution,
1641 SCS, CStyle)) {
1642 SCS.Second = ICK_TransparentUnionConversion;
1643 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001644 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1645 CStyle)) {
1646 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001647 // appropriately.
1648 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001649 } else if (ToType->isEventT() &&
1650 From->isIntegerConstantExpr(S.getASTContext()) &&
1651 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1652 SCS.Second = ICK_Zero_Event_Conversion;
1653 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001654 } else {
1655 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001656 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001658 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001660 QualType CanonFrom;
1661 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001663 bool ObjCLifetimeConversion;
1664 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1665 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001666 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001667 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001669 CanonFrom = S.Context.getCanonicalType(FromType);
1670 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 } else {
1672 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.Third = ICK_Identity;
1674
Mike Stump11289f42009-09-09 15:08:12 +00001675 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001676 // [...] Any difference in top-level cv-qualification is
1677 // subsumed by the initialization itself and does not constitute
1678 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001679 CanonFrom = S.Context.getCanonicalType(FromType);
1680 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001681 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001682 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001683 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001684 FromType = ToType;
1685 CanonFrom = CanonTo;
1686 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001688 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001689
1690 // If we have not converted the argument type to the parameter type,
1691 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001692 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001695 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001696}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001697
1698static bool
1699IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1700 QualType &ToType,
1701 bool InOverloadResolution,
1702 StandardConversionSequence &SCS,
1703 bool CStyle) {
1704
1705 const RecordType *UT = ToType->getAsUnionType();
1706 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1707 return false;
1708 // The field to initialize within the transparent union.
1709 RecordDecl *UD = UT->getDecl();
1710 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001711 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001712 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1713 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001714 ToType = it->getType();
1715 return true;
1716 }
1717 }
1718 return false;
1719}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001720
1721/// IsIntegralPromotion - Determines whether the conversion from the
1722/// expression From (whose potentially-adjusted type is FromType) to
1723/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1724/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001725bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001726 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001727 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001728 if (!To) {
1729 return false;
1730 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001731
1732 // An rvalue of type char, signed char, unsigned char, short int, or
1733 // unsigned short int can be converted to an rvalue of type int if
1734 // int can represent all the values of the source type; otherwise,
1735 // the source rvalue can be converted to an rvalue of type unsigned
1736 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001737 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1738 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739 if (// We can promote any signed, promotable integer type to an int
1740 (FromType->isSignedIntegerType() ||
1741 // We can promote any unsigned integer type whose size is
1742 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001743 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001744 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001745 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001746 }
1747
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 return To->getKind() == BuiltinType::UInt;
1749 }
1750
Richard Smithb9c5a602012-09-13 21:18:54 +00001751 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001752 // A prvalue of an unscoped enumeration type whose underlying type is not
1753 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1754 // following types that can represent all the values of the enumeration
1755 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1756 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001757 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001758 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001759 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001760 // with lowest integer conversion rank (4.13) greater than the rank of long
1761 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001762 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001763 // C++11 [conv.prom]p4:
1764 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1765 // can be converted to a prvalue of its underlying type. Moreover, if
1766 // integral promotion can be applied to its underlying type, a prvalue of an
1767 // unscoped enumeration type whose underlying type is fixed can also be
1768 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001769 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1770 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1771 // provided for a scoped enumeration.
1772 if (FromEnumType->getDecl()->isScoped())
1773 return false;
1774
Richard Smithb9c5a602012-09-13 21:18:54 +00001775 // We can perform an integral promotion to the underlying type of the enum,
1776 // even if that's not the promoted type.
1777 if (FromEnumType->getDecl()->isFixed()) {
1778 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1779 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1780 IsIntegralPromotion(From, Underlying, ToType);
1781 }
1782
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001783 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001785 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001786 return Context.hasSameUnqualifiedType(ToType,
1787 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001788 }
John McCall56774992009-12-09 09:09:27 +00001789
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001790 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001791 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1792 // to an rvalue a prvalue of the first of the following types that can
1793 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001794 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001795 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001796 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001797 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001798 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001799 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001800 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001801 // Determine whether the type we're converting from is signed or
1802 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001803 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001804 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001806 // The types we'll try to promote to, in the appropriate
1807 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001808 QualType PromoteTypes[6] = {
1809 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001810 Context.LongTy, Context.UnsignedLongTy ,
1811 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001812 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001813 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001814 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1815 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001816 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1818 // We found the type that we can promote to. If this is the
1819 // type we wanted, we have a promotion. Otherwise, no
1820 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001821 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001822 }
1823 }
1824 }
1825
1826 // An rvalue for an integral bit-field (9.6) can be converted to an
1827 // rvalue of type int if int can represent all the values of the
1828 // bit-field; otherwise, it can be converted to unsigned int if
1829 // unsigned int can represent all the values of the bit-field. If
1830 // the bit-field is larger yet, no integral promotion applies to
1831 // it. If the bit-field has an enumerated type, it is treated as any
1832 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001833 // FIXME: We should delay checking of bit-fields until we actually perform the
1834 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001835 using llvm::APSInt;
1836 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001837 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001838 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001839 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001840 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1841 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1842 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001843
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001844 // Are we promoting to an int from a bitfield that fits in an int?
1845 if (BitWidth < ToSize ||
1846 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1847 return To->getKind() == BuiltinType::Int;
1848 }
Mike Stump11289f42009-09-09 15:08:12 +00001849
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001850 // Are we promoting to an unsigned int from an unsigned bitfield
1851 // that fits into an unsigned int?
1852 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1853 return To->getKind() == BuiltinType::UInt;
1854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001856 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001857 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001858 }
Mike Stump11289f42009-09-09 15:08:12 +00001859
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001860 // An rvalue of type bool can be converted to an rvalue of type int,
1861 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001862 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001863 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001864 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001865
1866 return false;
1867}
1868
1869/// IsFloatingPointPromotion - Determines whether the conversion from
1870/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1871/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001872bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001873 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1874 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001875 /// An rvalue of type float can be converted to an rvalue of type
1876 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001877 if (FromBuiltin->getKind() == BuiltinType::Float &&
1878 ToBuiltin->getKind() == BuiltinType::Double)
1879 return true;
1880
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001881 // C99 6.3.1.5p1:
1882 // When a float is promoted to double or long double, or a
1883 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001884 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001885 (FromBuiltin->getKind() == BuiltinType::Float ||
1886 FromBuiltin->getKind() == BuiltinType::Double) &&
1887 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1888 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001889
1890 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001891 if (!getLangOpts().NativeHalfType &&
1892 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001893 ToBuiltin->getKind() == BuiltinType::Float)
1894 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001895 }
1896
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001897 return false;
1898}
1899
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001900/// \brief Determine if a conversion is a complex promotion.
1901///
1902/// A complex promotion is defined as a complex -> complex conversion
1903/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001904/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001905bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001906 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001907 if (!FromComplex)
1908 return false;
1909
John McCall9dd450b2009-09-21 23:43:11 +00001910 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001911 if (!ToComplex)
1912 return false;
1913
1914 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001915 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001916 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001917 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001918}
1919
Douglas Gregor237f96c2008-11-26 23:31:11 +00001920/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1921/// the pointer type FromPtr to a pointer to type ToPointee, with the
1922/// same type qualifiers as FromPtr has on its pointee type. ToType,
1923/// if non-empty, will be a pointer to ToType that may or may not have
1924/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001925///
Mike Stump11289f42009-09-09 15:08:12 +00001926static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001927BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001928 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001929 ASTContext &Context,
1930 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001931 assert((FromPtr->getTypeClass() == Type::Pointer ||
1932 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1933 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001934
John McCall31168b02011-06-15 23:02:42 +00001935 /// Conversions to 'id' subsume cv-qualifier conversions.
1936 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001937 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938
1939 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001940 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001941 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001942 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001943
John McCall31168b02011-06-15 23:02:42 +00001944 if (StripObjCLifetime)
1945 Quals.removeObjCLifetime();
1946
Mike Stump11289f42009-09-09 15:08:12 +00001947 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001948 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001949 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001950 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001951 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001952
1953 // Build a pointer to ToPointee. It has the right qualifiers
1954 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001955 if (isa<ObjCObjectPointerType>(ToType))
1956 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001957 return Context.getPointerType(ToPointee);
1958 }
1959
1960 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001961 QualType QualifiedCanonToPointee
1962 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001964 if (isa<ObjCObjectPointerType>(ToType))
1965 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1966 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001967}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968
Mike Stump11289f42009-09-09 15:08:12 +00001969static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001970 bool InOverloadResolution,
1971 ASTContext &Context) {
1972 // Handle value-dependent integral null pointer constants correctly.
1973 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1974 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001975 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001976 return !InOverloadResolution;
1977
Douglas Gregor56751b52009-09-25 04:25:58 +00001978 return Expr->isNullPointerConstant(Context,
1979 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1980 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001981}
Mike Stump11289f42009-09-09 15:08:12 +00001982
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001983/// IsPointerConversion - Determines whether the conversion of the
1984/// expression From, which has the (possibly adjusted) type FromType,
1985/// can be converted to the type ToType via a pointer conversion (C++
1986/// 4.10). If so, returns true and places the converted type (that
1987/// might differ from ToType in its cv-qualifiers at some level) into
1988/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001989///
Douglas Gregora29dc052008-11-27 01:19:21 +00001990/// This routine also supports conversions to and from block pointers
1991/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1992/// pointers to interfaces. FIXME: Once we've determined the
1993/// appropriate overloading rules for Objective-C, we may want to
1994/// split the Objective-C checks into a different routine; however,
1995/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001996/// conversions, so for now they live here. IncompatibleObjC will be
1997/// set if the conversion is an allowed Objective-C conversion that
1998/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001999bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002000 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002001 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002002 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002003 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002004 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2005 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002006 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002007
Mike Stump11289f42009-09-09 15:08:12 +00002008 // Conversion from a null pointer constant to any Objective-C pointer type.
2009 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002010 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002011 ConvertedType = ToType;
2012 return true;
2013 }
2014
Douglas Gregor231d1c62008-11-27 00:15:41 +00002015 // Blocks: Block pointers can be converted to void*.
2016 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002017 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002018 ConvertedType = ToType;
2019 return true;
2020 }
2021 // Blocks: A null pointer constant can be converted to a block
2022 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002023 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002024 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002025 ConvertedType = ToType;
2026 return true;
2027 }
2028
Sebastian Redl576fd422009-05-10 18:38:11 +00002029 // If the left-hand-side is nullptr_t, the right side can be a null
2030 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002031 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002032 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002033 ConvertedType = ToType;
2034 return true;
2035 }
2036
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002038 if (!ToTypePtr)
2039 return false;
2040
2041 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002042 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002043 ConvertedType = ToType;
2044 return true;
2045 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002046
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002048 // , including objective-c pointers.
2049 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002050 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002051 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002052 ConvertedType = BuildSimilarlyQualifiedPointerType(
2053 FromType->getAs<ObjCObjectPointerType>(),
2054 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002055 ToType, Context);
2056 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002057 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002058 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002059 if (!FromTypePtr)
2060 return false;
2061
2062 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002063
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002064 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002065 // pointer conversion, so don't do all of the work below.
2066 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2067 return false;
2068
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069 // An rvalue of type "pointer to cv T," where T is an object type,
2070 // can be converted to an rvalue of type "pointer to cv void" (C++
2071 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002072 if (FromPointeeType->isIncompleteOrObjectType() &&
2073 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002074 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002075 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002076 ToType, Context,
2077 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002078 return true;
2079 }
2080
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002081 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002082 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002083 ToPointeeType->isVoidType()) {
2084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2085 ToPointeeType,
2086 ToType, Context);
2087 return true;
2088 }
2089
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002090 // When we're overloading in C, we allow a special kind of pointer
2091 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002092 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002093 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002094 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002095 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002096 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002097 return true;
2098 }
2099
Douglas Gregor5c407d92008-10-23 00:40:37 +00002100 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002101 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002102 // An rvalue of type "pointer to cv D," where D is a class type,
2103 // can be converted to an rvalue of type "pointer to cv B," where
2104 // B is a base class (clause 10) of D. If B is an inaccessible
2105 // (clause 11) or ambiguous (10.2) base class of D, a program that
2106 // necessitates this conversion is ill-formed. The result of the
2107 // conversion is a pointer to the base class sub-object of the
2108 // derived class object. The null pointer value is converted to
2109 // the null pointer value of the destination type.
2110 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002111 // Note that we do not check for ambiguity or inaccessibility
2112 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002113 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002114 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002115 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002116 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002117 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002118 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002119 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002120 ToType, Context);
2121 return true;
2122 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002123
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002124 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2125 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2126 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2127 ToPointeeType,
2128 ToType, Context);
2129 return true;
2130 }
2131
Douglas Gregora119f102008-12-19 19:13:09 +00002132 return false;
2133}
Douglas Gregoraec25842011-04-26 23:16:46 +00002134
2135/// \brief Adopt the given qualifiers for the given type.
2136static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2137 Qualifiers TQs = T.getQualifiers();
2138
2139 // Check whether qualifiers already match.
2140 if (TQs == Qs)
2141 return T;
2142
2143 if (Qs.compatiblyIncludes(TQs))
2144 return Context.getQualifiedType(T, Qs);
2145
2146 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2147}
Douglas Gregora119f102008-12-19 19:13:09 +00002148
2149/// isObjCPointerConversion - Determines whether this is an
2150/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2151/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002152bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002153 QualType& ConvertedType,
2154 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002155 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002156 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002157
Douglas Gregoraec25842011-04-26 23:16:46 +00002158 // The set of qualifiers on the type we're converting from.
2159 Qualifiers FromQualifiers = FromType.getQualifiers();
2160
Steve Naroff7cae42b2009-07-10 23:34:53 +00002161 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002162 const ObjCObjectPointerType* ToObjCPtr =
2163 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002164 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002165 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002166
Steve Naroff7cae42b2009-07-10 23:34:53 +00002167 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002168 // If the pointee types are the same (ignoring qualifications),
2169 // then this is not a pointer conversion.
2170 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2171 FromObjCPtr->getPointeeType()))
2172 return false;
2173
Douglas Gregoraec25842011-04-26 23:16:46 +00002174 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002175 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002176 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002177 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002178 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002179 return true;
2180 }
2181 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002182 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002183 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002184 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002185 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002186 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002187 return true;
2188 }
2189 // Objective C++: We're able to convert from a pointer to an
2190 // interface to a pointer to a different interface.
2191 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002192 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2193 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002194 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002195 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2196 FromObjCPtr->getPointeeType()))
2197 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002199 ToObjCPtr->getPointeeType(),
2200 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002201 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002202 return true;
2203 }
2204
2205 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2206 // Okay: this is some kind of implicit downcast of Objective-C
2207 // interfaces, which is permitted. However, we're going to
2208 // complain about it.
2209 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002211 ToObjCPtr->getPointeeType(),
2212 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002213 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002214 return true;
2215 }
Mike Stump11289f42009-09-09 15:08:12 +00002216 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002217 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002218 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002219 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002220 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002221 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002222 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002223 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002224 // to a block pointer type.
2225 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002226 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002227 return true;
2228 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002229 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002230 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002231 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002232 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002233 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002234 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002236 return true;
2237 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002238 else
Douglas Gregora119f102008-12-19 19:13:09 +00002239 return false;
2240
Douglas Gregor033f56d2008-12-23 00:53:59 +00002241 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002242 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002243 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002244 else if (const BlockPointerType *FromBlockPtr =
2245 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002246 FromPointeeType = FromBlockPtr->getPointeeType();
2247 else
Douglas Gregora119f102008-12-19 19:13:09 +00002248 return false;
2249
Douglas Gregora119f102008-12-19 19:13:09 +00002250 // If we have pointers to pointers, recursively check whether this
2251 // is an Objective-C conversion.
2252 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2253 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2254 IncompatibleObjC)) {
2255 // We always complain about this conversion.
2256 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002257 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002258 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002259 return true;
2260 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002261 // Allow conversion of pointee being objective-c pointer to another one;
2262 // as in I* to id.
2263 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2264 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2265 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2266 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002267
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002268 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002269 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002270 return true;
2271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002272
Douglas Gregor033f56d2008-12-23 00:53:59 +00002273 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002274 // differences in the argument and result types are in Objective-C
2275 // pointer conversions. If so, we permit the conversion (but
2276 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002277 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002278 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002279 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002280 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002281 if (FromFunctionType && ToFunctionType) {
2282 // If the function types are exactly the same, this isn't an
2283 // Objective-C pointer conversion.
2284 if (Context.getCanonicalType(FromPointeeType)
2285 == Context.getCanonicalType(ToPointeeType))
2286 return false;
2287
2288 // Perform the quick checks that will tell us whether these
2289 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002290 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002291 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2292 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2293 return false;
2294
2295 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002296 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2297 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002298 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002299 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2300 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002301 ConvertedType, IncompatibleObjC)) {
2302 // Okay, we have an Objective-C pointer conversion.
2303 HasObjCConversion = true;
2304 } else {
2305 // Function types are too different. Abort.
2306 return false;
2307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
Douglas Gregora119f102008-12-19 19:13:09 +00002309 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002310 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002311 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002312 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2313 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002314 if (Context.getCanonicalType(FromArgType)
2315 == Context.getCanonicalType(ToArgType)) {
2316 // Okay, the types match exactly. Nothing to do.
2317 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2318 ConvertedType, IncompatibleObjC)) {
2319 // Okay, we have an Objective-C pointer conversion.
2320 HasObjCConversion = true;
2321 } else {
2322 // Argument types are too different. Abort.
2323 return false;
2324 }
2325 }
2326
2327 if (HasObjCConversion) {
2328 // We had an Objective-C conversion. Allow this pointer
2329 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002330 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002331 IncompatibleObjC = true;
2332 return true;
2333 }
2334 }
2335
Sebastian Redl72b597d2009-01-25 19:43:20 +00002336 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002337}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002338
John McCall31168b02011-06-15 23:02:42 +00002339/// \brief Determine whether this is an Objective-C writeback conversion,
2340/// used for parameter passing when performing automatic reference counting.
2341///
2342/// \param FromType The type we're converting form.
2343///
2344/// \param ToType The type we're converting to.
2345///
2346/// \param ConvertedType The type that will be produced after applying
2347/// this conversion.
2348bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2349 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002350 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002351 Context.hasSameUnqualifiedType(FromType, ToType))
2352 return false;
2353
2354 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2355 QualType ToPointee;
2356 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2357 ToPointee = ToPointer->getPointeeType();
2358 else
2359 return false;
2360
2361 Qualifiers ToQuals = ToPointee.getQualifiers();
2362 if (!ToPointee->isObjCLifetimeType() ||
2363 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002364 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002365 return false;
2366
2367 // Argument must be a pointer to __strong to __weak.
2368 QualType FromPointee;
2369 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2370 FromPointee = FromPointer->getPointeeType();
2371 else
2372 return false;
2373
2374 Qualifiers FromQuals = FromPointee.getQualifiers();
2375 if (!FromPointee->isObjCLifetimeType() ||
2376 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2377 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2378 return false;
2379
2380 // Make sure that we have compatible qualifiers.
2381 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2382 if (!ToQuals.compatiblyIncludes(FromQuals))
2383 return false;
2384
2385 // Remove qualifiers from the pointee type we're converting from; they
2386 // aren't used in the compatibility check belong, and we'll be adding back
2387 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2388 FromPointee = FromPointee.getUnqualifiedType();
2389
2390 // The unqualified form of the pointee types must be compatible.
2391 ToPointee = ToPointee.getUnqualifiedType();
2392 bool IncompatibleObjC;
2393 if (Context.typesAreCompatible(FromPointee, ToPointee))
2394 FromPointee = ToPointee;
2395 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2396 IncompatibleObjC))
2397 return false;
2398
2399 /// \brief Construct the type we're converting to, which is a pointer to
2400 /// __autoreleasing pointee.
2401 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2402 ConvertedType = Context.getPointerType(FromPointee);
2403 return true;
2404}
2405
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002406bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2407 QualType& ConvertedType) {
2408 QualType ToPointeeType;
2409 if (const BlockPointerType *ToBlockPtr =
2410 ToType->getAs<BlockPointerType>())
2411 ToPointeeType = ToBlockPtr->getPointeeType();
2412 else
2413 return false;
2414
2415 QualType FromPointeeType;
2416 if (const BlockPointerType *FromBlockPtr =
2417 FromType->getAs<BlockPointerType>())
2418 FromPointeeType = FromBlockPtr->getPointeeType();
2419 else
2420 return false;
2421 // We have pointer to blocks, check whether the only
2422 // differences in the argument and result types are in Objective-C
2423 // pointer conversions. If so, we permit the conversion.
2424
2425 const FunctionProtoType *FromFunctionType
2426 = FromPointeeType->getAs<FunctionProtoType>();
2427 const FunctionProtoType *ToFunctionType
2428 = ToPointeeType->getAs<FunctionProtoType>();
2429
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002430 if (!FromFunctionType || !ToFunctionType)
2431 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002432
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002433 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002434 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002435
2436 // Perform the quick checks that will tell us whether these
2437 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002438 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002439 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2440 return false;
2441
2442 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2443 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2444 if (FromEInfo != ToEInfo)
2445 return false;
2446
2447 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002448 if (Context.hasSameType(FromFunctionType->getReturnType(),
2449 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002450 // Okay, the types match exactly. Nothing to do.
2451 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002452 QualType RHS = FromFunctionType->getReturnType();
2453 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002454 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002455 !RHS.hasQualifiers() && LHS.hasQualifiers())
2456 LHS = LHS.getUnqualifiedType();
2457
2458 if (Context.hasSameType(RHS,LHS)) {
2459 // OK exact match.
2460 } else if (isObjCPointerConversion(RHS, LHS,
2461 ConvertedType, IncompatibleObjC)) {
2462 if (IncompatibleObjC)
2463 return false;
2464 // Okay, we have an Objective-C pointer conversion.
2465 }
2466 else
2467 return false;
2468 }
2469
2470 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002471 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002472 ArgIdx != NumArgs; ++ArgIdx) {
2473 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002474 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2475 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002476 if (Context.hasSameType(FromArgType, ToArgType)) {
2477 // Okay, the types match exactly. Nothing to do.
2478 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2479 ConvertedType, IncompatibleObjC)) {
2480 if (IncompatibleObjC)
2481 return false;
2482 // Okay, we have an Objective-C pointer conversion.
2483 } else
2484 // Argument types are too different. Abort.
2485 return false;
2486 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002487 if (LangOpts.ObjCAutoRefCount &&
2488 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2489 ToFunctionType))
2490 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002491
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002492 ConvertedType = ToType;
2493 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002494}
2495
Richard Trieucaff2472011-11-23 22:32:32 +00002496enum {
2497 ft_default,
2498 ft_different_class,
2499 ft_parameter_arity,
2500 ft_parameter_mismatch,
2501 ft_return_type,
2502 ft_qualifer_mismatch
2503};
2504
2505/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2506/// function types. Catches different number of parameter, mismatch in
2507/// parameter types, and different return types.
2508void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2509 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002510 // If either type is not valid, include no extra info.
2511 if (FromType.isNull() || ToType.isNull()) {
2512 PDiag << ft_default;
2513 return;
2514 }
2515
Richard Trieucaff2472011-11-23 22:32:32 +00002516 // Get the function type from the pointers.
2517 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2518 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2519 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002520 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002521 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2522 << QualType(FromMember->getClass(), 0);
2523 return;
2524 }
2525 FromType = FromMember->getPointeeType();
2526 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002527 }
2528
Richard Trieu96ed5b62011-12-13 23:19:45 +00002529 if (FromType->isPointerType())
2530 FromType = FromType->getPointeeType();
2531 if (ToType->isPointerType())
2532 ToType = ToType->getPointeeType();
2533
2534 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002535 FromType = FromType.getNonReferenceType();
2536 ToType = ToType.getNonReferenceType();
2537
Richard Trieucaff2472011-11-23 22:32:32 +00002538 // Don't print extra info for non-specialized template functions.
2539 if (FromType->isInstantiationDependentType() &&
2540 !FromType->getAs<TemplateSpecializationType>()) {
2541 PDiag << ft_default;
2542 return;
2543 }
2544
Richard Trieu96ed5b62011-12-13 23:19:45 +00002545 // No extra info for same types.
2546 if (Context.hasSameType(FromType, ToType)) {
2547 PDiag << ft_default;
2548 return;
2549 }
2550
Richard Trieucaff2472011-11-23 22:32:32 +00002551 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2552 *ToFunction = ToType->getAs<FunctionProtoType>();
2553
2554 // Both types need to be function types.
2555 if (!FromFunction || !ToFunction) {
2556 PDiag << ft_default;
2557 return;
2558 }
2559
Alp Toker9cacbab2014-01-20 20:26:09 +00002560 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2561 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2562 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002563 return;
2564 }
2565
2566 // Handle different parameter types.
2567 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002568 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002569 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002570 << ToFunction->getParamType(ArgPos)
2571 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002572 return;
2573 }
2574
2575 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002576 if (!Context.hasSameType(FromFunction->getReturnType(),
2577 ToFunction->getReturnType())) {
2578 PDiag << ft_return_type << ToFunction->getReturnType()
2579 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002580 return;
2581 }
2582
2583 unsigned FromQuals = FromFunction->getTypeQuals(),
2584 ToQuals = ToFunction->getTypeQuals();
2585 if (FromQuals != ToQuals) {
2586 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2587 return;
2588 }
2589
2590 // Unable to find a difference, so add no extra info.
2591 PDiag << ft_default;
2592}
2593
Alp Toker9cacbab2014-01-20 20:26:09 +00002594/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002595/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002596/// they have same number of arguments. If the parameters are different,
2597/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002598bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2599 const FunctionProtoType *NewType,
2600 unsigned *ArgPos) {
2601 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2602 N = NewType->param_type_begin(),
2603 E = OldType->param_type_end();
2604 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002605 if (!Context.hasSameType(O->getUnqualifiedType(),
2606 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002607 if (ArgPos)
2608 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002609 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002610 }
2611 }
2612 return true;
2613}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002614
Douglas Gregor39c16d42008-10-24 04:54:22 +00002615/// CheckPointerConversion - Check the pointer conversion from the
2616/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002617/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002618/// conversions for which IsPointerConversion has already returned
2619/// true. It returns true and produces a diagnostic if there was an
2620/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002621bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002622 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002623 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002624 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002625 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002626 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002627
John McCall8cb679e2010-11-15 09:13:47 +00002628 Kind = CK_BitCast;
2629
David Blaikie1c7c8f72012-08-08 17:33:31 +00002630 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002631 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002632 Expr::NPCK_ZeroExpression) {
2633 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2634 DiagRuntimeBehavior(From->getExprLoc(), From,
2635 PDiag(diag::warn_impcast_bool_to_null_pointer)
2636 << ToType << From->getSourceRange());
2637 else if (!isUnevaluatedContext())
2638 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2639 << ToType << From->getSourceRange();
2640 }
John McCall9320b872011-09-09 05:25:32 +00002641 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2642 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002643 QualType FromPointeeType = FromPtrType->getPointeeType(),
2644 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002645
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002646 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2647 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002648 // We must have a derived-to-base conversion. Check an
2649 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002650 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2651 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002652 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002653 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002654 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002655
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002656 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002657 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002658 }
2659 }
John McCall9320b872011-09-09 05:25:32 +00002660 } else if (const ObjCObjectPointerType *ToPtrType =
2661 ToType->getAs<ObjCObjectPointerType>()) {
2662 if (const ObjCObjectPointerType *FromPtrType =
2663 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002664 // Objective-C++ conversions are always okay.
2665 // FIXME: We should have a different class of conversions for the
2666 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002667 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002668 return false;
John McCall9320b872011-09-09 05:25:32 +00002669 } else if (FromType->isBlockPointerType()) {
2670 Kind = CK_BlockPointerToObjCPointerCast;
2671 } else {
2672 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002673 }
John McCall9320b872011-09-09 05:25:32 +00002674 } else if (ToType->isBlockPointerType()) {
2675 if (!FromType->isBlockPointerType())
2676 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002677 }
John McCall8cb679e2010-11-15 09:13:47 +00002678
2679 // We shouldn't fall into this case unless it's valid for other
2680 // reasons.
2681 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2682 Kind = CK_NullToPointer;
2683
Douglas Gregor39c16d42008-10-24 04:54:22 +00002684 return false;
2685}
2686
Sebastian Redl72b597d2009-01-25 19:43:20 +00002687/// IsMemberPointerConversion - Determines whether the conversion of the
2688/// expression From, which has the (possibly adjusted) type FromType, can be
2689/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2690/// If so, returns true and places the converted type (that might differ from
2691/// ToType in its cv-qualifiers at some level) into ConvertedType.
2692bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002694 bool InOverloadResolution,
2695 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002696 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002697 if (!ToTypePtr)
2698 return false;
2699
2700 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002701 if (From->isNullPointerConstant(Context,
2702 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2703 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002704 ConvertedType = ToType;
2705 return true;
2706 }
2707
2708 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002709 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002710 if (!FromTypePtr)
2711 return false;
2712
2713 // A pointer to member of B can be converted to a pointer to member of D,
2714 // where D is derived from B (C++ 4.11p2).
2715 QualType FromClass(FromTypePtr->getClass(), 0);
2716 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002717
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002718 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002719 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002720 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002721 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2722 ToClass.getTypePtr());
2723 return true;
2724 }
2725
2726 return false;
2727}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002728
Sebastian Redl72b597d2009-01-25 19:43:20 +00002729/// CheckMemberPointerConversion - Check the member pointer conversion from the
2730/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002731/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002732/// for which IsMemberPointerConversion has already returned true. It returns
2733/// true and produces a diagnostic if there was an error, or returns false
2734/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002735bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002736 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002737 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002738 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002739 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002740 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002741 if (!FromPtrType) {
2742 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002743 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002744 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002745 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002746 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002747 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002748 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002749
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002750 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002751 assert(ToPtrType && "No member pointer cast has a target type "
2752 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002753
Sebastian Redled8f2002009-01-28 18:33:18 +00002754 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2755 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002756
Sebastian Redled8f2002009-01-28 18:33:18 +00002757 // FIXME: What about dependent types?
2758 assert(FromClass->isRecordType() && "Pointer into non-class.");
2759 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002760
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002761 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002762 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002763 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2764 assert(DerivationOkay &&
2765 "Should not have been called if derivation isn't OK.");
2766 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002767
Sebastian Redled8f2002009-01-28 18:33:18 +00002768 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2769 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002770 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2771 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2772 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2773 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002774 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002775
Douglas Gregor89ee6822009-02-28 01:32:25 +00002776 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002777 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2778 << FromClass << ToClass << QualType(VBase, 0)
2779 << From->getSourceRange();
2780 return true;
2781 }
2782
John McCall5b0829a2010-02-10 09:31:12 +00002783 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002784 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2785 Paths.front(),
2786 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002787
Anders Carlssond7923c62009-08-22 23:33:40 +00002788 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002789 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002790 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002791 return false;
2792}
2793
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002794/// Determine whether the lifetime conversion between the two given
2795/// qualifiers sets is nontrivial.
2796static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2797 Qualifiers ToQuals) {
2798 // Converting anything to const __unsafe_unretained is trivial.
2799 if (ToQuals.hasConst() &&
2800 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2801 return false;
2802
2803 return true;
2804}
2805
Douglas Gregor9a657932008-10-21 23:43:52 +00002806/// IsQualificationConversion - Determines whether the conversion from
2807/// an rvalue of type FromType to ToType is a qualification conversion
2808/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002809///
2810/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2811/// when the qualification conversion involves a change in the Objective-C
2812/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002813bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002815 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002816 FromType = Context.getCanonicalType(FromType);
2817 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002818 ObjCLifetimeConversion = false;
2819
Douglas Gregor9a657932008-10-21 23:43:52 +00002820 // If FromType and ToType are the same type, this is not a
2821 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002822 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002823 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002824
Douglas Gregor9a657932008-10-21 23:43:52 +00002825 // (C++ 4.4p4):
2826 // A conversion can add cv-qualifiers at levels other than the first
2827 // in multi-level pointers, subject to the following rules: [...]
2828 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002829 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002830 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002831 // Within each iteration of the loop, we check the qualifiers to
2832 // determine if this still looks like a qualification
2833 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002834 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002835 // until there are no more pointers or pointers-to-members left to
2836 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002837 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002838
Douglas Gregor90609aa2011-04-25 18:40:17 +00002839 Qualifiers FromQuals = FromType.getQualifiers();
2840 Qualifiers ToQuals = ToType.getQualifiers();
2841
John McCall31168b02011-06-15 23:02:42 +00002842 // Objective-C ARC:
2843 // Check Objective-C lifetime conversions.
2844 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2845 UnwrappedAnyPointer) {
2846 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002847 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2848 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002849 FromQuals.removeObjCLifetime();
2850 ToQuals.removeObjCLifetime();
2851 } else {
2852 // Qualification conversions cannot cast between different
2853 // Objective-C lifetime qualifiers.
2854 return false;
2855 }
2856 }
2857
Douglas Gregorf30053d2011-05-08 06:09:53 +00002858 // Allow addition/removal of GC attributes but not changing GC attributes.
2859 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2860 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2861 FromQuals.removeObjCGCAttr();
2862 ToQuals.removeObjCGCAttr();
2863 }
2864
Douglas Gregor9a657932008-10-21 23:43:52 +00002865 // -- for every j > 0, if const is in cv 1,j then const is in cv
2866 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002867 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002868 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002869
Douglas Gregor9a657932008-10-21 23:43:52 +00002870 // -- if the cv 1,j and cv 2,j are different, then const is in
2871 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002872 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002873 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002874 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002875
Douglas Gregor9a657932008-10-21 23:43:52 +00002876 // Keep track of whether all prior cv-qualifiers in the "to" type
2877 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002878 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002879 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002880 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002881
2882 // We are left with FromType and ToType being the pointee types
2883 // after unwrapping the original FromType and ToType the same number
2884 // of types. If we unwrapped any pointers, and if FromType and
2885 // ToType have the same unqualified type (since we checked
2886 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002887 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002888}
2889
Douglas Gregorc79862f2012-04-12 17:51:55 +00002890/// \brief - Determine whether this is a conversion from a scalar type to an
2891/// atomic type.
2892///
2893/// If successful, updates \c SCS's second and third steps in the conversion
2894/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002895static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2896 bool InOverloadResolution,
2897 StandardConversionSequence &SCS,
2898 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002899 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2900 if (!ToAtomic)
2901 return false;
2902
2903 StandardConversionSequence InnerSCS;
2904 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2905 InOverloadResolution, InnerSCS,
2906 CStyle, /*AllowObjCWritebackConversion=*/false))
2907 return false;
2908
2909 SCS.Second = InnerSCS.Second;
2910 SCS.setToType(1, InnerSCS.getToType(1));
2911 SCS.Third = InnerSCS.Third;
2912 SCS.QualificationIncludesObjCLifetime
2913 = InnerSCS.QualificationIncludesObjCLifetime;
2914 SCS.setToType(2, InnerSCS.getToType(2));
2915 return true;
2916}
2917
Sebastian Redle5417162012-03-27 18:33:03 +00002918static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2919 CXXConstructorDecl *Constructor,
2920 QualType Type) {
2921 const FunctionProtoType *CtorType =
2922 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002923 if (CtorType->getNumParams() > 0) {
2924 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002925 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2926 return true;
2927 }
2928 return false;
2929}
2930
Sebastian Redl82ace982012-02-11 23:51:08 +00002931static OverloadingResult
2932IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2933 CXXRecordDecl *To,
2934 UserDefinedConversionSequence &User,
2935 OverloadCandidateSet &CandidateSet,
2936 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002937 DeclContext::lookup_result R = S.LookupConstructors(To);
2938 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002939 Con != ConEnd; ++Con) {
2940 NamedDecl *D = *Con;
2941 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2942
2943 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002944 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002945 FunctionTemplateDecl *ConstructorTmpl
2946 = dyn_cast<FunctionTemplateDecl>(D);
2947 if (ConstructorTmpl)
2948 Constructor
2949 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2950 else
2951 Constructor = cast<CXXConstructorDecl>(D);
2952
2953 bool Usable = !Constructor->isInvalidDecl() &&
2954 S.isInitListConstructor(Constructor) &&
2955 (AllowExplicit || !Constructor->isExplicit());
2956 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002957 // If the first argument is (a reference to) the target type,
2958 // suppress conversions.
2959 bool SuppressUserConversions =
2960 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002961 if (ConstructorTmpl)
2962 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002963 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002964 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002965 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002966 else
2967 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002968 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002969 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002970 }
2971 }
2972
2973 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2974
2975 OverloadCandidateSet::iterator Best;
2976 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2977 case OR_Success: {
2978 // Record the standard conversion we used and the conversion function.
2979 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002980 QualType ThisType = Constructor->getThisType(S.Context);
2981 // Initializer lists don't have conversions as such.
2982 User.Before.setAsIdentityConversion();
2983 User.HadMultipleCandidates = HadMultipleCandidates;
2984 User.ConversionFunction = Constructor;
2985 User.FoundConversionFunction = Best->FoundDecl;
2986 User.After.setAsIdentityConversion();
2987 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2988 User.After.setAllToTypes(ToType);
2989 return OR_Success;
2990 }
2991
2992 case OR_No_Viable_Function:
2993 return OR_No_Viable_Function;
2994 case OR_Deleted:
2995 return OR_Deleted;
2996 case OR_Ambiguous:
2997 return OR_Ambiguous;
2998 }
2999
3000 llvm_unreachable("Invalid OverloadResult!");
3001}
3002
Douglas Gregor576e98c2009-01-30 23:27:23 +00003003/// Determines whether there is a user-defined conversion sequence
3004/// (C++ [over.ics.user]) that converts expression From to the type
3005/// ToType. If such a conversion exists, User will contain the
3006/// user-defined conversion sequence that performs such a conversion
3007/// and this routine will return true. Otherwise, this routine returns
3008/// false and User is unspecified.
3009///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003010/// \param AllowExplicit true if the conversion should consider C++0x
3011/// "explicit" conversion functions as well as non-explicit conversion
3012/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003013///
3014/// \param AllowObjCConversionOnExplicit true if the conversion should
3015/// allow an extra Objective-C pointer conversion on uses of explicit
3016/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003017static OverloadingResult
3018IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003019 UserDefinedConversionSequence &User,
3020 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003021 bool AllowExplicit,
3022 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003023 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003024
Douglas Gregor5ab11652010-04-17 22:01:05 +00003025 // Whether we will only visit constructors.
3026 bool ConstructorsOnly = false;
3027
3028 // If the type we are conversion to is a class type, enumerate its
3029 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003030 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003031 // C++ [over.match.ctor]p1:
3032 // When objects of class type are direct-initialized (8.5), or
3033 // copy-initialized from an expression of the same or a
3034 // derived class type (8.5), overload resolution selects the
3035 // constructor. [...] For copy-initialization, the candidate
3036 // functions are all the converting constructors (12.3.1) of
3037 // that class. The argument list is the expression-list within
3038 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003039 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003040 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003041 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003042 ConstructorsOnly = true;
3043
Benjamin Kramer90633e32012-11-23 17:04:52 +00003044 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003045 // RequireCompleteType may have returned true due to some invalid decl
3046 // during template instantiation, but ToType may be complete enough now
3047 // to try to recover.
3048 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003049 // We're not going to find any constructors.
3050 } else if (CXXRecordDecl *ToRecordDecl
3051 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003052
3053 Expr **Args = &From;
3054 unsigned NumArgs = 1;
3055 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003056 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003057 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003058 OverloadingResult Result = IsInitializerListConstructorConversion(
3059 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3060 if (Result != OR_No_Viable_Function)
3061 return Result;
3062 // Never mind.
3063 CandidateSet.clear();
3064
3065 // If we're list-initializing, we pass the individual elements as
3066 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003067 Args = InitList->getInits();
3068 NumArgs = InitList->getNumInits();
3069 ListInitializing = true;
3070 }
3071
David Blaikieff7d47a2012-12-19 00:45:41 +00003072 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3073 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003074 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003075 NamedDecl *D = *Con;
3076 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3077
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003078 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003079 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003080 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003081 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003082 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003083 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003084 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3085 else
John McCalla0296f72010-03-19 07:35:19 +00003086 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003088 bool Usable = !Constructor->isInvalidDecl();
3089 if (ListInitializing)
3090 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3091 else
3092 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3093 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003094 bool SuppressUserConversions = !ConstructorsOnly;
3095 if (SuppressUserConversions && ListInitializing) {
3096 SuppressUserConversions = false;
3097 if (NumArgs == 1) {
3098 // If the first argument is (a reference to) the target type,
3099 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003100 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3101 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003102 }
3103 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003104 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003105 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003106 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003107 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003108 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003109 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003110 // Allow one user-defined conversion when user specifies a
3111 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003112 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003113 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003114 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003115 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003116 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003117 }
3118 }
3119
Douglas Gregor5ab11652010-04-17 22:01:05 +00003120 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003121 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003122 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003123 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003124 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003125 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003126 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003127 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3128 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003129 std::pair<CXXRecordDecl::conversion_iterator,
3130 CXXRecordDecl::conversion_iterator>
3131 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3132 for (CXXRecordDecl::conversion_iterator
3133 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003134 DeclAccessPair FoundDecl = I.getPair();
3135 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003136 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3137 if (isa<UsingShadowDecl>(D))
3138 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3139
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003140 CXXConversionDecl *Conv;
3141 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003142 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3143 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003144 else
John McCallda4458e2010-03-31 01:36:47 +00003145 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003146
3147 if (AllowExplicit || !Conv->isExplicit()) {
3148 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003149 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3150 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003151 CandidateSet,
3152 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003153 else
John McCall5c32be02010-08-24 20:38:10 +00003154 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003155 From, ToType, CandidateSet,
3156 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003157 }
3158 }
3159 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003160 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003161
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003162 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3163
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003164 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003165 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003166 case OR_Success:
3167 // Record the standard conversion we used and the conversion function.
3168 if (CXXConstructorDecl *Constructor
3169 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3170 // C++ [over.ics.user]p1:
3171 // If the user-defined conversion is specified by a
3172 // constructor (12.3.1), the initial standard conversion
3173 // sequence converts the source type to the type required by
3174 // the argument of the constructor.
3175 //
3176 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003177 if (isa<InitListExpr>(From)) {
3178 // Initializer lists don't have conversions as such.
3179 User.Before.setAsIdentityConversion();
3180 } else {
3181 if (Best->Conversions[0].isEllipsis())
3182 User.EllipsisConversion = true;
3183 else {
3184 User.Before = Best->Conversions[0].Standard;
3185 User.EllipsisConversion = false;
3186 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003187 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003188 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003189 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003190 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003191 User.After.setAsIdentityConversion();
3192 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3193 User.After.setAllToTypes(ToType);
3194 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003195 }
3196 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003197 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3198 // C++ [over.ics.user]p1:
3199 //
3200 // [...] If the user-defined conversion is specified by a
3201 // conversion function (12.3.2), the initial standard
3202 // conversion sequence converts the source type to the
3203 // implicit object parameter of the conversion function.
3204 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003205 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003206 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003207 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003208 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003209
John McCall5c32be02010-08-24 20:38:10 +00003210 // C++ [over.ics.user]p2:
3211 // The second standard conversion sequence converts the
3212 // result of the user-defined conversion to the target type
3213 // for the sequence. Since an implicit conversion sequence
3214 // is an initialization, the special rules for
3215 // initialization by user-defined conversion apply when
3216 // selecting the best user-defined conversion for a
3217 // user-defined conversion sequence (see 13.3.3 and
3218 // 13.3.3.1).
3219 User.After = Best->FinalConversion;
3220 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003221 }
David Blaikie8a40f702012-01-17 06:56:22 +00003222 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003223
John McCall5c32be02010-08-24 20:38:10 +00003224 case OR_No_Viable_Function:
3225 return OR_No_Viable_Function;
3226 case OR_Deleted:
3227 // No conversion here! We're done.
3228 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229
John McCall5c32be02010-08-24 20:38:10 +00003230 case OR_Ambiguous:
3231 return OR_Ambiguous;
3232 }
3233
David Blaikie8a40f702012-01-17 06:56:22 +00003234 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003235}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003237bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003238Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003239 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003240 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3241 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003243 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003244 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003245 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003246 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3247 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003248 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003249 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003250 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003251 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003252 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3253 << From->getType() << From->getSourceRange() << ToType;
3254 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003255 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003256 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003258}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003259
Douglas Gregor2837aa22012-02-22 17:32:19 +00003260/// \brief Compare the user-defined conversion functions or constructors
3261/// of two user-defined conversion sequences to determine whether any ordering
3262/// is possible.
3263static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003264compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003265 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003266 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003267 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003268
Douglas Gregor2837aa22012-02-22 17:32:19 +00003269 // Objective-C++:
3270 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003271 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003272 // respectively, always prefer the conversion to a function pointer,
3273 // because the function pointer is more lightweight and is more likely
3274 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003275 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003276 if (!Conv1)
3277 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003278
Douglas Gregor2837aa22012-02-22 17:32:19 +00003279 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3280 if (!Conv2)
3281 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003282
Douglas Gregor2837aa22012-02-22 17:32:19 +00003283 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3284 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3285 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3286 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003287 return Block1 ? ImplicitConversionSequence::Worse
3288 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003289 }
3290
3291 return ImplicitConversionSequence::Indistinguishable;
3292}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003293
3294static bool hasDeprecatedStringLiteralToCharPtrConversion(
3295 const ImplicitConversionSequence &ICS) {
3296 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3297 (ICS.isUserDefined() &&
3298 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3299}
3300
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003301/// CompareImplicitConversionSequences - Compare two implicit
3302/// conversion sequences to determine whether one is better than the
3303/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003304static ImplicitConversionSequence::CompareKind
3305CompareImplicitConversionSequences(Sema &S,
3306 const ImplicitConversionSequence& ICS1,
3307 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003308{
3309 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3310 // conversion sequences (as defined in 13.3.3.1)
3311 // -- a standard conversion sequence (13.3.3.1.1) is a better
3312 // conversion sequence than a user-defined conversion sequence or
3313 // an ellipsis conversion sequence, and
3314 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3315 // conversion sequence than an ellipsis conversion sequence
3316 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003317 //
John McCall0d1da222010-01-12 00:44:57 +00003318 // C++0x [over.best.ics]p10:
3319 // For the purpose of ranking implicit conversion sequences as
3320 // described in 13.3.3.2, the ambiguous conversion sequence is
3321 // treated as a user-defined sequence that is indistinguishable
3322 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003323
3324 // String literal to 'char *' conversion has been deprecated in C++03. It has
3325 // been removed from C++11. We still accept this conversion, if it happens at
3326 // the best viable function. Otherwise, this conversion is considered worse
3327 // than ellipsis conversion. Consider this as an extension; this is not in the
3328 // standard. For example:
3329 //
3330 // int &f(...); // #1
3331 // void f(char*); // #2
3332 // void g() { int &r = f("foo"); }
3333 //
3334 // In C++03, we pick #2 as the best viable function.
3335 // In C++11, we pick #1 as the best viable function, because ellipsis
3336 // conversion is better than string-literal to char* conversion (since there
3337 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3338 // convert arguments, #2 would be the best viable function in C++11.
3339 // If the best viable function has this conversion, a warning will be issued
3340 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3341
3342 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3343 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3344 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3345 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3346 ? ImplicitConversionSequence::Worse
3347 : ImplicitConversionSequence::Better;
3348
Douglas Gregor5ab11652010-04-17 22:01:05 +00003349 if (ICS1.getKindRank() < ICS2.getKindRank())
3350 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003351 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003352 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003353
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003354 // The following checks require both conversion sequences to be of
3355 // the same kind.
3356 if (ICS1.getKind() != ICS2.getKind())
3357 return ImplicitConversionSequence::Indistinguishable;
3358
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003359 ImplicitConversionSequence::CompareKind Result =
3360 ImplicitConversionSequence::Indistinguishable;
3361
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003362 // Two implicit conversion sequences of the same form are
3363 // indistinguishable conversion sequences unless one of the
3364 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003365 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003366 Result = CompareStandardConversionSequences(S,
3367 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003368 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003369 // User-defined conversion sequence U1 is a better conversion
3370 // sequence than another user-defined conversion sequence U2 if
3371 // they contain the same user-defined conversion function or
3372 // constructor and if the second standard conversion sequence of
3373 // U1 is better than the second standard conversion sequence of
3374 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003375 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003376 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003377 Result = CompareStandardConversionSequences(S,
3378 ICS1.UserDefined.After,
3379 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003380 else
3381 Result = compareConversionFunctions(S,
3382 ICS1.UserDefined.ConversionFunction,
3383 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003384 }
3385
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003386 // List-initialization sequence L1 is a better conversion sequence than
3387 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3388 // for some X and L2 does not.
3389 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003390 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003391 if (ICS1.isStdInitializerListElement() &&
3392 !ICS2.isStdInitializerListElement())
3393 return ImplicitConversionSequence::Better;
3394 if (!ICS1.isStdInitializerListElement() &&
3395 ICS2.isStdInitializerListElement())
3396 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003397 }
3398
3399 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003400}
3401
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003402static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3403 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3404 Qualifiers Quals;
3405 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003409 return Context.hasSameUnqualifiedType(T1, T2);
3410}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003412// Per 13.3.3.2p3, compare the given standard conversion sequences to
3413// determine if one is a proper subset of the other.
3414static ImplicitConversionSequence::CompareKind
3415compareStandardConversionSubsets(ASTContext &Context,
3416 const StandardConversionSequence& SCS1,
3417 const StandardConversionSequence& SCS2) {
3418 ImplicitConversionSequence::CompareKind Result
3419 = ImplicitConversionSequence::Indistinguishable;
3420
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003422 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003423 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3424 return ImplicitConversionSequence::Better;
3425 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3426 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003428 if (SCS1.Second != SCS2.Second) {
3429 if (SCS1.Second == ICK_Identity)
3430 Result = ImplicitConversionSequence::Better;
3431 else if (SCS2.Second == ICK_Identity)
3432 Result = ImplicitConversionSequence::Worse;
3433 else
3434 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003435 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003436 return ImplicitConversionSequence::Indistinguishable;
3437
3438 if (SCS1.Third == SCS2.Third) {
3439 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3440 : ImplicitConversionSequence::Indistinguishable;
3441 }
3442
3443 if (SCS1.Third == ICK_Identity)
3444 return Result == ImplicitConversionSequence::Worse
3445 ? ImplicitConversionSequence::Indistinguishable
3446 : ImplicitConversionSequence::Better;
3447
3448 if (SCS2.Third == ICK_Identity)
3449 return Result == ImplicitConversionSequence::Better
3450 ? ImplicitConversionSequence::Indistinguishable
3451 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003453 return ImplicitConversionSequence::Indistinguishable;
3454}
3455
Douglas Gregore696ebb2011-01-26 14:52:12 +00003456/// \brief Determine whether one of the given reference bindings is better
3457/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003458static bool
3459isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3460 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003461 // C++0x [over.ics.rank]p3b4:
3462 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3463 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003465 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003467 // reference*.
3468 //
3469 // FIXME: Rvalue references. We're going rogue with the above edits,
3470 // because the semantics in the current C++0x working paper (N3225 at the
3471 // time of this writing) break the standard definition of std::forward
3472 // and std::reference_wrapper when dealing with references to functions.
3473 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003474 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3475 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3476 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477
Douglas Gregore696ebb2011-01-26 14:52:12 +00003478 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3479 SCS2.IsLvalueReference) ||
3480 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003481 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003482}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003484/// CompareStandardConversionSequences - Compare two standard
3485/// conversion sequences to determine whether one is better than the
3486/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003487static ImplicitConversionSequence::CompareKind
3488CompareStandardConversionSequences(Sema &S,
3489 const StandardConversionSequence& SCS1,
3490 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003491{
3492 // Standard conversion sequence S1 is a better conversion sequence
3493 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3494
3495 // -- S1 is a proper subsequence of S2 (comparing the conversion
3496 // sequences in the canonical form defined by 13.3.3.1.1,
3497 // excluding any Lvalue Transformation; the identity conversion
3498 // sequence is considered to be a subsequence of any
3499 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003500 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003501 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003502 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003503
3504 // -- the rank of S1 is better than the rank of S2 (by the rules
3505 // defined below), or, if not that,
3506 ImplicitConversionRank Rank1 = SCS1.getRank();
3507 ImplicitConversionRank Rank2 = SCS2.getRank();
3508 if (Rank1 < Rank2)
3509 return ImplicitConversionSequence::Better;
3510 else if (Rank2 < Rank1)
3511 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003512
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003513 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3514 // are indistinguishable unless one of the following rules
3515 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003516
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003517 // A conversion that is not a conversion of a pointer, or
3518 // pointer to member, to bool is better than another conversion
3519 // that is such a conversion.
3520 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3521 return SCS2.isPointerConversionToBool()
3522 ? ImplicitConversionSequence::Better
3523 : ImplicitConversionSequence::Worse;
3524
Douglas Gregor5c407d92008-10-23 00:40:37 +00003525 // C++ [over.ics.rank]p4b2:
3526 //
3527 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003528 // conversion of B* to A* is better than conversion of B* to
3529 // void*, and conversion of A* to void* is better than conversion
3530 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003531 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003532 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003533 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003534 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003535 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3536 // Exactly one of the conversion sequences is a conversion to
3537 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003538 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3539 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003540 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3541 // Neither conversion sequence converts to a void pointer; compare
3542 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003543 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003544 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003545 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003546 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3547 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003548 // Both conversion sequences are conversions to void
3549 // pointers. Compare the source types to determine if there's an
3550 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003551 QualType FromType1 = SCS1.getFromType();
3552 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003553
3554 // Adjust the types we're converting from via the array-to-pointer
3555 // conversion, if we need to.
3556 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003557 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003558 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003559 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003560
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003561 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3562 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003563
John McCall5c32be02010-08-24 20:38:10 +00003564 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003565 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003566 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003567 return ImplicitConversionSequence::Worse;
3568
3569 // Objective-C++: If one interface is more specific than the
3570 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003571 const ObjCObjectPointerType* FromObjCPtr1
3572 = FromType1->getAs<ObjCObjectPointerType>();
3573 const ObjCObjectPointerType* FromObjCPtr2
3574 = FromType2->getAs<ObjCObjectPointerType>();
3575 if (FromObjCPtr1 && FromObjCPtr2) {
3576 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3577 FromObjCPtr2);
3578 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3579 FromObjCPtr1);
3580 if (AssignLeft != AssignRight) {
3581 return AssignLeft? ImplicitConversionSequence::Better
3582 : ImplicitConversionSequence::Worse;
3583 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003584 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003585 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003586
3587 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3588 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003589 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003590 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003591 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003592
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003593 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003594 // Check for a better reference binding based on the kind of bindings.
3595 if (isBetterReferenceBindingKind(SCS1, SCS2))
3596 return ImplicitConversionSequence::Better;
3597 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3598 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Sebastian Redlb28b4072009-03-22 23:49:27 +00003600 // C++ [over.ics.rank]p3b4:
3601 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3602 // which the references refer are the same type except for
3603 // top-level cv-qualifiers, and the type to which the reference
3604 // initialized by S2 refers is more cv-qualified than the type
3605 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003606 QualType T1 = SCS1.getToType(2);
3607 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003608 T1 = S.Context.getCanonicalType(T1);
3609 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003610 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003611 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3612 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003613 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003614 // Objective-C++ ARC: If the references refer to objects with different
3615 // lifetimes, prefer bindings that don't change lifetime.
3616 if (SCS1.ObjCLifetimeConversionBinding !=
3617 SCS2.ObjCLifetimeConversionBinding) {
3618 return SCS1.ObjCLifetimeConversionBinding
3619 ? ImplicitConversionSequence::Worse
3620 : ImplicitConversionSequence::Better;
3621 }
3622
Chandler Carruth8e543b32010-12-12 08:17:55 +00003623 // If the type is an array type, promote the element qualifiers to the
3624 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003625 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003626 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003627 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003628 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003629 if (T2.isMoreQualifiedThan(T1))
3630 return ImplicitConversionSequence::Better;
3631 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003632 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003633 }
3634 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003635
Francois Pichet08d2fa02011-09-18 21:37:37 +00003636 // In Microsoft mode, prefer an integral conversion to a
3637 // floating-to-integral conversion if the integral conversion
3638 // is between types of the same size.
3639 // For example:
3640 // void f(float);
3641 // void f(int);
3642 // int main {
3643 // long a;
3644 // f(a);
3645 // }
3646 // Here, MSVC will call f(int) instead of generating a compile error
3647 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003648 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3649 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003650 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003651 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003652 return ImplicitConversionSequence::Better;
3653
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003654 return ImplicitConversionSequence::Indistinguishable;
3655}
3656
3657/// CompareQualificationConversions - Compares two standard conversion
3658/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003659/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3660ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003661CompareQualificationConversions(Sema &S,
3662 const StandardConversionSequence& SCS1,
3663 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003664 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003665 // -- S1 and S2 differ only in their qualification conversion and
3666 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3667 // cv-qualification signature of type T1 is a proper subset of
3668 // the cv-qualification signature of type T2, and S1 is not the
3669 // deprecated string literal array-to-pointer conversion (4.2).
3670 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3671 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3672 return ImplicitConversionSequence::Indistinguishable;
3673
3674 // FIXME: the example in the standard doesn't use a qualification
3675 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003676 QualType T1 = SCS1.getToType(2);
3677 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003678 T1 = S.Context.getCanonicalType(T1);
3679 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003680 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003681 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3682 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003683
3684 // If the types are the same, we won't learn anything by unwrapped
3685 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003686 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003687 return ImplicitConversionSequence::Indistinguishable;
3688
Chandler Carruth607f38e2009-12-29 07:16:59 +00003689 // If the type is an array type, promote the element qualifiers to the type
3690 // for comparison.
3691 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003692 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003693 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003694 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003695
Mike Stump11289f42009-09-09 15:08:12 +00003696 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003697 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003698
3699 // Objective-C++ ARC:
3700 // Prefer qualification conversions not involving a change in lifetime
3701 // to qualification conversions that do not change lifetime.
3702 if (SCS1.QualificationIncludesObjCLifetime !=
3703 SCS2.QualificationIncludesObjCLifetime) {
3704 Result = SCS1.QualificationIncludesObjCLifetime
3705 ? ImplicitConversionSequence::Worse
3706 : ImplicitConversionSequence::Better;
3707 }
3708
John McCall5c32be02010-08-24 20:38:10 +00003709 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003710 // Within each iteration of the loop, we check the qualifiers to
3711 // determine if this still looks like a qualification
3712 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003713 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003714 // until there are no more pointers or pointers-to-members left
3715 // to unwrap. This essentially mimics what
3716 // IsQualificationConversion does, but here we're checking for a
3717 // strict subset of qualifiers.
3718 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3719 // The qualifiers are the same, so this doesn't tell us anything
3720 // about how the sequences rank.
3721 ;
3722 else if (T2.isMoreQualifiedThan(T1)) {
3723 // T1 has fewer qualifiers, so it could be the better sequence.
3724 if (Result == ImplicitConversionSequence::Worse)
3725 // Neither has qualifiers that are a subset of the other's
3726 // qualifiers.
3727 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003728
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003729 Result = ImplicitConversionSequence::Better;
3730 } else if (T1.isMoreQualifiedThan(T2)) {
3731 // T2 has fewer qualifiers, so it could be the better sequence.
3732 if (Result == ImplicitConversionSequence::Better)
3733 // Neither has qualifiers that are a subset of the other's
3734 // qualifiers.
3735 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003736
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003737 Result = ImplicitConversionSequence::Worse;
3738 } else {
3739 // Qualifiers are disjoint.
3740 return ImplicitConversionSequence::Indistinguishable;
3741 }
3742
3743 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003744 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003745 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003746 }
3747
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003748 // Check that the winning standard conversion sequence isn't using
3749 // the deprecated string literal array to pointer conversion.
3750 switch (Result) {
3751 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003752 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003753 Result = ImplicitConversionSequence::Indistinguishable;
3754 break;
3755
3756 case ImplicitConversionSequence::Indistinguishable:
3757 break;
3758
3759 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003760 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003761 Result = ImplicitConversionSequence::Indistinguishable;
3762 break;
3763 }
3764
3765 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003766}
3767
Douglas Gregor5c407d92008-10-23 00:40:37 +00003768/// CompareDerivedToBaseConversions - Compares two standard conversion
3769/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003770/// various kinds of derived-to-base conversions (C++
3771/// [over.ics.rank]p4b3). As part of these checks, we also look at
3772/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003773ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003774CompareDerivedToBaseConversions(Sema &S,
3775 const StandardConversionSequence& SCS1,
3776 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003777 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003778 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003779 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003780 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003781
3782 // Adjust the types we're converting from via the array-to-pointer
3783 // conversion, if we need to.
3784 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003785 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003786 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003787 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003788
3789 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003790 FromType1 = S.Context.getCanonicalType(FromType1);
3791 ToType1 = S.Context.getCanonicalType(ToType1);
3792 FromType2 = S.Context.getCanonicalType(FromType2);
3793 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003794
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003795 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003796 //
3797 // If class B is derived directly or indirectly from class A and
3798 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003799 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003800 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003801 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003802 SCS2.Second == ICK_Pointer_Conversion &&
3803 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3804 FromType1->isPointerType() && FromType2->isPointerType() &&
3805 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003806 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003807 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003808 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003809 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003810 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003811 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003812 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003813 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003814
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003815 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003816 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003817 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003818 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003819 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003820 return ImplicitConversionSequence::Worse;
3821 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003822
3823 // -- conversion of B* to A* is better than conversion of C* to A*,
3824 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003825 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003826 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003827 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003828 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003829 }
3830 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3831 SCS2.Second == ICK_Pointer_Conversion) {
3832 const ObjCObjectPointerType *FromPtr1
3833 = FromType1->getAs<ObjCObjectPointerType>();
3834 const ObjCObjectPointerType *FromPtr2
3835 = FromType2->getAs<ObjCObjectPointerType>();
3836 const ObjCObjectPointerType *ToPtr1
3837 = ToType1->getAs<ObjCObjectPointerType>();
3838 const ObjCObjectPointerType *ToPtr2
3839 = ToType2->getAs<ObjCObjectPointerType>();
3840
3841 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3842 // Apply the same conversion ranking rules for Objective-C pointer types
3843 // that we do for C++ pointers to class types. However, we employ the
3844 // Objective-C pseudo-subtyping relationship used for assignment of
3845 // Objective-C pointer types.
3846 bool FromAssignLeft
3847 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3848 bool FromAssignRight
3849 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3850 bool ToAssignLeft
3851 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3852 bool ToAssignRight
3853 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3854
3855 // A conversion to an a non-id object pointer type or qualified 'id'
3856 // type is better than a conversion to 'id'.
3857 if (ToPtr1->isObjCIdType() &&
3858 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3859 return ImplicitConversionSequence::Worse;
3860 if (ToPtr2->isObjCIdType() &&
3861 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3862 return ImplicitConversionSequence::Better;
3863
3864 // A conversion to a non-id object pointer type is better than a
3865 // conversion to a qualified 'id' type
3866 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3867 return ImplicitConversionSequence::Worse;
3868 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3869 return ImplicitConversionSequence::Better;
3870
3871 // A conversion to an a non-Class object pointer type or qualified 'Class'
3872 // type is better than a conversion to 'Class'.
3873 if (ToPtr1->isObjCClassType() &&
3874 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3875 return ImplicitConversionSequence::Worse;
3876 if (ToPtr2->isObjCClassType() &&
3877 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3878 return ImplicitConversionSequence::Better;
3879
3880 // A conversion to a non-Class object pointer type is better than a
3881 // conversion to a qualified 'Class' type.
3882 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3883 return ImplicitConversionSequence::Worse;
3884 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3885 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003886
Douglas Gregor058d3de2011-01-31 18:51:41 +00003887 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3888 if (S.Context.hasSameType(FromType1, FromType2) &&
3889 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3890 (ToAssignLeft != ToAssignRight))
3891 return ToAssignLeft? ImplicitConversionSequence::Worse
3892 : ImplicitConversionSequence::Better;
3893
3894 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3895 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3896 (FromAssignLeft != FromAssignRight))
3897 return FromAssignLeft? ImplicitConversionSequence::Better
3898 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003899 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003900 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003901
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003902 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003903 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3904 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3905 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003907 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003908 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003909 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003911 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003913 ToType2->getAs<MemberPointerType>();
3914 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3915 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3916 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3917 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3918 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3919 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3920 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3921 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003922 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003923 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003924 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003925 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003926 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003927 return ImplicitConversionSequence::Better;
3928 }
3929 // conversion of B::* to C::* is better than conversion of A::* to C::*
3930 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003931 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003932 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003933 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003934 return ImplicitConversionSequence::Worse;
3935 }
3936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937
Douglas Gregor5ab11652010-04-17 22:01:05 +00003938 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003939 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003940 // -- binding of an expression of type C to a reference of type
3941 // B& is better than binding an expression of type C to a
3942 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003943 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3944 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3945 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003946 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003947 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003948 return ImplicitConversionSequence::Worse;
3949 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003950
Douglas Gregor2fe98832008-11-03 19:09:14 +00003951 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003952 // -- binding of an expression of type B to a reference of type
3953 // A& is better than binding an expression of type C to a
3954 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003955 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3956 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3957 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003958 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003959 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003960 return ImplicitConversionSequence::Worse;
3961 }
3962 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003963
Douglas Gregor5c407d92008-10-23 00:40:37 +00003964 return ImplicitConversionSequence::Indistinguishable;
3965}
3966
Douglas Gregor45bb4832013-03-26 23:36:30 +00003967/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3968/// C++ class.
3969static bool isTypeValid(QualType T) {
3970 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3971 return !Record->isInvalidDecl();
3972
3973 return true;
3974}
3975
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003976/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3977/// determine whether they are reference-related,
3978/// reference-compatible, reference-compatible with added
3979/// qualification, or incompatible, for use in C++ initialization by
3980/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3981/// type, and the first type (T1) is the pointee type of the reference
3982/// type being initialized.
3983Sema::ReferenceCompareResult
3984Sema::CompareReferenceRelationship(SourceLocation Loc,
3985 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003986 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003987 bool &ObjCConversion,
3988 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003989 assert(!OrigT1->isReferenceType() &&
3990 "T1 must be the pointee type of the reference type");
3991 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3992
3993 QualType T1 = Context.getCanonicalType(OrigT1);
3994 QualType T2 = Context.getCanonicalType(OrigT2);
3995 Qualifiers T1Quals, T2Quals;
3996 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3997 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3998
3999 // C++ [dcl.init.ref]p4:
4000 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4001 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4002 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004003 DerivedToBase = false;
4004 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004005 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004006 if (UnqualT1 == UnqualT2) {
4007 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004008 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004009 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4010 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004011 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004012 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4013 UnqualT2->isObjCObjectOrInterfaceType() &&
4014 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4015 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004016 else
4017 return Ref_Incompatible;
4018
4019 // At this point, we know that T1 and T2 are reference-related (at
4020 // least).
4021
4022 // If the type is an array type, promote the element qualifiers to the type
4023 // for comparison.
4024 if (isa<ArrayType>(T1) && T1Quals)
4025 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4026 if (isa<ArrayType>(T2) && T2Quals)
4027 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4028
4029 // C++ [dcl.init.ref]p4:
4030 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4031 // reference-related to T2 and cv1 is the same cv-qualification
4032 // as, or greater cv-qualification than, cv2. For purposes of
4033 // overload resolution, cases for which cv1 is greater
4034 // cv-qualification than cv2 are identified as
4035 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004036 //
4037 // Note that we also require equivalence of Objective-C GC and address-space
4038 // qualifiers when performing these computations, so that e.g., an int in
4039 // address space 1 is not reference-compatible with an int in address
4040 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004041 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4042 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004043 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4044 ObjCLifetimeConversion = true;
4045
John McCall31168b02011-06-15 23:02:42 +00004046 T1Quals.removeObjCLifetime();
4047 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004048 }
4049
Douglas Gregord517d552011-04-28 17:56:11 +00004050 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004051 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004052 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004053 return Ref_Compatible_With_Added_Qualification;
4054 else
4055 return Ref_Related;
4056}
4057
Douglas Gregor836a7e82010-08-11 02:15:33 +00004058/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004059/// with DeclType. Return true if something definite is found.
4060static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004061FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4062 QualType DeclType, SourceLocation DeclLoc,
4063 Expr *Init, QualType T2, bool AllowRvalues,
4064 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004065 assert(T2->isRecordType() && "Can only find conversions of record types.");
4066 CXXRecordDecl *T2RecordDecl
4067 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4068
Richard Smith100b24a2014-04-17 01:52:14 +00004069 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004070 std::pair<CXXRecordDecl::conversion_iterator,
4071 CXXRecordDecl::conversion_iterator>
4072 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4073 for (CXXRecordDecl::conversion_iterator
4074 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004075 NamedDecl *D = *I;
4076 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4077 if (isa<UsingShadowDecl>(D))
4078 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4079
4080 FunctionTemplateDecl *ConvTemplate
4081 = dyn_cast<FunctionTemplateDecl>(D);
4082 CXXConversionDecl *Conv;
4083 if (ConvTemplate)
4084 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4085 else
4086 Conv = cast<CXXConversionDecl>(D);
4087
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004089 // explicit conversions, skip it.
4090 if (!AllowExplicit && Conv->isExplicit())
4091 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004092
Douglas Gregor836a7e82010-08-11 02:15:33 +00004093 if (AllowRvalues) {
4094 bool DerivedToBase = false;
4095 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004096 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004097
4098 // If we are initializing an rvalue reference, don't permit conversion
4099 // functions that return lvalues.
4100 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4101 const ReferenceType *RefType
4102 = Conv->getConversionType()->getAs<LValueReferenceType>();
4103 if (RefType && !RefType->getPointeeType()->isFunctionType())
4104 continue;
4105 }
4106
Douglas Gregor836a7e82010-08-11 02:15:33 +00004107 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004108 S.CompareReferenceRelationship(
4109 DeclLoc,
4110 Conv->getConversionType().getNonReferenceType()
4111 .getUnqualifiedType(),
4112 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004113 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004114 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004115 continue;
4116 } else {
4117 // If the conversion function doesn't return a reference type,
4118 // it can't be considered for this conversion. An rvalue reference
4119 // is only acceptable if its referencee is a function type.
4120
4121 const ReferenceType *RefType =
4122 Conv->getConversionType()->getAs<ReferenceType>();
4123 if (!RefType ||
4124 (!RefType->isLValueReferenceType() &&
4125 !RefType->getPointeeType()->isFunctionType()))
4126 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128
Douglas Gregor836a7e82010-08-11 02:15:33 +00004129 if (ConvTemplate)
4130 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004131 Init, DeclType, CandidateSet,
4132 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004133 else
4134 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004135 DeclType, CandidateSet,
4136 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004137 }
4138
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004139 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4140
Sebastian Redld92badf2010-06-30 18:13:39 +00004141 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004142 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004143 case OR_Success:
4144 // C++ [over.ics.ref]p1:
4145 //
4146 // [...] If the parameter binds directly to the result of
4147 // applying a conversion function to the argument
4148 // expression, the implicit conversion sequence is a
4149 // user-defined conversion sequence (13.3.3.1.2), with the
4150 // second standard conversion sequence either an identity
4151 // conversion or, if the conversion function returns an
4152 // entity of a type that is a derived class of the parameter
4153 // type, a derived-to-base Conversion.
4154 if (!Best->FinalConversion.DirectBinding)
4155 return false;
4156
4157 ICS.setUserDefined();
4158 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4159 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004160 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004161 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004162 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004163 ICS.UserDefined.EllipsisConversion = false;
4164 assert(ICS.UserDefined.After.ReferenceBinding &&
4165 ICS.UserDefined.After.DirectBinding &&
4166 "Expected a direct reference binding!");
4167 return true;
4168
4169 case OR_Ambiguous:
4170 ICS.setAmbiguous();
4171 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4172 Cand != CandidateSet.end(); ++Cand)
4173 if (Cand->Viable)
4174 ICS.Ambiguous.addConversion(Cand->Function);
4175 return true;
4176
4177 case OR_No_Viable_Function:
4178 case OR_Deleted:
4179 // There was no suitable conversion, or we found a deleted
4180 // conversion; continue with other checks.
4181 return false;
4182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183
David Blaikie8a40f702012-01-17 06:56:22 +00004184 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004185}
4186
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004187/// \brief Compute an implicit conversion sequence for reference
4188/// initialization.
4189static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004190TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004191 SourceLocation DeclLoc,
4192 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004193 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004194 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4195
4196 // Most paths end in a failed conversion.
4197 ImplicitConversionSequence ICS;
4198 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4199
4200 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4201 QualType T2 = Init->getType();
4202
4203 // If the initializer is the address of an overloaded function, try
4204 // to resolve the overloaded function. If all goes well, T2 is the
4205 // type of the resulting function.
4206 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4207 DeclAccessPair Found;
4208 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4209 false, Found))
4210 T2 = Fn->getType();
4211 }
4212
4213 // Compute some basic properties of the types and the initializer.
4214 bool isRValRef = DeclType->isRValueReferenceType();
4215 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004216 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004217 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004218 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004219 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004220 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004221 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004222
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004223
Sebastian Redld92badf2010-06-30 18:13:39 +00004224 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004225 // A reference to type "cv1 T1" is initialized by an expression
4226 // of type "cv2 T2" as follows:
4227
Sebastian Redld92badf2010-06-30 18:13:39 +00004228 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004229 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004230 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4231 // reference-compatible with "cv2 T2," or
4232 //
4233 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4234 if (InitCategory.isLValue() &&
4235 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004236 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004237 // When a parameter of reference type binds directly (8.5.3)
4238 // to an argument expression, the implicit conversion sequence
4239 // is the identity conversion, unless the argument expression
4240 // has a type that is a derived class of the parameter type,
4241 // in which case the implicit conversion sequence is a
4242 // derived-to-base Conversion (13.3.3.1).
4243 ICS.setStandard();
4244 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004245 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4246 : ObjCConversion? ICK_Compatible_Conversion
4247 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004248 ICS.Standard.Third = ICK_Identity;
4249 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4250 ICS.Standard.setToType(0, T2);
4251 ICS.Standard.setToType(1, T1);
4252 ICS.Standard.setToType(2, T1);
4253 ICS.Standard.ReferenceBinding = true;
4254 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004255 ICS.Standard.IsLvalueReference = !isRValRef;
4256 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4257 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004258 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004259 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004260 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004261 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004262
Sebastian Redld92badf2010-06-30 18:13:39 +00004263 // Nothing more to do: the inaccessibility/ambiguity check for
4264 // derived-to-base conversions is suppressed when we're
4265 // computing the implicit conversion sequence (C++
4266 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004267 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004268 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004269
Sebastian Redld92badf2010-06-30 18:13:39 +00004270 // -- has a class type (i.e., T2 is a class type), where T1 is
4271 // not reference-related to T2, and can be implicitly
4272 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4273 // is reference-compatible with "cv3 T3" 92) (this
4274 // conversion is selected by enumerating the applicable
4275 // conversion functions (13.3.1.6) and choosing the best
4276 // one through overload resolution (13.3)),
4277 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004279 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004280 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4281 Init, T2, /*AllowRvalues=*/false,
4282 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004283 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004284 }
4285 }
4286
Sebastian Redld92badf2010-06-30 18:13:39 +00004287 // -- Otherwise, the reference shall be an lvalue reference to a
4288 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004289 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004291 // We actually handle one oddity of C++ [over.ics.ref] at this
4292 // point, which is that, due to p2 (which short-circuits reference
4293 // binding by only attempting a simple conversion for non-direct
4294 // bindings) and p3's strange wording, we allow a const volatile
4295 // reference to bind to an rvalue. Hence the check for the presence
4296 // of "const" rather than checking for "const" being the only
4297 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004298 // This is also the point where rvalue references and lvalue inits no longer
4299 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004300 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004301 return ICS;
4302
Douglas Gregorf143cd52011-01-24 16:14:37 +00004303 // -- If the initializer expression
4304 //
4305 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004306 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004307 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4308 (InitCategory.isXValue() ||
4309 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4310 (InitCategory.isLValue() && T2->isFunctionType()))) {
4311 ICS.setStandard();
4312 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004314 : ObjCConversion? ICK_Compatible_Conversion
4315 : ICK_Identity;
4316 ICS.Standard.Third = ICK_Identity;
4317 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4318 ICS.Standard.setToType(0, T2);
4319 ICS.Standard.setToType(1, T1);
4320 ICS.Standard.setToType(2, T1);
4321 ICS.Standard.ReferenceBinding = true;
4322 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4323 // binding unless we're binding to a class prvalue.
4324 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4325 // allow the use of rvalue references in C++98/03 for the benefit of
4326 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004328 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004329 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004330 ICS.Standard.IsLvalueReference = !isRValRef;
4331 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004333 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004334 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004335 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004336 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339
Douglas Gregorf143cd52011-01-24 16:14:37 +00004340 // -- has a class type (i.e., T2 is a class type), where T1 is not
4341 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342 // an xvalue, class prvalue, or function lvalue of type
4343 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004344 // "cv3 T3",
4345 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004347 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004349 // class subobject).
4350 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004352 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4353 Init, T2, /*AllowRvalues=*/true,
4354 AllowExplicit)) {
4355 // In the second case, if the reference is an rvalue reference
4356 // and the second standard conversion sequence of the
4357 // user-defined conversion sequence includes an lvalue-to-rvalue
4358 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004360 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4361 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4362
Douglas Gregor95273c32011-01-21 16:36:05 +00004363 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Richard Smith19172c42014-07-14 02:28:44 +00004366 // A temporary of function type cannot be created; don't even try.
4367 if (T1->isFunctionType())
4368 return ICS;
4369
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004370 // -- Otherwise, a temporary of type "cv1 T1" is created and
4371 // initialized from the initializer expression using the
4372 // rules for a non-reference copy initialization (8.5). The
4373 // reference is then bound to the temporary. If T1 is
4374 // reference-related to T2, cv1 must be the same
4375 // cv-qualification as, or greater cv-qualification than,
4376 // cv2; otherwise, the program is ill-formed.
4377 if (RefRelationship == Sema::Ref_Related) {
4378 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4379 // we would be reference-compatible or reference-compatible with
4380 // added qualification. But that wasn't the case, so the reference
4381 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004382 //
4383 // Note that we only want to check address spaces and cvr-qualifiers here.
4384 // ObjC GC and lifetime qualifiers aren't important.
4385 Qualifiers T1Quals = T1.getQualifiers();
4386 Qualifiers T2Quals = T2.getQualifiers();
4387 T1Quals.removeObjCGCAttr();
4388 T1Quals.removeObjCLifetime();
4389 T2Quals.removeObjCGCAttr();
4390 T2Quals.removeObjCLifetime();
4391 if (!T1Quals.compatiblyIncludes(T2Quals))
4392 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004393 }
4394
4395 // If at least one of the types is a class type, the types are not
4396 // related, and we aren't allowed any user conversions, the
4397 // reference binding fails. This case is important for breaking
4398 // recursion, since TryImplicitConversion below will attempt to
4399 // create a temporary through the use of a copy constructor.
4400 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4401 (T1->isRecordType() || T2->isRecordType()))
4402 return ICS;
4403
Douglas Gregorcba72b12011-01-21 05:18:22 +00004404 // If T1 is reference-related to T2 and the reference is an rvalue
4405 // reference, the initializer expression shall not be an lvalue.
4406 if (RefRelationship >= Sema::Ref_Related &&
4407 isRValRef && Init->Classify(S.Context).isLValue())
4408 return ICS;
4409
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004410 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004411 // When a parameter of reference type is not bound directly to
4412 // an argument expression, the conversion sequence is the one
4413 // required to convert the argument expression to the
4414 // underlying type of the reference according to
4415 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4416 // to copy-initializing a temporary of the underlying type with
4417 // the argument expression. Any difference in top-level
4418 // cv-qualification is subsumed by the initialization itself
4419 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004420 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4421 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004422 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004423 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004424 /*AllowObjCWritebackConversion=*/false,
4425 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004426
4427 // Of course, that's still a reference binding.
4428 if (ICS.isStandard()) {
4429 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004430 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004431 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004432 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004433 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004434 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004435 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004436 const ReferenceType *LValRefType =
4437 ICS.UserDefined.ConversionFunction->getReturnType()
4438 ->getAs<LValueReferenceType>();
4439
4440 // C++ [over.ics.ref]p3:
4441 // Except for an implicit object parameter, for which see 13.3.1, a
4442 // standard conversion sequence cannot be formed if it requires [...]
4443 // binding an rvalue reference to an lvalue other than a function
4444 // lvalue.
4445 // Note that the function case is not possible here.
4446 if (DeclType->isRValueReferenceType() && LValRefType) {
4447 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4448 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4449 // reference to an rvalue!
4450 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4451 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004452 }
Richard Smith19172c42014-07-14 02:28:44 +00004453
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004454 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004455 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004456 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004457 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4458 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004459 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4460 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004461 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004462
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004463 return ICS;
4464}
4465
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004466static ImplicitConversionSequence
4467TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4468 bool SuppressUserConversions,
4469 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004470 bool AllowObjCWritebackConversion,
4471 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004472
4473/// TryListConversion - Try to copy-initialize a value of type ToType from the
4474/// initializer list From.
4475static ImplicitConversionSequence
4476TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4477 bool SuppressUserConversions,
4478 bool InOverloadResolution,
4479 bool AllowObjCWritebackConversion) {
4480 // C++11 [over.ics.list]p1:
4481 // When an argument is an initializer list, it is not an expression and
4482 // special rules apply for converting it to a parameter type.
4483
4484 ImplicitConversionSequence Result;
4485 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4486
Sebastian Redl09edce02012-01-23 22:09:39 +00004487 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004488 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004489 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004490 return Result;
4491
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004492 // C++11 [over.ics.list]p2:
4493 // If the parameter type is std::initializer_list<X> or "array of X" and
4494 // all the elements can be implicitly converted to X, the implicit
4495 // conversion sequence is the worst conversion necessary to convert an
4496 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004497 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004498 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004499 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004500 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004501 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004502 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004503 if (!X.isNull()) {
4504 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4505 Expr *Init = From->getInit(i);
4506 ImplicitConversionSequence ICS =
4507 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4508 InOverloadResolution,
4509 AllowObjCWritebackConversion);
4510 // If a single element isn't convertible, fail.
4511 if (ICS.isBad()) {
4512 Result = ICS;
4513 break;
4514 }
4515 // Otherwise, look for the worst conversion.
4516 if (Result.isBad() ||
4517 CompareImplicitConversionSequences(S, ICS, Result) ==
4518 ImplicitConversionSequence::Worse)
4519 Result = ICS;
4520 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004521
4522 // For an empty list, we won't have computed any conversion sequence.
4523 // Introduce the identity conversion sequence.
4524 if (From->getNumInits() == 0) {
4525 Result.setStandard();
4526 Result.Standard.setAsIdentityConversion();
4527 Result.Standard.setFromType(ToType);
4528 Result.Standard.setAllToTypes(ToType);
4529 }
4530
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004531 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004532 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004533 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004534
4535 // C++11 [over.ics.list]p3:
4536 // Otherwise, if the parameter is a non-aggregate class X and overload
4537 // resolution chooses a single best constructor [...] the implicit
4538 // conversion sequence is a user-defined conversion sequence. If multiple
4539 // constructors are viable but none is better than the others, the
4540 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004541 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4542 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004543 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4544 /*AllowExplicit=*/false,
4545 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004546 AllowObjCWritebackConversion,
4547 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004548 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004549
4550 // C++11 [over.ics.list]p4:
4551 // Otherwise, if the parameter has an aggregate type which can be
4552 // initialized from the initializer list [...] the implicit conversion
4553 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004554 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004555 // Type is an aggregate, argument is an init list. At this point it comes
4556 // down to checking whether the initialization works.
4557 // FIXME: Find out whether this parameter is consumed or not.
4558 InitializedEntity Entity =
4559 InitializedEntity::InitializeParameter(S.Context, ToType,
4560 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004561 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004562 Result.setUserDefined();
4563 Result.UserDefined.Before.setAsIdentityConversion();
4564 // Initializer lists don't have a type.
4565 Result.UserDefined.Before.setFromType(QualType());
4566 Result.UserDefined.Before.setAllToTypes(QualType());
4567
4568 Result.UserDefined.After.setAsIdentityConversion();
4569 Result.UserDefined.After.setFromType(ToType);
4570 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004571 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004572 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004573 return Result;
4574 }
4575
4576 // C++11 [over.ics.list]p5:
4577 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004578 if (ToType->isReferenceType()) {
4579 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4580 // mention initializer lists in any way. So we go by what list-
4581 // initialization would do and try to extrapolate from that.
4582
4583 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4584
4585 // If the initializer list has a single element that is reference-related
4586 // to the parameter type, we initialize the reference from that.
4587 if (From->getNumInits() == 1) {
4588 Expr *Init = From->getInit(0);
4589
4590 QualType T2 = Init->getType();
4591
4592 // If the initializer is the address of an overloaded function, try
4593 // to resolve the overloaded function. If all goes well, T2 is the
4594 // type of the resulting function.
4595 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4596 DeclAccessPair Found;
4597 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4598 Init, ToType, false, Found))
4599 T2 = Fn->getType();
4600 }
4601
4602 // Compute some basic properties of the types and the initializer.
4603 bool dummy1 = false;
4604 bool dummy2 = false;
4605 bool dummy3 = false;
4606 Sema::ReferenceCompareResult RefRelationship
4607 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4608 dummy2, dummy3);
4609
Richard Smith4d2bbd72013-09-06 01:22:42 +00004610 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004611 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4612 SuppressUserConversions,
4613 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004614 }
Sebastian Redldf888642011-12-03 14:54:30 +00004615 }
4616
4617 // Otherwise, we bind the reference to a temporary created from the
4618 // initializer list.
4619 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4620 InOverloadResolution,
4621 AllowObjCWritebackConversion);
4622 if (Result.isFailure())
4623 return Result;
4624 assert(!Result.isEllipsis() &&
4625 "Sub-initialization cannot result in ellipsis conversion.");
4626
4627 // Can we even bind to a temporary?
4628 if (ToType->isRValueReferenceType() ||
4629 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4630 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4631 Result.UserDefined.After;
4632 SCS.ReferenceBinding = true;
4633 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4634 SCS.BindsToRvalue = true;
4635 SCS.BindsToFunctionLvalue = false;
4636 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4637 SCS.ObjCLifetimeConversionBinding = false;
4638 } else
4639 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4640 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004641 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004642 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004643
4644 // C++11 [over.ics.list]p6:
4645 // Otherwise, if the parameter type is not a class:
4646 if (!ToType->isRecordType()) {
4647 // - if the initializer list has one element, the implicit conversion
4648 // sequence is the one required to convert the element to the
4649 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004650 unsigned NumInits = From->getNumInits();
4651 if (NumInits == 1)
4652 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4653 SuppressUserConversions,
4654 InOverloadResolution,
4655 AllowObjCWritebackConversion);
4656 // - if the initializer list has no elements, the implicit conversion
4657 // sequence is the identity conversion.
4658 else if (NumInits == 0) {
4659 Result.setStandard();
4660 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004661 Result.Standard.setFromType(ToType);
4662 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004663 }
4664 return Result;
4665 }
4666
4667 // C++11 [over.ics.list]p7:
4668 // In all cases other than those enumerated above, no conversion is possible
4669 return Result;
4670}
4671
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004672/// TryCopyInitialization - Try to copy-initialize a value of type
4673/// ToType from the expression From. Return the implicit conversion
4674/// sequence required to pass this argument, which may be a bad
4675/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004676/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004677/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004678static ImplicitConversionSequence
4679TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004681 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004682 bool AllowObjCWritebackConversion,
4683 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004684 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4685 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4686 InOverloadResolution,AllowObjCWritebackConversion);
4687
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004688 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004689 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004690 /*FIXME:*/From->getLocStart(),
4691 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004692 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004693
John McCall5c32be02010-08-24 20:38:10 +00004694 return TryImplicitConversion(S, From, ToType,
4695 SuppressUserConversions,
4696 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004697 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004698 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004699 AllowObjCWritebackConversion,
4700 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004701}
4702
Anna Zaks1b068122011-07-28 19:46:48 +00004703static bool TryCopyInitialization(const CanQualType FromQTy,
4704 const CanQualType ToQTy,
4705 Sema &S,
4706 SourceLocation Loc,
4707 ExprValueKind FromVK) {
4708 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4709 ImplicitConversionSequence ICS =
4710 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4711
4712 return !ICS.isBad();
4713}
4714
Douglas Gregor436424c2008-11-18 23:14:02 +00004715/// TryObjectArgumentInitialization - Try to initialize the object
4716/// parameter of the given member function (@c Method) from the
4717/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004718static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004719TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004720 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004721 CXXMethodDecl *Method,
4722 CXXRecordDecl *ActingContext) {
4723 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004724 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4725 // const volatile object.
4726 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4727 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004728 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004729
4730 // Set up the conversion sequence as a "bad" conversion, to allow us
4731 // to exit early.
4732 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004733
4734 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004735 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004736 FromType = PT->getPointeeType();
4737
Douglas Gregor02824322011-01-26 19:30:28 +00004738 // When we had a pointer, it's implicitly dereferenced, so we
4739 // better have an lvalue.
4740 assert(FromClassification.isLValue());
4741 }
4742
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004743 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004744
Douglas Gregor02824322011-01-26 19:30:28 +00004745 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004746 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004747 // parameter is
4748 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004749 // - "lvalue reference to cv X" for functions declared without a
4750 // ref-qualifier or with the & ref-qualifier
4751 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004752 // ref-qualifier
4753 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004755 // cv-qualification on the member function declaration.
4756 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004758 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004759 // (C++ [over.match.funcs]p5). We perform a simplified version of
4760 // reference binding here, that allows class rvalues to bind to
4761 // non-constant references.
4762
Douglas Gregor02824322011-01-26 19:30:28 +00004763 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004764 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004766 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004767 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004768 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004769 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004770 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004771 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004772
4773 // Check that we have either the same type or a derived type. It
4774 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004775 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004776 ImplicitConversionKind SecondKind;
4777 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4778 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004779 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004780 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004781 else {
John McCall65eb8792010-02-25 01:37:24 +00004782 ICS.setBad(BadConversionSequence::unrelated_class,
4783 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004784 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004785 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004786
Douglas Gregor02824322011-01-26 19:30:28 +00004787 // Check the ref-qualifier.
4788 switch (Method->getRefQualifier()) {
4789 case RQ_None:
4790 // Do nothing; we don't care about lvalueness or rvalueness.
4791 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004792
Douglas Gregor02824322011-01-26 19:30:28 +00004793 case RQ_LValue:
4794 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4795 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004797 ImplicitParamType);
4798 return ICS;
4799 }
4800 break;
4801
4802 case RQ_RValue:
4803 if (!FromClassification.isRValue()) {
4804 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004806 ImplicitParamType);
4807 return ICS;
4808 }
4809 break;
4810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811
Douglas Gregor436424c2008-11-18 23:14:02 +00004812 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004813 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004814 ICS.Standard.setAsIdentityConversion();
4815 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004816 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004817 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004818 ICS.Standard.ReferenceBinding = true;
4819 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004821 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004822 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4823 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4824 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004825 return ICS;
4826}
4827
4828/// PerformObjectArgumentInitialization - Perform initialization of
4829/// the implicit object parameter for the given Method with the given
4830/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004831ExprResult
4832Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004834 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004835 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004836 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004837 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004838 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004839
Douglas Gregor02824322011-01-26 19:30:28 +00004840 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004841 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004842 FromRecordType = PT->getPointeeType();
4843 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004844 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004845 } else {
4846 FromRecordType = From->getType();
4847 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004848 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004849 }
4850
John McCall6e9f8f62009-12-03 04:06:58 +00004851 // Note that we always use the true parent context when performing
4852 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004853 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004854 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4855 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004856 if (ICS.isBad()) {
4857 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4858 Qualifiers FromQs = FromRecordType.getQualifiers();
4859 Qualifiers ToQs = DestType.getQualifiers();
4860 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4861 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004862 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004863 diag::err_member_function_call_bad_cvr)
4864 << Method->getDeclName() << FromRecordType << (CVR - 1)
4865 << From->getSourceRange();
4866 Diag(Method->getLocation(), diag::note_previous_decl)
4867 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004868 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004869 }
4870 }
4871
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004872 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004873 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004874 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004875 }
Mike Stump11289f42009-09-09 15:08:12 +00004876
John Wiegley01296292011-04-08 18:41:53 +00004877 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4878 ExprResult FromRes =
4879 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4880 if (FromRes.isInvalid())
4881 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004882 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004883 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004884
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004885 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004886 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004887 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004888 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004889}
4890
Douglas Gregor5fb53972009-01-14 15:45:31 +00004891/// TryContextuallyConvertToBool - Attempt to contextually convert the
4892/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004893static ImplicitConversionSequence
4894TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004895 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004896 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004897 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004898 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004899 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004900 /*AllowObjCWritebackConversion=*/false,
4901 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004902}
4903
4904/// PerformContextuallyConvertToBool - Perform a contextual conversion
4905/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004906ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004907 if (checkPlaceholderForOverload(*this, From))
4908 return ExprError();
4909
John McCall5c32be02010-08-24 20:38:10 +00004910 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004911 if (!ICS.isBad())
4912 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004913
Fariborz Jahanian76197412009-11-18 18:26:29 +00004914 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004915 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004916 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004917 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004918 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004919}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920
Richard Smithf8379a02012-01-18 23:55:52 +00004921/// Check that the specified conversion is permitted in a converted constant
4922/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4923/// is acceptable.
4924static bool CheckConvertedConstantConversions(Sema &S,
4925 StandardConversionSequence &SCS) {
4926 // Since we know that the target type is an integral or unscoped enumeration
4927 // type, most conversion kinds are impossible. All possible First and Third
4928 // conversions are fine.
4929 switch (SCS.Second) {
4930 case ICK_Identity:
4931 case ICK_Integral_Promotion:
4932 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004933 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004934 return true;
4935
4936 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004937 // Conversion from an integral or unscoped enumeration type to bool is
4938 // classified as ICK_Boolean_Conversion, but it's also an integral
4939 // conversion, so it's permitted in a converted constant expression.
4940 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4941 SCS.getToType(2)->isBooleanType();
4942
Richard Smithf8379a02012-01-18 23:55:52 +00004943 case ICK_Floating_Integral:
4944 case ICK_Complex_Real:
4945 return false;
4946
4947 case ICK_Lvalue_To_Rvalue:
4948 case ICK_Array_To_Pointer:
4949 case ICK_Function_To_Pointer:
4950 case ICK_NoReturn_Adjustment:
4951 case ICK_Qualification:
4952 case ICK_Compatible_Conversion:
4953 case ICK_Vector_Conversion:
4954 case ICK_Vector_Splat:
4955 case ICK_Derived_To_Base:
4956 case ICK_Pointer_Conversion:
4957 case ICK_Pointer_Member:
4958 case ICK_Block_Pointer_Conversion:
4959 case ICK_Writeback_Conversion:
4960 case ICK_Floating_Promotion:
4961 case ICK_Complex_Promotion:
4962 case ICK_Complex_Conversion:
4963 case ICK_Floating_Conversion:
4964 case ICK_TransparentUnionConversion:
4965 llvm_unreachable("unexpected second conversion kind");
4966
4967 case ICK_Num_Conversion_Kinds:
4968 break;
4969 }
4970
4971 llvm_unreachable("unknown conversion kind");
4972}
4973
4974/// CheckConvertedConstantExpression - Check that the expression From is a
4975/// converted constant expression of type T, perform the conversion and produce
4976/// the converted expression, per C++11 [expr.const]p3.
4977ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4978 llvm::APSInt &Value,
4979 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004980 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004981 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4982
4983 if (checkPlaceholderForOverload(*this, From))
4984 return ExprError();
4985
4986 // C++11 [expr.const]p3 with proposed wording fixes:
4987 // A converted constant expression of type T is a core constant expression,
4988 // implicitly converted to a prvalue of type T, where the converted
4989 // expression is a literal constant expression and the implicit conversion
4990 // sequence contains only user-defined conversions, lvalue-to-rvalue
4991 // conversions, integral promotions, and integral conversions other than
4992 // narrowing conversions.
4993 ImplicitConversionSequence ICS =
4994 TryImplicitConversion(From, T,
4995 /*SuppressUserConversions=*/false,
4996 /*AllowExplicit=*/false,
4997 /*InOverloadResolution=*/false,
4998 /*CStyle=*/false,
4999 /*AllowObjcWritebackConversion=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005000 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005001 switch (ICS.getKind()) {
5002 case ImplicitConversionSequence::StandardConversion:
5003 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005004 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005005 diag::err_typecheck_converted_constant_expression_disallowed)
5006 << From->getType() << From->getSourceRange() << T;
5007 SCS = &ICS.Standard;
5008 break;
5009 case ImplicitConversionSequence::UserDefinedConversion:
5010 // We are converting from class type to an integral or enumeration type, so
5011 // the Before sequence must be trivial.
5012 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005013 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005014 diag::err_typecheck_converted_constant_expression_disallowed)
5015 << From->getType() << From->getSourceRange() << T;
5016 SCS = &ICS.UserDefined.After;
5017 break;
5018 case ImplicitConversionSequence::AmbiguousConversion:
5019 case ImplicitConversionSequence::BadConversion:
5020 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005021 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005022 diag::err_typecheck_converted_constant_expression)
5023 << From->getType() << From->getSourceRange() << T;
5024 return ExprError();
5025
5026 case ImplicitConversionSequence::EllipsisConversion:
5027 llvm_unreachable("ellipsis conversion in converted constant expression");
5028 }
5029
5030 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5031 if (Result.isInvalid())
5032 return Result;
5033
5034 // Check for a narrowing implicit conversion.
5035 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005036 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005037 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5038 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005039 case NK_Variable_Narrowing:
5040 // Implicit conversion to a narrower type, and the value is not a constant
5041 // expression. We'll diagnose this in a moment.
5042 case NK_Not_Narrowing:
5043 break;
5044
5045 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005046 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005047 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005048 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005049 break;
5050
5051 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005052 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005053 << CCE << /*Constant*/0 << From->getType() << T;
5054 break;
5055 }
5056
5057 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005058 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005059 Expr::EvalResult Eval;
5060 Eval.Diag = &Notes;
5061
Douglas Gregorebe2db72013-04-08 23:24:07 +00005062 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005063 // The expression can't be folded, so we can't keep it at this position in
5064 // the AST.
5065 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005066 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005067 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005068
5069 if (Notes.empty()) {
5070 // It's a constant expression.
5071 return Result;
5072 }
Richard Smithf8379a02012-01-18 23:55:52 +00005073 }
5074
5075 // It's not a constant expression. Produce an appropriate diagnostic.
5076 if (Notes.size() == 1 &&
5077 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5078 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5079 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005080 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005081 << CCE << From->getSourceRange();
5082 for (unsigned I = 0; I < Notes.size(); ++I)
5083 Diag(Notes[I].first, Notes[I].second);
5084 }
Richard Smith911e1422012-01-30 22:27:01 +00005085 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005086}
5087
John McCallfec112d2011-09-09 06:11:02 +00005088/// dropPointerConversions - If the given standard conversion sequence
5089/// involves any pointer conversions, remove them. This may change
5090/// the result type of the conversion sequence.
5091static void dropPointerConversion(StandardConversionSequence &SCS) {
5092 if (SCS.Second == ICK_Pointer_Conversion) {
5093 SCS.Second = ICK_Identity;
5094 SCS.Third = ICK_Identity;
5095 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5096 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005097}
John McCall5c32be02010-08-24 20:38:10 +00005098
John McCallfec112d2011-09-09 06:11:02 +00005099/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5100/// convert the expression From to an Objective-C pointer type.
5101static ImplicitConversionSequence
5102TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5103 // Do an implicit conversion to 'id'.
5104 QualType Ty = S.Context.getObjCIdType();
5105 ImplicitConversionSequence ICS
5106 = TryImplicitConversion(S, From, Ty,
5107 // FIXME: Are these flags correct?
5108 /*SuppressUserConversions=*/false,
5109 /*AllowExplicit=*/true,
5110 /*InOverloadResolution=*/false,
5111 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005112 /*AllowObjCWritebackConversion=*/false,
5113 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005114
5115 // Strip off any final conversions to 'id'.
5116 switch (ICS.getKind()) {
5117 case ImplicitConversionSequence::BadConversion:
5118 case ImplicitConversionSequence::AmbiguousConversion:
5119 case ImplicitConversionSequence::EllipsisConversion:
5120 break;
5121
5122 case ImplicitConversionSequence::UserDefinedConversion:
5123 dropPointerConversion(ICS.UserDefined.After);
5124 break;
5125
5126 case ImplicitConversionSequence::StandardConversion:
5127 dropPointerConversion(ICS.Standard);
5128 break;
5129 }
5130
5131 return ICS;
5132}
5133
5134/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5135/// conversion of the expression From to an Objective-C pointer type.
5136ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005137 if (checkPlaceholderForOverload(*this, From))
5138 return ExprError();
5139
John McCall8b07ec22010-05-15 11:32:37 +00005140 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005141 ImplicitConversionSequence ICS =
5142 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005143 if (!ICS.isBad())
5144 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005145 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005146}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005147
Richard Smith8dd34252012-02-04 07:07:42 +00005148/// Determine whether the provided type is an integral type, or an enumeration
5149/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005150bool Sema::ICEConvertDiagnoser::match(QualType T) {
5151 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5152 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005153}
5154
Larisse Voufo236bec22013-06-10 06:50:24 +00005155static ExprResult
5156diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5157 Sema::ContextualImplicitConverter &Converter,
5158 QualType T, UnresolvedSetImpl &ViableConversions) {
5159
5160 if (Converter.Suppress)
5161 return ExprError();
5162
5163 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5164 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5165 CXXConversionDecl *Conv =
5166 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5167 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5168 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5169 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005170 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005171}
5172
5173static bool
5174diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5175 Sema::ContextualImplicitConverter &Converter,
5176 QualType T, bool HadMultipleCandidates,
5177 UnresolvedSetImpl &ExplicitConversions) {
5178 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5179 DeclAccessPair Found = ExplicitConversions[0];
5180 CXXConversionDecl *Conversion =
5181 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5182
5183 // The user probably meant to invoke the given explicit
5184 // conversion; use it.
5185 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5186 std::string TypeStr;
5187 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5188
5189 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5190 << FixItHint::CreateInsertion(From->getLocStart(),
5191 "static_cast<" + TypeStr + ">(")
5192 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005193 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005194 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5195
5196 // If we aren't in a SFINAE context, build a call to the
5197 // explicit conversion function.
5198 if (SemaRef.isSFINAEContext())
5199 return true;
5200
Craig Topperc3ec1492014-05-26 06:22:03 +00005201 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005202 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5203 HadMultipleCandidates);
5204 if (Result.isInvalid())
5205 return true;
5206 // Record usage of conversion in an implicit cast.
5207 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005208 CK_UserDefinedConversion, Result.get(),
5209 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005210 }
5211 return false;
5212}
5213
5214static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5215 Sema::ContextualImplicitConverter &Converter,
5216 QualType T, bool HadMultipleCandidates,
5217 DeclAccessPair &Found) {
5218 CXXConversionDecl *Conversion =
5219 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005220 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005221
5222 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5223 if (!Converter.SuppressConversion) {
5224 if (SemaRef.isSFINAEContext())
5225 return true;
5226
5227 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5228 << From->getSourceRange();
5229 }
5230
5231 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5232 HadMultipleCandidates);
5233 if (Result.isInvalid())
5234 return true;
5235 // Record usage of conversion in an implicit cast.
5236 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005237 CK_UserDefinedConversion, Result.get(),
5238 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005239 return false;
5240}
5241
5242static ExprResult finishContextualImplicitConversion(
5243 Sema &SemaRef, SourceLocation Loc, Expr *From,
5244 Sema::ContextualImplicitConverter &Converter) {
5245 if (!Converter.match(From->getType()) && !Converter.Suppress)
5246 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5247 << From->getSourceRange();
5248
5249 return SemaRef.DefaultLvalueConversion(From);
5250}
5251
5252static void
5253collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5254 UnresolvedSetImpl &ViableConversions,
5255 OverloadCandidateSet &CandidateSet) {
5256 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5257 DeclAccessPair FoundDecl = ViableConversions[I];
5258 NamedDecl *D = FoundDecl.getDecl();
5259 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5260 if (isa<UsingShadowDecl>(D))
5261 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5262
5263 CXXConversionDecl *Conv;
5264 FunctionTemplateDecl *ConvTemplate;
5265 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5266 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5267 else
5268 Conv = cast<CXXConversionDecl>(D);
5269
5270 if (ConvTemplate)
5271 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005272 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5273 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005274 else
5275 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005276 ToType, CandidateSet,
5277 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005278 }
5279}
5280
Richard Smithccc11812013-05-21 19:05:48 +00005281/// \brief Attempt to convert the given expression to a type which is accepted
5282/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005283///
Richard Smithccc11812013-05-21 19:05:48 +00005284/// This routine will attempt to convert an expression of class type to a
5285/// type accepted by the specified converter. In C++11 and before, the class
5286/// must have a single non-explicit conversion function converting to a matching
5287/// type. In C++1y, there can be multiple such conversion functions, but only
5288/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005289///
Douglas Gregor4799d032010-06-30 00:20:43 +00005290/// \param Loc The source location of the construct that requires the
5291/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005292///
James Dennett18348b62012-06-22 08:52:37 +00005293/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005294///
Richard Smithccc11812013-05-21 19:05:48 +00005295/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005296///
Douglas Gregor4799d032010-06-30 00:20:43 +00005297/// \returns The expression, converted to an integral or enumeration type if
5298/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005299ExprResult Sema::PerformContextualImplicitConversion(
5300 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005301 // We can't perform any more checking for type-dependent expressions.
5302 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005303 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005304
Eli Friedman1da70392012-01-26 00:26:18 +00005305 // Process placeholders immediately.
5306 if (From->hasPlaceholderType()) {
5307 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005308 if (result.isInvalid())
5309 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005310 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005311 }
5312
Richard Smithccc11812013-05-21 19:05:48 +00005313 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005314 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005315 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005316 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005317
5318 // FIXME: Check for missing '()' if T is a function type?
5319
Richard Smithccc11812013-05-21 19:05:48 +00005320 // We can only perform contextual implicit conversions on objects of class
5321 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005322 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005323 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005324 if (!Converter.Suppress)
5325 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005326 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005329 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005330 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005331 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005332 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005333
5334 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5335 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5336
Craig Toppere14c0f82014-03-12 04:55:44 +00005337 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005338 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005339 }
Richard Smithccc11812013-05-21 19:05:48 +00005340 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005341
5342 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005343 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005344
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005345 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005346 UnresolvedSet<4>
5347 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005348 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005349 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005350 CXXRecordDecl::conversion_iterator> Conversions =
5351 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352
Larisse Voufo236bec22013-06-10 06:50:24 +00005353 bool HadMultipleCandidates =
5354 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005355
Larisse Voufo236bec22013-06-10 06:50:24 +00005356 // To check that there is only one target type, in C++1y:
5357 QualType ToType;
5358 bool HasUniqueTargetType = true;
5359
5360 // Collect explicit or viable (potentially in C++1y) conversions.
5361 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5362 E = Conversions.second;
5363 I != E; ++I) {
5364 NamedDecl *D = (*I)->getUnderlyingDecl();
5365 CXXConversionDecl *Conversion;
5366 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5367 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005368 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005369 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5370 else
5371 continue; // C++11 does not consider conversion operator templates(?).
5372 } else
5373 Conversion = cast<CXXConversionDecl>(D);
5374
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005375 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005376 "Conversion operator templates are considered potentially "
5377 "viable in C++1y");
5378
5379 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5380 if (Converter.match(CurToType) || ConvTemplate) {
5381
5382 if (Conversion->isExplicit()) {
5383 // FIXME: For C++1y, do we need this restriction?
5384 // cf. diagnoseNoViableConversion()
5385 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005386 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005387 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005388 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005389 if (ToType.isNull())
5390 ToType = CurToType.getUnqualifiedType();
5391 else if (HasUniqueTargetType &&
5392 (CurToType.getUnqualifiedType() != ToType))
5393 HasUniqueTargetType = false;
5394 }
5395 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005396 }
Richard Smith8dd34252012-02-04 07:07:42 +00005397 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005399
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005400 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005401 // C++1y [conv]p6:
5402 // ... An expression e of class type E appearing in such a context
5403 // is said to be contextually implicitly converted to a specified
5404 // type T and is well-formed if and only if e can be implicitly
5405 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005406 // for conversion functions whose return type is cv T or reference to
5407 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005408 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005409
Larisse Voufo236bec22013-06-10 06:50:24 +00005410 // If no unique T is found:
5411 if (ToType.isNull()) {
5412 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5413 HadMultipleCandidates,
5414 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005415 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005416 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005418
Larisse Voufo236bec22013-06-10 06:50:24 +00005419 // If more than one unique Ts are found:
5420 if (!HasUniqueTargetType)
5421 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5422 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423
Larisse Voufo236bec22013-06-10 06:50:24 +00005424 // If one unique T is found:
5425 // First, build a candidate set from the previously recorded
5426 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005427 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005428 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5429 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005430
Larisse Voufo236bec22013-06-10 06:50:24 +00005431 // Then, perform overload resolution over the candidate set.
5432 OverloadCandidateSet::iterator Best;
5433 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5434 case OR_Success: {
5435 // Apply this conversion.
5436 DeclAccessPair Found =
5437 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5438 if (recordConversion(*this, Loc, From, Converter, T,
5439 HadMultipleCandidates, Found))
5440 return ExprError();
5441 break;
5442 }
5443 case OR_Ambiguous:
5444 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5445 ViableConversions);
5446 case OR_No_Viable_Function:
5447 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5448 HadMultipleCandidates,
5449 ExplicitConversions))
5450 return ExprError();
5451 // fall through 'OR_Deleted' case.
5452 case OR_Deleted:
5453 // We'll complain below about a non-integral condition type.
5454 break;
5455 }
5456 } else {
5457 switch (ViableConversions.size()) {
5458 case 0: {
5459 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5460 HadMultipleCandidates,
5461 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005462 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463
Larisse Voufo236bec22013-06-10 06:50:24 +00005464 // We'll complain below about a non-integral condition type.
5465 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005466 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005467 case 1: {
5468 // Apply this conversion.
5469 DeclAccessPair Found = ViableConversions[0];
5470 if (recordConversion(*this, Loc, From, Converter, T,
5471 HadMultipleCandidates, Found))
5472 return ExprError();
5473 break;
5474 }
5475 default:
5476 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5477 ViableConversions);
5478 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480
Larisse Voufo236bec22013-06-10 06:50:24 +00005481 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005482}
5483
Richard Smith100b24a2014-04-17 01:52:14 +00005484/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5485/// an acceptable non-member overloaded operator for a call whose
5486/// arguments have types T1 (and, if non-empty, T2). This routine
5487/// implements the check in C++ [over.match.oper]p3b2 concerning
5488/// enumeration types.
5489static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5490 FunctionDecl *Fn,
5491 ArrayRef<Expr *> Args) {
5492 QualType T1 = Args[0]->getType();
5493 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5494
5495 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5496 return true;
5497
5498 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5499 return true;
5500
5501 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5502 if (Proto->getNumParams() < 1)
5503 return false;
5504
5505 if (T1->isEnumeralType()) {
5506 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5507 if (Context.hasSameUnqualifiedType(T1, ArgType))
5508 return true;
5509 }
5510
5511 if (Proto->getNumParams() < 2)
5512 return false;
5513
5514 if (!T2.isNull() && T2->isEnumeralType()) {
5515 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5516 if (Context.hasSameUnqualifiedType(T2, ArgType))
5517 return true;
5518 }
5519
5520 return false;
5521}
5522
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005523/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005524/// candidate functions, using the given function call arguments. If
5525/// @p SuppressUserConversions, then don't allow user-defined
5526/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005527///
James Dennett2a4d13c2012-06-15 07:13:21 +00005528/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005529/// based on an incomplete set of function arguments. This feature is used by
5530/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005531void
5532Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005533 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005534 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005535 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005536 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005537 bool PartialOverloading,
5538 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005539 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005540 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005541 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005542 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005543 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005544
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005545 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005546 if (!isa<CXXConstructorDecl>(Method)) {
5547 // If we get here, it's because we're calling a member function
5548 // that is named without a member access expression (e.g.,
5549 // "this->f") that was either written explicitly or created
5550 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005551 // function, e.g., X::f(). We use an empty type for the implied
5552 // object argument (C++ [over.call.func]p3), and the acting context
5553 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005554 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005556 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005557 return;
5558 }
5559 // We treat a constructor like a non-member function, since its object
5560 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005561 }
5562
Douglas Gregorff7028a2009-11-13 23:59:09 +00005563 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005564 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005565
Richard Smith100b24a2014-04-17 01:52:14 +00005566 // C++ [over.match.oper]p3:
5567 // if no operand has a class type, only those non-member functions in the
5568 // lookup set that have a first parameter of type T1 or "reference to
5569 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5570 // is a right operand) a second parameter of type T2 or "reference to
5571 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5572 // candidate functions.
5573 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5574 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5575 return;
5576
Richard Smith8b86f2d2013-11-04 01:48:18 +00005577 // C++11 [class.copy]p11: [DR1402]
5578 // A defaulted move constructor that is defined as deleted is ignored by
5579 // overload resolution.
5580 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5581 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5582 Constructor->isMoveConstructor())
5583 return;
5584
Douglas Gregor27381f32009-11-23 12:27:39 +00005585 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005586 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005587
Richard Smith8b86f2d2013-11-04 01:48:18 +00005588 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005589 // C++ [class.copy]p3:
5590 // A member function template is never instantiated to perform the copy
5591 // of a class object to an object of its class type.
5592 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005593 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005594 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005595 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5596 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005597 return;
5598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005599
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005600 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005601 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005602 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005603 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005604 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005605 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005606 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005607 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005609 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005610
5611 // (C++ 13.3.2p2): A candidate function having fewer than m
5612 // parameters is viable only if it has an ellipsis in its parameter
5613 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005614 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005615 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005616 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005617 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005618 return;
5619 }
5620
5621 // (C++ 13.3.2p2): A candidate function having more than m parameters
5622 // is viable only if the (m+1)st parameter has a default argument
5623 // (8.3.6). For the purposes of overload resolution, the
5624 // parameter list is truncated on the right, so that there are
5625 // exactly m parameters.
5626 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005627 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005628 // Not enough arguments.
5629 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005630 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005631 return;
5632 }
5633
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005634 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005635 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005636 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5637 if (CheckCUDATarget(Caller, Function)) {
5638 Candidate.Viable = false;
5639 Candidate.FailureKind = ovl_fail_bad_target;
5640 return;
5641 }
5642
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005643 // Determine the implicit conversion sequences for each of the
5644 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005645 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005646 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005647 // (C++ 13.3.2p3): for F to be a viable function, there shall
5648 // exist for each argument an implicit conversion sequence
5649 // (13.3.3.1) that converts that argument to the corresponding
5650 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005651 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005652 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005653 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005654 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005655 /*InOverloadResolution=*/true,
5656 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005657 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005658 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005659 if (Candidate.Conversions[ArgIdx].isBad()) {
5660 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005661 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005662 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005663 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005664 } else {
5665 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5666 // argument for which there is no corresponding parameter is
5667 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005668 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005669 }
5670 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005671
5672 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5673 Candidate.Viable = false;
5674 Candidate.FailureKind = ovl_fail_enable_if;
5675 Candidate.DeductionFailure.Data = FailedAttr;
5676 return;
5677 }
5678}
5679
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005680ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005681 bool IsInstance) {
5682 SmallVector<ObjCMethodDecl*, 4> Methods;
5683 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5684 return nullptr;
5685
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005686 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5687 bool Match = true;
5688 ObjCMethodDecl *Method = Methods[b];
5689 unsigned NumNamedArgs = Sel.getNumArgs();
5690 // Method might have more arguments than selector indicates. This is due
5691 // to addition of c-style arguments in method.
5692 if (Method->param_size() > NumNamedArgs)
5693 NumNamedArgs = Method->param_size();
5694 if (Args.size() < NumNamedArgs)
5695 continue;
5696
5697 for (unsigned i = 0; i < NumNamedArgs; i++) {
5698 // We can't do any type-checking on a type-dependent argument.
5699 if (Args[i]->isTypeDependent()) {
5700 Match = false;
5701 break;
5702 }
5703
5704 ParmVarDecl *param = Method->parameters()[i];
5705 Expr *argExpr = Args[i];
5706 assert(argExpr && "SelectBestMethod(): missing expression");
5707
5708 // Strip the unbridged-cast placeholder expression off unless it's
5709 // a consumed argument.
5710 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5711 !param->hasAttr<CFConsumedAttr>())
5712 argExpr = stripARCUnbridgedCast(argExpr);
5713
5714 // If the parameter is __unknown_anytype, move on to the next method.
5715 if (param->getType() == Context.UnknownAnyTy) {
5716 Match = false;
5717 break;
5718 }
5719
5720 ImplicitConversionSequence ConversionState
5721 = TryCopyInitialization(*this, argExpr, param->getType(),
5722 /*SuppressUserConversions*/false,
5723 /*InOverloadResolution=*/true,
5724 /*AllowObjCWritebackConversion=*/
5725 getLangOpts().ObjCAutoRefCount,
5726 /*AllowExplicit*/false);
5727 if (ConversionState.isBad()) {
5728 Match = false;
5729 break;
5730 }
5731 }
5732 // Promote additional arguments to variadic methods.
5733 if (Match && Method->isVariadic()) {
5734 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5735 if (Args[i]->isTypeDependent()) {
5736 Match = false;
5737 break;
5738 }
5739 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5740 nullptr);
5741 if (Arg.isInvalid()) {
5742 Match = false;
5743 break;
5744 }
5745 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005746 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005747 // Check for extra arguments to non-variadic methods.
5748 if (Args.size() != NumNamedArgs)
5749 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005750 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5751 // Special case when selectors have no argument. In this case, select
5752 // one with the most general result type of 'id'.
5753 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5754 QualType ReturnT = Methods[b]->getReturnType();
5755 if (ReturnT->isObjCIdType())
5756 return Methods[b];
5757 }
5758 }
5759 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005760
5761 if (Match)
5762 return Method;
5763 }
5764 return nullptr;
5765}
5766
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005767static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5768
5769EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5770 bool MissingImplicitThis) {
5771 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5772 // we need to find the first failing one.
5773 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005774 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005775 AttrVec Attrs = Function->getAttrs();
5776 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5777 IsNotEnableIfAttr);
5778 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005779 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005780 std::reverse(Attrs.begin(), E);
5781
5782 SFINAETrap Trap(*this);
5783
5784 // Convert the arguments.
5785 SmallVector<Expr *, 16> ConvertedArgs;
5786 bool InitializationFailed = false;
5787 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5788 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005789 !cast<CXXMethodDecl>(Function)->isStatic() &&
5790 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005791 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5792 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005793 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005794 Method, Method);
5795 if (R.isInvalid()) {
5796 InitializationFailed = true;
5797 break;
5798 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005799 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005800 } else {
5801 ExprResult R =
5802 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5803 Context,
5804 Function->getParamDecl(i)),
5805 SourceLocation(),
5806 Args[i]);
5807 if (R.isInvalid()) {
5808 InitializationFailed = true;
5809 break;
5810 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005811 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005812 }
5813 }
5814
5815 if (InitializationFailed || Trap.hasErrorOccurred())
5816 return cast<EnableIfAttr>(Attrs[0]);
5817
5818 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5819 APValue Result;
5820 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5821 if (!EIA->getCond()->EvaluateWithSubstitution(
Craig Topperf78d8492014-08-29 06:05:01 +00005822 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)) ||
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005823 !Result.isInt() || !Result.getInt().getBoolValue()) {
5824 return EIA;
5825 }
5826 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005827 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005828}
5829
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005830/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005831/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005832void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005833 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005834 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005835 bool SuppressUserConversions,
5836 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005837 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005838 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5839 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005840 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005841 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005842 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005843 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005844 Args.slice(1), CandidateSet,
5845 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005846 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005847 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005848 SuppressUserConversions);
5849 } else {
John McCalla0296f72010-03-19 07:35:19 +00005850 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005851 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5852 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005853 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005854 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005855 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005856 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005857 Args[0]->Classify(Context), Args.slice(1),
5858 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005859 else
John McCalla0296f72010-03-19 07:35:19 +00005860 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005861 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005862 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005863 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005864 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005865}
5866
John McCallf0f1cf02009-11-17 07:50:12 +00005867/// AddMethodCandidate - Adds a named decl (which is some kind of
5868/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005869void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005870 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005871 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005872 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005873 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005874 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005875 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005876 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005877
5878 if (isa<UsingShadowDecl>(Decl))
5879 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005880
John McCallf0f1cf02009-11-17 07:50:12 +00005881 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5882 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5883 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005884 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005885 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005886 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005887 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005888 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005889 } else {
John McCalla0296f72010-03-19 07:35:19 +00005890 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005891 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005892 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005893 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005894 }
5895}
5896
Douglas Gregor436424c2008-11-18 23:14:02 +00005897/// AddMethodCandidate - Adds the given C++ member function to the set
5898/// of candidate functions, using the given function call arguments
5899/// and the object argument (@c Object). For example, in a call
5900/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5901/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5902/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005903/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005904void
John McCalla0296f72010-03-19 07:35:19 +00005905Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005906 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005907 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005908 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005909 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005910 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005911 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005912 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005913 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005914 assert(!isa<CXXConstructorDecl>(Method) &&
5915 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005916
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005917 if (!CandidateSet.isNewCandidate(Method))
5918 return;
5919
Richard Smith8b86f2d2013-11-04 01:48:18 +00005920 // C++11 [class.copy]p23: [DR1402]
5921 // A defaulted move assignment operator that is defined as deleted is
5922 // ignored by overload resolution.
5923 if (Method->isDefaulted() && Method->isDeleted() &&
5924 Method->isMoveAssignmentOperator())
5925 return;
5926
Douglas Gregor27381f32009-11-23 12:27:39 +00005927 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005928 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005929
Douglas Gregor436424c2008-11-18 23:14:02 +00005930 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005931 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005932 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005933 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005934 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005935 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005936 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005937
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005938 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005939
5940 // (C++ 13.3.2p2): A candidate function having fewer than m
5941 // parameters is viable only if it has an ellipsis in its parameter
5942 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005943 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005944 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005945 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005946 return;
5947 }
5948
5949 // (C++ 13.3.2p2): A candidate function having more than m parameters
5950 // is viable only if the (m+1)st parameter has a default argument
5951 // (8.3.6). For the purposes of overload resolution, the
5952 // parameter list is truncated on the right, so that there are
5953 // exactly m parameters.
5954 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005955 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005956 // Not enough arguments.
5957 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005958 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005959 return;
5960 }
5961
5962 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005963
John McCall6e9f8f62009-12-03 04:06:58 +00005964 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005965 // The implicit object argument is ignored.
5966 Candidate.IgnoreObjectArgument = true;
5967 else {
5968 // Determine the implicit conversion sequence for the object
5969 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005970 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005971 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5972 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005973 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005974 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005975 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005976 return;
5977 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005978 }
5979
Eli Bendersky291a57e2014-09-25 23:59:08 +00005980 // (CUDA B.1): Check for invalid calls between targets.
5981 if (getLangOpts().CUDA)
5982 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5983 if (CheckCUDATarget(Caller, Method)) {
5984 Candidate.Viable = false;
5985 Candidate.FailureKind = ovl_fail_bad_target;
5986 return;
5987 }
5988
Douglas Gregor436424c2008-11-18 23:14:02 +00005989 // Determine the implicit conversion sequences for each of the
5990 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005991 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005992 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005993 // (C++ 13.3.2p3): for F to be a viable function, there shall
5994 // exist for each argument an implicit conversion sequence
5995 // (13.3.3.1) that converts that argument to the corresponding
5996 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005997 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005998 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005999 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006000 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006001 /*InOverloadResolution=*/true,
6002 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006003 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006004 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006005 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006006 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006007 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006008 }
6009 } else {
6010 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6011 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006012 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006013 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006014 }
6015 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006016
6017 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6018 Candidate.Viable = false;
6019 Candidate.FailureKind = ovl_fail_enable_if;
6020 Candidate.DeductionFailure.Data = FailedAttr;
6021 return;
6022 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006023}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024
Douglas Gregor97628d62009-08-21 00:16:32 +00006025/// \brief Add a C++ member function template as a candidate to the candidate
6026/// set, using template argument deduction to produce an appropriate member
6027/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006028void
Douglas Gregor97628d62009-08-21 00:16:32 +00006029Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006030 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006031 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006032 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006033 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006034 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006035 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006036 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006037 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006038 if (!CandidateSet.isNewCandidate(MethodTmpl))
6039 return;
6040
Douglas Gregor97628d62009-08-21 00:16:32 +00006041 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006042 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006043 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006044 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006045 // candidate functions in the usual way.113) A given name can refer to one
6046 // or more function templates and also to a set of overloaded non-template
6047 // functions. In such a case, the candidate functions generated from each
6048 // function template are combined with the set of non-template candidate
6049 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006050 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006051 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006052 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006053 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6054 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006055 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006056 Candidate.FoundDecl = FoundDecl;
6057 Candidate.Function = MethodTmpl->getTemplatedDecl();
6058 Candidate.Viable = false;
6059 Candidate.FailureKind = ovl_fail_bad_deduction;
6060 Candidate.IsSurrogate = false;
6061 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006062 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006063 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006064 Info);
6065 return;
6066 }
Mike Stump11289f42009-09-09 15:08:12 +00006067
Douglas Gregor97628d62009-08-21 00:16:32 +00006068 // Add the function template specialization produced by template argument
6069 // deduction as a candidate.
6070 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006071 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006072 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006073 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006074 ActingContext, ObjectType, ObjectClassification, Args,
6075 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006076}
6077
Douglas Gregor05155d82009-08-21 23:19:43 +00006078/// \brief Add a C++ function template specialization as a candidate
6079/// in the candidate set, using template argument deduction to produce
6080/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006081void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006082Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006083 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006084 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006085 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006086 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006087 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006088 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6089 return;
6090
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006091 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006092 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006093 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006094 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006095 // candidate functions in the usual way.113) A given name can refer to one
6096 // or more function templates and also to a set of overloaded non-template
6097 // functions. In such a case, the candidate functions generated from each
6098 // function template are combined with the set of non-template candidate
6099 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006100 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006101 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006102 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006103 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6104 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006105 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006106 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006107 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6108 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006109 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006110 Candidate.IsSurrogate = false;
6111 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006112 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006113 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006114 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006115 return;
6116 }
Mike Stump11289f42009-09-09 15:08:12 +00006117
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006118 // Add the function template specialization produced by template argument
6119 // deduction as a candidate.
6120 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006121 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006122 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006123}
Mike Stump11289f42009-09-09 15:08:12 +00006124
Douglas Gregor4b60a152013-11-07 22:34:54 +00006125/// Determine whether this is an allowable conversion from the result
6126/// of an explicit conversion operator to the expected type, per C++
6127/// [over.match.conv]p1 and [over.match.ref]p1.
6128///
6129/// \param ConvType The return type of the conversion function.
6130///
6131/// \param ToType The type we are converting to.
6132///
6133/// \param AllowObjCPointerConversion Allow a conversion from one
6134/// Objective-C pointer to another.
6135///
6136/// \returns true if the conversion is allowable, false otherwise.
6137static bool isAllowableExplicitConversion(Sema &S,
6138 QualType ConvType, QualType ToType,
6139 bool AllowObjCPointerConversion) {
6140 QualType ToNonRefType = ToType.getNonReferenceType();
6141
6142 // Easy case: the types are the same.
6143 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6144 return true;
6145
6146 // Allow qualification conversions.
6147 bool ObjCLifetimeConversion;
6148 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6149 ObjCLifetimeConversion))
6150 return true;
6151
6152 // If we're not allowed to consider Objective-C pointer conversions,
6153 // we're done.
6154 if (!AllowObjCPointerConversion)
6155 return false;
6156
6157 // Is this an Objective-C pointer conversion?
6158 bool IncompatibleObjC = false;
6159 QualType ConvertedType;
6160 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6161 IncompatibleObjC);
6162}
6163
Douglas Gregora1f013e2008-11-07 22:36:19 +00006164/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006165/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006166/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006167/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006168/// (which may or may not be the same type as the type that the
6169/// conversion function produces).
6170void
6171Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006172 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006173 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006174 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006175 OverloadCandidateSet& CandidateSet,
6176 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006177 assert(!Conversion->getDescribedFunctionTemplate() &&
6178 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006179 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006180 if (!CandidateSet.isNewCandidate(Conversion))
6181 return;
6182
Richard Smith2a7d4812013-05-04 07:00:32 +00006183 // If the conversion function has an undeduced return type, trigger its
6184 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006185 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006186 if (DeduceReturnType(Conversion, From->getExprLoc()))
6187 return;
6188 ConvType = Conversion->getConversionType().getNonReferenceType();
6189 }
6190
Richard Smith089c3162013-09-21 21:55:46 +00006191 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6192 // operator is only a candidate if its return type is the target type or
6193 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006194 if (Conversion->isExplicit() &&
6195 !isAllowableExplicitConversion(*this, ConvType, ToType,
6196 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006197 return;
6198
Douglas Gregor27381f32009-11-23 12:27:39 +00006199 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006200 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006201
Douglas Gregora1f013e2008-11-07 22:36:19 +00006202 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006203 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006204 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006205 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006206 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006207 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006208 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006209 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006210 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006211 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006212 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006213
Douglas Gregor6affc782010-08-19 15:37:02 +00006214 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006215 // For conversion functions, the function is considered to be a member of
6216 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006217 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006218 //
6219 // Determine the implicit conversion sequence for the implicit
6220 // object parameter.
6221 QualType ImplicitParamType = From->getType();
6222 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6223 ImplicitParamType = FromPtrType->getPointeeType();
6224 CXXRecordDecl *ConversionContext
6225 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006226
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006227 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006228 = TryObjectArgumentInitialization(*this, From->getType(),
6229 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006230 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006231
John McCall0d1da222010-01-12 00:44:57 +00006232 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006233 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006234 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006235 return;
6236 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006237
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006238 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006239 // derived to base as such conversions are given Conversion Rank. They only
6240 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6241 QualType FromCanon
6242 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6243 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6244 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6245 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006246 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006247 return;
6248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006249
Douglas Gregora1f013e2008-11-07 22:36:19 +00006250 // To determine what the conversion from the result of calling the
6251 // conversion function to the type we're eventually trying to
6252 // convert to (ToType), we need to synthesize a call to the
6253 // conversion function and attempt copy initialization from it. This
6254 // makes sure that we get the right semantics with respect to
6255 // lvalues/rvalues and the type. Fortunately, we can allocate this
6256 // call on the stack and we don't need its arguments to be
6257 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006258 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006259 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006260 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6261 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006262 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006263 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006264
Richard Smith48d24642011-07-13 22:53:21 +00006265 QualType ConversionType = Conversion->getConversionType();
6266 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006267 Candidate.Viable = false;
6268 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6269 return;
6270 }
6271
Richard Smith48d24642011-07-13 22:53:21 +00006272 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006273
Mike Stump11289f42009-09-09 15:08:12 +00006274 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006275 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6276 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006277 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006278 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006279 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006280 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006281 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006282 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006283 /*InOverloadResolution=*/false,
6284 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006285
John McCall0d1da222010-01-12 00:44:57 +00006286 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006287 case ImplicitConversionSequence::StandardConversion:
6288 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006289
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006290 // C++ [over.ics.user]p3:
6291 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006292 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006293 // shall have exact match rank.
6294 if (Conversion->getPrimaryTemplate() &&
6295 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6296 Candidate.Viable = false;
6297 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006298 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006299 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006300
Douglas Gregorcba72b12011-01-21 05:18:22 +00006301 // C++0x [dcl.init.ref]p5:
6302 // In the second case, if the reference is an rvalue reference and
6303 // the second standard conversion sequence of the user-defined
6304 // conversion sequence includes an lvalue-to-rvalue conversion, the
6305 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006306 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006307 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6308 Candidate.Viable = false;
6309 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006310 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006311 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006312 break;
6313
6314 case ImplicitConversionSequence::BadConversion:
6315 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006316 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006317 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006318
6319 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006320 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006321 "Can only end up with a standard conversion sequence or failure");
6322 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006323
Craig Topper5fc8fc22014-08-27 06:28:36 +00006324 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006325 Candidate.Viable = false;
6326 Candidate.FailureKind = ovl_fail_enable_if;
6327 Candidate.DeductionFailure.Data = FailedAttr;
6328 return;
6329 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006330}
6331
Douglas Gregor05155d82009-08-21 23:19:43 +00006332/// \brief Adds a conversion function template specialization
6333/// candidate to the overload set, using template argument deduction
6334/// to deduce the template arguments of the conversion function
6335/// template from the type that we are converting to (C++
6336/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006337void
Douglas Gregor05155d82009-08-21 23:19:43 +00006338Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006339 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006340 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006341 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006342 OverloadCandidateSet &CandidateSet,
6343 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006344 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6345 "Only conversion function templates permitted here");
6346
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006347 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6348 return;
6349
Craig Toppere6706e42012-09-19 02:26:47 +00006350 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006351 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006352 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006353 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006354 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006355 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006356 Candidate.FoundDecl = FoundDecl;
6357 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6358 Candidate.Viable = false;
6359 Candidate.FailureKind = ovl_fail_bad_deduction;
6360 Candidate.IsSurrogate = false;
6361 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006362 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006363 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006364 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006365 return;
6366 }
Mike Stump11289f42009-09-09 15:08:12 +00006367
Douglas Gregor05155d82009-08-21 23:19:43 +00006368 // Add the conversion function template specialization produced by
6369 // template argument deduction as a candidate.
6370 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006371 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006372 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006373}
6374
Douglas Gregorab7897a2008-11-19 22:57:39 +00006375/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6376/// converts the given @c Object to a function pointer via the
6377/// conversion function @c Conversion, and then attempts to call it
6378/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6379/// the type of function that we'll eventually be calling.
6380void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006381 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006382 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006383 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006384 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006385 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006386 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006387 if (!CandidateSet.isNewCandidate(Conversion))
6388 return;
6389
Douglas Gregor27381f32009-11-23 12:27:39 +00006390 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006391 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006392
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006393 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006394 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006395 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006396 Candidate.Surrogate = Conversion;
6397 Candidate.Viable = true;
6398 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006399 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006400 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006401
6402 // Determine the implicit conversion sequence for the implicit
6403 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006404 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006405 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006406 Object->Classify(Context),
6407 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006408 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006409 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006410 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006411 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006412 return;
6413 }
6414
6415 // The first conversion is actually a user-defined conversion whose
6416 // first conversion is ObjectInit's standard conversion (which is
6417 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006418 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006419 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006420 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006421 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006422 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006423 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006424 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006425 = Candidate.Conversions[0].UserDefined.Before;
6426 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6427
Mike Stump11289f42009-09-09 15:08:12 +00006428 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006429 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006430
6431 // (C++ 13.3.2p2): A candidate function having fewer than m
6432 // parameters is viable only if it has an ellipsis in its parameter
6433 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006434 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006435 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006436 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006437 return;
6438 }
6439
6440 // Function types don't have any default arguments, so just check if
6441 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006442 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006443 // Not enough arguments.
6444 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006445 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006446 return;
6447 }
6448
6449 // Determine the implicit conversion sequences for each of the
6450 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006451 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006452 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006453 // (C++ 13.3.2p3): for F to be a viable function, there shall
6454 // exist for each argument an implicit conversion sequence
6455 // (13.3.3.1) that converts that argument to the corresponding
6456 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006457 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006458 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006459 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006460 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006461 /*InOverloadResolution=*/false,
6462 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006463 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006464 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006465 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006466 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006467 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006468 }
6469 } else {
6470 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6471 // argument for which there is no corresponding parameter is
6472 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006473 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006474 }
6475 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006476
Craig Topper5fc8fc22014-08-27 06:28:36 +00006477 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006478 Candidate.Viable = false;
6479 Candidate.FailureKind = ovl_fail_enable_if;
6480 Candidate.DeductionFailure.Data = FailedAttr;
6481 return;
6482 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006483}
6484
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006485/// \brief Add overload candidates for overloaded operators that are
6486/// member functions.
6487///
6488/// Add the overloaded operator candidates that are member functions
6489/// for the operator Op that was used in an operator expression such
6490/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6491/// CandidateSet will store the added overload candidates. (C++
6492/// [over.match.oper]).
6493void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6494 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006495 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006496 OverloadCandidateSet& CandidateSet,
6497 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006498 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6499
6500 // C++ [over.match.oper]p3:
6501 // For a unary operator @ with an operand of a type whose
6502 // cv-unqualified version is T1, and for a binary operator @ with
6503 // a left operand of a type whose cv-unqualified version is T1 and
6504 // a right operand of a type whose cv-unqualified version is T2,
6505 // three sets of candidate functions, designated member
6506 // candidates, non-member candidates and built-in candidates, are
6507 // constructed as follows:
6508 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006509
Richard Smith0feaf0c2013-04-20 12:41:22 +00006510 // -- If T1 is a complete class type or a class currently being
6511 // defined, the set of member candidates is the result of the
6512 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6513 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006514 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006515 // Complete the type if it can be completed.
6516 RequireCompleteType(OpLoc, T1, 0);
6517 // If the type is neither complete nor being defined, bail out now.
6518 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006519 return;
Mike Stump11289f42009-09-09 15:08:12 +00006520
John McCall27b18f82009-11-17 02:14:36 +00006521 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6522 LookupQualifiedName(Operators, T1Rec->getDecl());
6523 Operators.suppressDiagnostics();
6524
Mike Stump11289f42009-09-09 15:08:12 +00006525 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006526 OperEnd = Operators.end();
6527 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006528 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006529 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006530 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006531 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006532 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006533 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006534 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006535}
6536
Douglas Gregora11693b2008-11-12 17:17:38 +00006537/// AddBuiltinCandidate - Add a candidate for a built-in
6538/// operator. ResultTy and ParamTys are the result and parameter types
6539/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006540/// arguments being passed to the candidate. IsAssignmentOperator
6541/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006542/// operator. NumContextualBoolArguments is the number of arguments
6543/// (at the beginning of the argument list) that will be contextually
6544/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006545void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006546 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006547 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006548 bool IsAssignmentOperator,
6549 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006550 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006551 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006552
Douglas Gregora11693b2008-11-12 17:17:38 +00006553 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006554 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006555 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6556 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006557 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006558 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006559 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006560 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006561 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6562
6563 // Determine the implicit conversion sequences for each of the
6564 // arguments.
6565 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006566 Candidate.ExplicitCallArguments = Args.size();
6567 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006568 // C++ [over.match.oper]p4:
6569 // For the built-in assignment operators, conversions of the
6570 // left operand are restricted as follows:
6571 // -- no temporaries are introduced to hold the left operand, and
6572 // -- no user-defined conversions are applied to the left
6573 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006574 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006575 //
6576 // We block these conversions by turning off user-defined
6577 // conversions, since that is the only way that initialization of
6578 // a reference to a non-class type can occur from something that
6579 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006580 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006581 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006582 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006583 Candidate.Conversions[ArgIdx]
6584 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006585 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006586 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006587 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006588 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006589 /*InOverloadResolution=*/false,
6590 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006591 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006592 }
John McCall0d1da222010-01-12 00:44:57 +00006593 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006594 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006595 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006596 break;
6597 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006598 }
6599}
6600
Craig Toppercd7b0332013-07-01 06:29:40 +00006601namespace {
6602
Douglas Gregora11693b2008-11-12 17:17:38 +00006603/// BuiltinCandidateTypeSet - A set of types that will be used for the
6604/// candidate operator functions for built-in operators (C++
6605/// [over.built]). The types are separated into pointer types and
6606/// enumeration types.
6607class BuiltinCandidateTypeSet {
6608 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006609 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006610
6611 /// PointerTypes - The set of pointer types that will be used in the
6612 /// built-in candidates.
6613 TypeSet PointerTypes;
6614
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006615 /// MemberPointerTypes - The set of member pointer types that will be
6616 /// used in the built-in candidates.
6617 TypeSet MemberPointerTypes;
6618
Douglas Gregora11693b2008-11-12 17:17:38 +00006619 /// EnumerationTypes - The set of enumeration types that will be
6620 /// used in the built-in candidates.
6621 TypeSet EnumerationTypes;
6622
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006623 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006624 /// candidates.
6625 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006626
6627 /// \brief A flag indicating non-record types are viable candidates
6628 bool HasNonRecordTypes;
6629
6630 /// \brief A flag indicating whether either arithmetic or enumeration types
6631 /// were present in the candidate set.
6632 bool HasArithmeticOrEnumeralTypes;
6633
Douglas Gregor80af3132011-05-21 23:15:46 +00006634 /// \brief A flag indicating whether the nullptr type was present in the
6635 /// candidate set.
6636 bool HasNullPtrType;
6637
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006638 /// Sema - The semantic analysis instance where we are building the
6639 /// candidate type set.
6640 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006641
Douglas Gregora11693b2008-11-12 17:17:38 +00006642 /// Context - The AST context in which we will build the type sets.
6643 ASTContext &Context;
6644
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006645 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6646 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006647 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006648
6649public:
6650 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006651 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006652
Mike Stump11289f42009-09-09 15:08:12 +00006653 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006654 : HasNonRecordTypes(false),
6655 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006656 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006657 SemaRef(SemaRef),
6658 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006659
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006660 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006661 SourceLocation Loc,
6662 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006663 bool AllowExplicitConversions,
6664 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006665
6666 /// pointer_begin - First pointer type found;
6667 iterator pointer_begin() { return PointerTypes.begin(); }
6668
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006669 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006670 iterator pointer_end() { return PointerTypes.end(); }
6671
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006672 /// member_pointer_begin - First member pointer type found;
6673 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6674
6675 /// member_pointer_end - Past the last member pointer type found;
6676 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6677
Douglas Gregora11693b2008-11-12 17:17:38 +00006678 /// enumeration_begin - First enumeration type found;
6679 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6680
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006681 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006682 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006684 iterator vector_begin() { return VectorTypes.begin(); }
6685 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006686
6687 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6688 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006689 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006690};
6691
Craig Toppercd7b0332013-07-01 06:29:40 +00006692} // end anonymous namespace
6693
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006694/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006695/// the set of pointer types along with any more-qualified variants of
6696/// that type. For example, if @p Ty is "int const *", this routine
6697/// will add "int const *", "int const volatile *", "int const
6698/// restrict *", and "int const volatile restrict *" to the set of
6699/// pointer types. Returns true if the add of @p Ty itself succeeded,
6700/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006701///
6702/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006703bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006704BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6705 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006706
Douglas Gregora11693b2008-11-12 17:17:38 +00006707 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006708 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006709 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006710
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006711 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006712 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006713 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006714 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006715 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6716 PointeeTy = PTy->getPointeeType();
6717 buildObjCPtr = true;
6718 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006719 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006720 }
6721
Sebastian Redl4990a632009-11-18 20:39:26 +00006722 // Don't add qualified variants of arrays. For one, they're not allowed
6723 // (the qualifier would sink to the element type), and for another, the
6724 // only overload situation where it matters is subscript or pointer +- int,
6725 // and those shouldn't have qualifier variants anyway.
6726 if (PointeeTy->isArrayType())
6727 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006728
John McCall8ccfcb52009-09-24 19:53:00 +00006729 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006730 bool hasVolatile = VisibleQuals.hasVolatile();
6731 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006732
John McCall8ccfcb52009-09-24 19:53:00 +00006733 // Iterate through all strict supersets of BaseCVR.
6734 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6735 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006736 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006737 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006738
6739 // Skip over restrict if no restrict found anywhere in the types, or if
6740 // the type cannot be restrict-qualified.
6741 if ((CVR & Qualifiers::Restrict) &&
6742 (!hasRestrict ||
6743 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6744 continue;
6745
6746 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006747 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006748
6749 // Build qualified pointer type.
6750 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006751 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006752 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006753 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006754 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6755
6756 // Insert qualified pointer type.
6757 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006758 }
6759
6760 return true;
6761}
6762
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006763/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6764/// to the set of pointer types along with any more-qualified variants of
6765/// that type. For example, if @p Ty is "int const *", this routine
6766/// will add "int const *", "int const volatile *", "int const
6767/// restrict *", and "int const volatile restrict *" to the set of
6768/// pointer types. Returns true if the add of @p Ty itself succeeded,
6769/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006770///
6771/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006772bool
6773BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6774 QualType Ty) {
6775 // Insert this type.
6776 if (!MemberPointerTypes.insert(Ty))
6777 return false;
6778
John McCall8ccfcb52009-09-24 19:53:00 +00006779 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6780 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006781
John McCall8ccfcb52009-09-24 19:53:00 +00006782 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006783 // Don't add qualified variants of arrays. For one, they're not allowed
6784 // (the qualifier would sink to the element type), and for another, the
6785 // only overload situation where it matters is subscript or pointer +- int,
6786 // and those shouldn't have qualifier variants anyway.
6787 if (PointeeTy->isArrayType())
6788 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006789 const Type *ClassTy = PointerTy->getClass();
6790
6791 // Iterate through all strict supersets of the pointee type's CVR
6792 // qualifiers.
6793 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6794 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6795 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006796
John McCall8ccfcb52009-09-24 19:53:00 +00006797 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006798 MemberPointerTypes.insert(
6799 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006800 }
6801
6802 return true;
6803}
6804
Douglas Gregora11693b2008-11-12 17:17:38 +00006805/// AddTypesConvertedFrom - Add each of the types to which the type @p
6806/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006807/// primarily interested in pointer types and enumeration types. We also
6808/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006809/// AllowUserConversions is true if we should look at the conversion
6810/// functions of a class type, and AllowExplicitConversions if we
6811/// should also include the explicit conversion functions of a class
6812/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006813void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006814BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006815 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006816 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006817 bool AllowExplicitConversions,
6818 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006819 // Only deal with canonical types.
6820 Ty = Context.getCanonicalType(Ty);
6821
6822 // Look through reference types; they aren't part of the type of an
6823 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006824 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006825 Ty = RefTy->getPointeeType();
6826
John McCall33ddac02011-01-19 10:06:00 +00006827 // If we're dealing with an array type, decay to the pointer.
6828 if (Ty->isArrayType())
6829 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6830
6831 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006832 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006833
Chandler Carruth00a38332010-12-13 01:44:01 +00006834 // Flag if we ever add a non-record type.
6835 const RecordType *TyRec = Ty->getAs<RecordType>();
6836 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6837
Chandler Carruth00a38332010-12-13 01:44:01 +00006838 // Flag if we encounter an arithmetic type.
6839 HasArithmeticOrEnumeralTypes =
6840 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6841
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006842 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6843 PointerTypes.insert(Ty);
6844 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006845 // Insert our type, and its more-qualified variants, into the set
6846 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006847 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006848 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006849 } else if (Ty->isMemberPointerType()) {
6850 // Member pointers are far easier, since the pointee can't be converted.
6851 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6852 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006853 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006854 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006855 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006856 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006857 // We treat vector types as arithmetic types in many contexts as an
6858 // extension.
6859 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006860 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006861 } else if (Ty->isNullPtrType()) {
6862 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006863 } else if (AllowUserConversions && TyRec) {
6864 // No conversion functions in incomplete types.
6865 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6866 return;
Mike Stump11289f42009-09-09 15:08:12 +00006867
Chandler Carruth00a38332010-12-13 01:44:01 +00006868 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006869 std::pair<CXXRecordDecl::conversion_iterator,
6870 CXXRecordDecl::conversion_iterator>
6871 Conversions = ClassDecl->getVisibleConversionFunctions();
6872 for (CXXRecordDecl::conversion_iterator
6873 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006874 NamedDecl *D = I.getDecl();
6875 if (isa<UsingShadowDecl>(D))
6876 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006877
Chandler Carruth00a38332010-12-13 01:44:01 +00006878 // Skip conversion function templates; they don't tell us anything
6879 // about which builtin types we can convert to.
6880 if (isa<FunctionTemplateDecl>(D))
6881 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006882
Chandler Carruth00a38332010-12-13 01:44:01 +00006883 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6884 if (AllowExplicitConversions || !Conv->isExplicit()) {
6885 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6886 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006887 }
6888 }
6889 }
6890}
6891
Douglas Gregor84605ae2009-08-24 13:43:27 +00006892/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6893/// the volatile- and non-volatile-qualified assignment operators for the
6894/// given type to the candidate set.
6895static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6896 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006897 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006898 OverloadCandidateSet &CandidateSet) {
6899 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006900
Douglas Gregor84605ae2009-08-24 13:43:27 +00006901 // T& operator=(T&, T)
6902 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6903 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006904 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006905 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006906
Douglas Gregor84605ae2009-08-24 13:43:27 +00006907 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6908 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006909 ParamTypes[0]
6910 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006911 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006912 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006913 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006914 }
6915}
Mike Stump11289f42009-09-09 15:08:12 +00006916
Sebastian Redl1054fae2009-10-25 17:03:50 +00006917/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6918/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006919static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6920 Qualifiers VRQuals;
6921 const RecordType *TyRec;
6922 if (const MemberPointerType *RHSMPType =
6923 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006924 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006925 else
6926 TyRec = ArgExpr->getType()->getAs<RecordType>();
6927 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006928 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006929 VRQuals.addVolatile();
6930 VRQuals.addRestrict();
6931 return VRQuals;
6932 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006933
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006934 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006935 if (!ClassDecl->hasDefinition())
6936 return VRQuals;
6937
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006938 std::pair<CXXRecordDecl::conversion_iterator,
6939 CXXRecordDecl::conversion_iterator>
6940 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006941
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006942 for (CXXRecordDecl::conversion_iterator
6943 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006944 NamedDecl *D = I.getDecl();
6945 if (isa<UsingShadowDecl>(D))
6946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6947 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006948 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6949 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6950 CanTy = ResTypeRef->getPointeeType();
6951 // Need to go down the pointer/mempointer chain and add qualifiers
6952 // as see them.
6953 bool done = false;
6954 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006955 if (CanTy.isRestrictQualified())
6956 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006957 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6958 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006959 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006960 CanTy->getAs<MemberPointerType>())
6961 CanTy = ResTypeMPtr->getPointeeType();
6962 else
6963 done = true;
6964 if (CanTy.isVolatileQualified())
6965 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006966 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6967 return VRQuals;
6968 }
6969 }
6970 }
6971 return VRQuals;
6972}
John McCall52872982010-11-13 05:51:15 +00006973
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006974namespace {
John McCall52872982010-11-13 05:51:15 +00006975
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006976/// \brief Helper class to manage the addition of builtin operator overload
6977/// candidates. It provides shared state and utility methods used throughout
6978/// the process, as well as a helper method to add each group of builtin
6979/// operator overloads from the standard to a candidate set.
6980class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006981 // Common instance state available to all overload candidate addition methods.
6982 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006983 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006984 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006985 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006986 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006987 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006988
Chandler Carruthc6586e52010-12-12 10:35:00 +00006989 // Define some constants used to index and iterate over the arithemetic types
6990 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006991 // The "promoted arithmetic types" are the arithmetic
6992 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006993 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006994 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006995 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006996 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006997 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006998 LastPromotedArithmeticType = 11;
6999 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007000
Chandler Carruthc6586e52010-12-12 10:35:00 +00007001 /// \brief Get the canonical type for a given arithmetic type index.
7002 CanQualType getArithmeticType(unsigned index) {
7003 assert(index < NumArithmeticTypes);
7004 static CanQualType ASTContext::* const
7005 ArithmeticTypes[NumArithmeticTypes] = {
7006 // Start of promoted types.
7007 &ASTContext::FloatTy,
7008 &ASTContext::DoubleTy,
7009 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007010
Chandler Carruthc6586e52010-12-12 10:35:00 +00007011 // Start of integral types.
7012 &ASTContext::IntTy,
7013 &ASTContext::LongTy,
7014 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007015 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007016 &ASTContext::UnsignedIntTy,
7017 &ASTContext::UnsignedLongTy,
7018 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007019 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007020 // End of promoted types.
7021
7022 &ASTContext::BoolTy,
7023 &ASTContext::CharTy,
7024 &ASTContext::WCharTy,
7025 &ASTContext::Char16Ty,
7026 &ASTContext::Char32Ty,
7027 &ASTContext::SignedCharTy,
7028 &ASTContext::ShortTy,
7029 &ASTContext::UnsignedCharTy,
7030 &ASTContext::UnsignedShortTy,
7031 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007032 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007033 };
7034 return S.Context.*ArithmeticTypes[index];
7035 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007036
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007037 /// \brief Gets the canonical type resulting from the usual arithemetic
7038 /// converions for the given arithmetic types.
7039 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7040 // Accelerator table for performing the usual arithmetic conversions.
7041 // The rules are basically:
7042 // - if either is floating-point, use the wider floating-point
7043 // - if same signedness, use the higher rank
7044 // - if same size, use unsigned of the higher rank
7045 // - use the larger type
7046 // These rules, together with the axiom that higher ranks are
7047 // never smaller, are sufficient to precompute all of these results
7048 // *except* when dealing with signed types of higher rank.
7049 // (we could precompute SLL x UI for all known platforms, but it's
7050 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007051 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007052 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007053 Dep=-1,
7054 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007055 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007056 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007057 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007058/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7059/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7060/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7061/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7062/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7063/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7064/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7065/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7066/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7067/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7068/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007069 };
7070
7071 assert(L < LastPromotedArithmeticType);
7072 assert(R < LastPromotedArithmeticType);
7073 int Idx = ConversionsTable[L][R];
7074
7075 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007076 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007077
7078 // Slow path: we need to compare widths.
7079 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007080 CanQualType LT = getArithmeticType(L),
7081 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007082 unsigned LW = S.Context.getIntWidth(LT),
7083 RW = S.Context.getIntWidth(RT);
7084
7085 // If they're different widths, use the signed type.
7086 if (LW > RW) return LT;
7087 else if (LW < RW) return RT;
7088
7089 // Otherwise, use the unsigned type of the signed type's rank.
7090 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7091 assert(L == SLL || R == SLL);
7092 return S.Context.UnsignedLongLongTy;
7093 }
7094
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007095 /// \brief Helper method to factor out the common pattern of adding overloads
7096 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007097 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007098 bool HasVolatile,
7099 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007100 QualType ParamTypes[2] = {
7101 S.Context.getLValueReferenceType(CandidateTy),
7102 S.Context.IntTy
7103 };
7104
7105 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007106 if (Args.size() == 1)
7107 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007108 else
Richard Smithe54c3072013-05-05 15:51:06 +00007109 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007110
7111 // Use a heuristic to reduce number of builtin candidates in the set:
7112 // add volatile version only if there are conversions to a volatile type.
7113 if (HasVolatile) {
7114 ParamTypes[0] =
7115 S.Context.getLValueReferenceType(
7116 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007117 if (Args.size() == 1)
7118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007119 else
Richard Smithe54c3072013-05-05 15:51:06 +00007120 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007121 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007122
7123 // Add restrict version only if there are conversions to a restrict type
7124 // and our candidate type is a non-restrict-qualified pointer.
7125 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7126 !CandidateTy.isRestrictQualified()) {
7127 ParamTypes[0]
7128 = S.Context.getLValueReferenceType(
7129 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007130 if (Args.size() == 1)
7131 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007132 else
Richard Smithe54c3072013-05-05 15:51:06 +00007133 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007134
7135 if (HasVolatile) {
7136 ParamTypes[0]
7137 = S.Context.getLValueReferenceType(
7138 S.Context.getCVRQualifiedType(CandidateTy,
7139 (Qualifiers::Volatile |
7140 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007141 if (Args.size() == 1)
7142 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007143 else
Richard Smithe54c3072013-05-05 15:51:06 +00007144 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007145 }
7146 }
7147
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007148 }
7149
7150public:
7151 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007152 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007153 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007154 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007155 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007156 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007157 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007158 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007159 HasArithmeticOrEnumeralCandidateType(
7160 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007161 CandidateTypes(CandidateTypes),
7162 CandidateSet(CandidateSet) {
7163 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007164 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007165 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007166 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007167 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007168 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007169 assert(getArithmeticType(FirstPromotedArithmeticType)
7170 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007171 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007172 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007173 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007174 "Invalid last promoted arithmetic type");
7175 }
7176
7177 // C++ [over.built]p3:
7178 //
7179 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7180 // is either volatile or empty, there exist candidate operator
7181 // functions of the form
7182 //
7183 // VQ T& operator++(VQ T&);
7184 // T operator++(VQ T&, int);
7185 //
7186 // C++ [over.built]p4:
7187 //
7188 // For every pair (T, VQ), where T is an arithmetic type other
7189 // than bool, and VQ is either volatile or empty, there exist
7190 // candidate operator functions of the form
7191 //
7192 // VQ T& operator--(VQ T&);
7193 // T operator--(VQ T&, int);
7194 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007195 if (!HasArithmeticOrEnumeralCandidateType)
7196 return;
7197
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007198 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7199 Arith < NumArithmeticTypes; ++Arith) {
7200 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007201 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007202 VisibleTypeConversionsQuals.hasVolatile(),
7203 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007204 }
7205 }
7206
7207 // C++ [over.built]p5:
7208 //
7209 // For every pair (T, VQ), where T is a cv-qualified or
7210 // cv-unqualified object type, and VQ is either volatile or
7211 // empty, there exist candidate operator functions of the form
7212 //
7213 // T*VQ& operator++(T*VQ&);
7214 // T*VQ& operator--(T*VQ&);
7215 // T* operator++(T*VQ&, int);
7216 // T* operator--(T*VQ&, int);
7217 void addPlusPlusMinusMinusPointerOverloads() {
7218 for (BuiltinCandidateTypeSet::iterator
7219 Ptr = CandidateTypes[0].pointer_begin(),
7220 PtrEnd = CandidateTypes[0].pointer_end();
7221 Ptr != PtrEnd; ++Ptr) {
7222 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007223 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007224 continue;
7225
7226 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007227 (!(*Ptr).isVolatileQualified() &&
7228 VisibleTypeConversionsQuals.hasVolatile()),
7229 (!(*Ptr).isRestrictQualified() &&
7230 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007231 }
7232 }
7233
7234 // C++ [over.built]p6:
7235 // For every cv-qualified or cv-unqualified object type T, there
7236 // exist candidate operator functions of the form
7237 //
7238 // T& operator*(T*);
7239 //
7240 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007241 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007242 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007243 // T& operator*(T*);
7244 void addUnaryStarPointerOverloads() {
7245 for (BuiltinCandidateTypeSet::iterator
7246 Ptr = CandidateTypes[0].pointer_begin(),
7247 PtrEnd = CandidateTypes[0].pointer_end();
7248 Ptr != PtrEnd; ++Ptr) {
7249 QualType ParamTy = *Ptr;
7250 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007251 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7252 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007253
Douglas Gregor02824322011-01-26 19:30:28 +00007254 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7255 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7256 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007257
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007258 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007259 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007260 }
7261 }
7262
7263 // C++ [over.built]p9:
7264 // For every promoted arithmetic type T, there exist candidate
7265 // operator functions of the form
7266 //
7267 // T operator+(T);
7268 // T operator-(T);
7269 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007270 if (!HasArithmeticOrEnumeralCandidateType)
7271 return;
7272
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007273 for (unsigned Arith = FirstPromotedArithmeticType;
7274 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007275 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007276 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007277 }
7278
7279 // Extension: We also add these operators for vector types.
7280 for (BuiltinCandidateTypeSet::iterator
7281 Vec = CandidateTypes[0].vector_begin(),
7282 VecEnd = CandidateTypes[0].vector_end();
7283 Vec != VecEnd; ++Vec) {
7284 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007285 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007286 }
7287 }
7288
7289 // C++ [over.built]p8:
7290 // For every type T, there exist candidate operator functions of
7291 // the form
7292 //
7293 // T* operator+(T*);
7294 void addUnaryPlusPointerOverloads() {
7295 for (BuiltinCandidateTypeSet::iterator
7296 Ptr = CandidateTypes[0].pointer_begin(),
7297 PtrEnd = CandidateTypes[0].pointer_end();
7298 Ptr != PtrEnd; ++Ptr) {
7299 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007300 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007301 }
7302 }
7303
7304 // C++ [over.built]p10:
7305 // For every promoted integral type T, there exist candidate
7306 // operator functions of the form
7307 //
7308 // T operator~(T);
7309 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007310 if (!HasArithmeticOrEnumeralCandidateType)
7311 return;
7312
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007313 for (unsigned Int = FirstPromotedIntegralType;
7314 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007315 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007316 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007317 }
7318
7319 // Extension: We also add this operator for vector types.
7320 for (BuiltinCandidateTypeSet::iterator
7321 Vec = CandidateTypes[0].vector_begin(),
7322 VecEnd = CandidateTypes[0].vector_end();
7323 Vec != VecEnd; ++Vec) {
7324 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007325 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007326 }
7327 }
7328
7329 // C++ [over.match.oper]p16:
7330 // For every pointer to member type T, there exist candidate operator
7331 // functions of the form
7332 //
7333 // bool operator==(T,T);
7334 // bool operator!=(T,T);
7335 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7336 /// Set of (canonical) types that we've already handled.
7337 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7338
Richard Smithe54c3072013-05-05 15:51:06 +00007339 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007340 for (BuiltinCandidateTypeSet::iterator
7341 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7342 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7343 MemPtr != MemPtrEnd;
7344 ++MemPtr) {
7345 // Don't add the same builtin candidate twice.
7346 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7347 continue;
7348
7349 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007350 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007351 }
7352 }
7353 }
7354
7355 // C++ [over.built]p15:
7356 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007357 // For every T, where T is an enumeration type, a pointer type, or
7358 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007359 //
7360 // bool operator<(T, T);
7361 // bool operator>(T, T);
7362 // bool operator<=(T, T);
7363 // bool operator>=(T, T);
7364 // bool operator==(T, T);
7365 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007366 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007367 // C++ [over.match.oper]p3:
7368 // [...]the built-in candidates include all of the candidate operator
7369 // functions defined in 13.6 that, compared to the given operator, [...]
7370 // do not have the same parameter-type-list as any non-template non-member
7371 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007372 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007373 // Note that in practice, this only affects enumeration types because there
7374 // aren't any built-in candidates of record type, and a user-defined operator
7375 // must have an operand of record or enumeration type. Also, the only other
7376 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007377 // cannot be overloaded for enumeration types, so this is the only place
7378 // where we must suppress candidates like this.
7379 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7380 UserDefinedBinaryOperators;
7381
Richard Smithe54c3072013-05-05 15:51:06 +00007382 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007383 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7384 CandidateTypes[ArgIdx].enumeration_end()) {
7385 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7386 CEnd = CandidateSet.end();
7387 C != CEnd; ++C) {
7388 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7389 continue;
7390
Eli Friedman14f082b2012-09-18 21:52:24 +00007391 if (C->Function->isFunctionTemplateSpecialization())
7392 continue;
7393
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007394 QualType FirstParamType =
7395 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7396 QualType SecondParamType =
7397 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7398
7399 // Skip if either parameter isn't of enumeral type.
7400 if (!FirstParamType->isEnumeralType() ||
7401 !SecondParamType->isEnumeralType())
7402 continue;
7403
7404 // Add this operator to the set of known user-defined operators.
7405 UserDefinedBinaryOperators.insert(
7406 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7407 S.Context.getCanonicalType(SecondParamType)));
7408 }
7409 }
7410 }
7411
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007412 /// Set of (canonical) types that we've already handled.
7413 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7414
Richard Smithe54c3072013-05-05 15:51:06 +00007415 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007416 for (BuiltinCandidateTypeSet::iterator
7417 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7418 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7419 Ptr != PtrEnd; ++Ptr) {
7420 // Don't add the same builtin candidate twice.
7421 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7422 continue;
7423
7424 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007425 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007426 }
7427 for (BuiltinCandidateTypeSet::iterator
7428 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7429 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7430 Enum != EnumEnd; ++Enum) {
7431 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7432
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007433 // Don't add the same builtin candidate twice, or if a user defined
7434 // candidate exists.
7435 if (!AddedTypes.insert(CanonType) ||
7436 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7437 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007438 continue;
7439
7440 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007441 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007442 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007443
7444 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7445 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7446 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007447 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007448 NullPtrTy))) {
7449 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007450 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007451 CandidateSet);
7452 }
7453 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007454 }
7455 }
7456
7457 // C++ [over.built]p13:
7458 //
7459 // For every cv-qualified or cv-unqualified object type T
7460 // there exist candidate operator functions of the form
7461 //
7462 // T* operator+(T*, ptrdiff_t);
7463 // T& operator[](T*, ptrdiff_t); [BELOW]
7464 // T* operator-(T*, ptrdiff_t);
7465 // T* operator+(ptrdiff_t, T*);
7466 // T& operator[](ptrdiff_t, T*); [BELOW]
7467 //
7468 // C++ [over.built]p14:
7469 //
7470 // For every T, where T is a pointer to object type, there
7471 // exist candidate operator functions of the form
7472 //
7473 // ptrdiff_t operator-(T, T);
7474 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7475 /// Set of (canonical) types that we've already handled.
7476 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7477
7478 for (int Arg = 0; Arg < 2; ++Arg) {
7479 QualType AsymetricParamTypes[2] = {
7480 S.Context.getPointerDiffType(),
7481 S.Context.getPointerDiffType(),
7482 };
7483 for (BuiltinCandidateTypeSet::iterator
7484 Ptr = CandidateTypes[Arg].pointer_begin(),
7485 PtrEnd = CandidateTypes[Arg].pointer_end();
7486 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007487 QualType PointeeTy = (*Ptr)->getPointeeType();
7488 if (!PointeeTy->isObjectType())
7489 continue;
7490
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007491 AsymetricParamTypes[Arg] = *Ptr;
7492 if (Arg == 0 || Op == OO_Plus) {
7493 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7494 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007495 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007496 }
7497 if (Op == OO_Minus) {
7498 // ptrdiff_t operator-(T, T);
7499 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7500 continue;
7501
7502 QualType ParamTypes[2] = { *Ptr, *Ptr };
7503 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007504 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007505 }
7506 }
7507 }
7508 }
7509
7510 // C++ [over.built]p12:
7511 //
7512 // For every pair of promoted arithmetic types L and R, there
7513 // exist candidate operator functions of the form
7514 //
7515 // LR operator*(L, R);
7516 // LR operator/(L, R);
7517 // LR operator+(L, R);
7518 // LR operator-(L, R);
7519 // bool operator<(L, R);
7520 // bool operator>(L, R);
7521 // bool operator<=(L, R);
7522 // bool operator>=(L, R);
7523 // bool operator==(L, R);
7524 // bool operator!=(L, R);
7525 //
7526 // where LR is the result of the usual arithmetic conversions
7527 // between types L and R.
7528 //
7529 // C++ [over.built]p24:
7530 //
7531 // For every pair of promoted arithmetic types L and R, there exist
7532 // candidate operator functions of the form
7533 //
7534 // LR operator?(bool, L, R);
7535 //
7536 // where LR is the result of the usual arithmetic conversions
7537 // between types L and R.
7538 // Our candidates ignore the first parameter.
7539 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007540 if (!HasArithmeticOrEnumeralCandidateType)
7541 return;
7542
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007543 for (unsigned Left = FirstPromotedArithmeticType;
7544 Left < LastPromotedArithmeticType; ++Left) {
7545 for (unsigned Right = FirstPromotedArithmeticType;
7546 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007547 QualType LandR[2] = { getArithmeticType(Left),
7548 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007549 QualType Result =
7550 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007551 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007552 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007553 }
7554 }
7555
7556 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7557 // conditional operator for vector types.
7558 for (BuiltinCandidateTypeSet::iterator
7559 Vec1 = CandidateTypes[0].vector_begin(),
7560 Vec1End = CandidateTypes[0].vector_end();
7561 Vec1 != Vec1End; ++Vec1) {
7562 for (BuiltinCandidateTypeSet::iterator
7563 Vec2 = CandidateTypes[1].vector_begin(),
7564 Vec2End = CandidateTypes[1].vector_end();
7565 Vec2 != Vec2End; ++Vec2) {
7566 QualType LandR[2] = { *Vec1, *Vec2 };
7567 QualType Result = S.Context.BoolTy;
7568 if (!isComparison) {
7569 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7570 Result = *Vec1;
7571 else
7572 Result = *Vec2;
7573 }
7574
Richard Smithe54c3072013-05-05 15:51:06 +00007575 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007576 }
7577 }
7578 }
7579
7580 // C++ [over.built]p17:
7581 //
7582 // For every pair of promoted integral types L and R, there
7583 // exist candidate operator functions of the form
7584 //
7585 // LR operator%(L, R);
7586 // LR operator&(L, R);
7587 // LR operator^(L, R);
7588 // LR operator|(L, R);
7589 // L operator<<(L, R);
7590 // L operator>>(L, R);
7591 //
7592 // where LR is the result of the usual arithmetic conversions
7593 // between types L and R.
7594 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007595 if (!HasArithmeticOrEnumeralCandidateType)
7596 return;
7597
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007598 for (unsigned Left = FirstPromotedIntegralType;
7599 Left < LastPromotedIntegralType; ++Left) {
7600 for (unsigned Right = FirstPromotedIntegralType;
7601 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007602 QualType LandR[2] = { getArithmeticType(Left),
7603 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007604 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7605 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007606 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007607 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007608 }
7609 }
7610 }
7611
7612 // C++ [over.built]p20:
7613 //
7614 // For every pair (T, VQ), where T is an enumeration or
7615 // pointer to member type and VQ is either volatile or
7616 // empty, there exist candidate operator functions of the form
7617 //
7618 // VQ T& operator=(VQ T&, T);
7619 void addAssignmentMemberPointerOrEnumeralOverloads() {
7620 /// Set of (canonical) types that we've already handled.
7621 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7622
7623 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7624 for (BuiltinCandidateTypeSet::iterator
7625 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7626 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7627 Enum != EnumEnd; ++Enum) {
7628 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7629 continue;
7630
Richard Smithe54c3072013-05-05 15:51:06 +00007631 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007632 }
7633
7634 for (BuiltinCandidateTypeSet::iterator
7635 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7636 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7637 MemPtr != MemPtrEnd; ++MemPtr) {
7638 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7639 continue;
7640
Richard Smithe54c3072013-05-05 15:51:06 +00007641 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007642 }
7643 }
7644 }
7645
7646 // C++ [over.built]p19:
7647 //
7648 // For every pair (T, VQ), where T is any type and VQ is either
7649 // volatile or empty, there exist candidate operator functions
7650 // of the form
7651 //
7652 // T*VQ& operator=(T*VQ&, T*);
7653 //
7654 // C++ [over.built]p21:
7655 //
7656 // For every pair (T, VQ), where T is a cv-qualified or
7657 // cv-unqualified object type and VQ is either volatile or
7658 // empty, there exist candidate operator functions of the form
7659 //
7660 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7661 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7662 void addAssignmentPointerOverloads(bool isEqualOp) {
7663 /// Set of (canonical) types that we've already handled.
7664 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7665
7666 for (BuiltinCandidateTypeSet::iterator
7667 Ptr = CandidateTypes[0].pointer_begin(),
7668 PtrEnd = CandidateTypes[0].pointer_end();
7669 Ptr != PtrEnd; ++Ptr) {
7670 // If this is operator=, keep track of the builtin candidates we added.
7671 if (isEqualOp)
7672 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007673 else if (!(*Ptr)->getPointeeType()->isObjectType())
7674 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007675
7676 // non-volatile version
7677 QualType ParamTypes[2] = {
7678 S.Context.getLValueReferenceType(*Ptr),
7679 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7680 };
Richard Smithe54c3072013-05-05 15:51:06 +00007681 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007682 /*IsAssigmentOperator=*/ isEqualOp);
7683
Douglas Gregor5bee2582012-06-04 00:15:09 +00007684 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7685 VisibleTypeConversionsQuals.hasVolatile();
7686 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007687 // volatile version
7688 ParamTypes[0] =
7689 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007690 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007691 /*IsAssigmentOperator=*/isEqualOp);
7692 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007693
7694 if (!(*Ptr).isRestrictQualified() &&
7695 VisibleTypeConversionsQuals.hasRestrict()) {
7696 // restrict version
7697 ParamTypes[0]
7698 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007699 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007700 /*IsAssigmentOperator=*/isEqualOp);
7701
7702 if (NeedVolatile) {
7703 // volatile restrict version
7704 ParamTypes[0]
7705 = S.Context.getLValueReferenceType(
7706 S.Context.getCVRQualifiedType(*Ptr,
7707 (Qualifiers::Volatile |
7708 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007709 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007710 /*IsAssigmentOperator=*/isEqualOp);
7711 }
7712 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007713 }
7714
7715 if (isEqualOp) {
7716 for (BuiltinCandidateTypeSet::iterator
7717 Ptr = CandidateTypes[1].pointer_begin(),
7718 PtrEnd = CandidateTypes[1].pointer_end();
7719 Ptr != PtrEnd; ++Ptr) {
7720 // Make sure we don't add the same candidate twice.
7721 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7722 continue;
7723
Chandler Carruth8e543b32010-12-12 08:17:55 +00007724 QualType ParamTypes[2] = {
7725 S.Context.getLValueReferenceType(*Ptr),
7726 *Ptr,
7727 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007728
7729 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007730 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007731 /*IsAssigmentOperator=*/true);
7732
Douglas Gregor5bee2582012-06-04 00:15:09 +00007733 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7734 VisibleTypeConversionsQuals.hasVolatile();
7735 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007736 // volatile version
7737 ParamTypes[0] =
7738 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007739 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7740 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007741 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007742
7743 if (!(*Ptr).isRestrictQualified() &&
7744 VisibleTypeConversionsQuals.hasRestrict()) {
7745 // restrict version
7746 ParamTypes[0]
7747 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007748 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7749 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007750
7751 if (NeedVolatile) {
7752 // volatile restrict version
7753 ParamTypes[0]
7754 = S.Context.getLValueReferenceType(
7755 S.Context.getCVRQualifiedType(*Ptr,
7756 (Qualifiers::Volatile |
7757 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007758 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7759 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007760 }
7761 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007762 }
7763 }
7764 }
7765
7766 // C++ [over.built]p18:
7767 //
7768 // For every triple (L, VQ, R), where L is an arithmetic type,
7769 // VQ is either volatile or empty, and R is a promoted
7770 // arithmetic type, there exist candidate operator functions of
7771 // the form
7772 //
7773 // VQ L& operator=(VQ L&, R);
7774 // VQ L& operator*=(VQ L&, R);
7775 // VQ L& operator/=(VQ L&, R);
7776 // VQ L& operator+=(VQ L&, R);
7777 // VQ L& operator-=(VQ L&, R);
7778 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007779 if (!HasArithmeticOrEnumeralCandidateType)
7780 return;
7781
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007782 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7783 for (unsigned Right = FirstPromotedArithmeticType;
7784 Right < LastPromotedArithmeticType; ++Right) {
7785 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007786 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007787
7788 // Add this built-in operator as a candidate (VQ is empty).
7789 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007790 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007791 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007792 /*IsAssigmentOperator=*/isEqualOp);
7793
7794 // Add this built-in operator as a candidate (VQ is 'volatile').
7795 if (VisibleTypeConversionsQuals.hasVolatile()) {
7796 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007797 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007798 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007799 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007800 /*IsAssigmentOperator=*/isEqualOp);
7801 }
7802 }
7803 }
7804
7805 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7806 for (BuiltinCandidateTypeSet::iterator
7807 Vec1 = CandidateTypes[0].vector_begin(),
7808 Vec1End = CandidateTypes[0].vector_end();
7809 Vec1 != Vec1End; ++Vec1) {
7810 for (BuiltinCandidateTypeSet::iterator
7811 Vec2 = CandidateTypes[1].vector_begin(),
7812 Vec2End = CandidateTypes[1].vector_end();
7813 Vec2 != Vec2End; ++Vec2) {
7814 QualType ParamTypes[2];
7815 ParamTypes[1] = *Vec2;
7816 // Add this built-in operator as a candidate (VQ is empty).
7817 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007818 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007819 /*IsAssigmentOperator=*/isEqualOp);
7820
7821 // Add this built-in operator as a candidate (VQ is 'volatile').
7822 if (VisibleTypeConversionsQuals.hasVolatile()) {
7823 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7824 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007825 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007826 /*IsAssigmentOperator=*/isEqualOp);
7827 }
7828 }
7829 }
7830 }
7831
7832 // C++ [over.built]p22:
7833 //
7834 // For every triple (L, VQ, R), where L is an integral type, VQ
7835 // is either volatile or empty, and R is a promoted integral
7836 // type, there exist candidate operator functions of the form
7837 //
7838 // VQ L& operator%=(VQ L&, R);
7839 // VQ L& operator<<=(VQ L&, R);
7840 // VQ L& operator>>=(VQ L&, R);
7841 // VQ L& operator&=(VQ L&, R);
7842 // VQ L& operator^=(VQ L&, R);
7843 // VQ L& operator|=(VQ L&, R);
7844 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007845 if (!HasArithmeticOrEnumeralCandidateType)
7846 return;
7847
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007848 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7849 for (unsigned Right = FirstPromotedIntegralType;
7850 Right < LastPromotedIntegralType; ++Right) {
7851 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007852 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007853
7854 // Add this built-in operator as a candidate (VQ is empty).
7855 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007856 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007857 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007858 if (VisibleTypeConversionsQuals.hasVolatile()) {
7859 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007860 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007861 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7862 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007863 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007864 }
7865 }
7866 }
7867 }
7868
7869 // C++ [over.operator]p23:
7870 //
7871 // There also exist candidate operator functions of the form
7872 //
7873 // bool operator!(bool);
7874 // bool operator&&(bool, bool);
7875 // bool operator||(bool, bool);
7876 void addExclaimOverload() {
7877 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007878 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879 /*IsAssignmentOperator=*/false,
7880 /*NumContextualBoolArguments=*/1);
7881 }
7882 void addAmpAmpOrPipePipeOverload() {
7883 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007884 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007885 /*IsAssignmentOperator=*/false,
7886 /*NumContextualBoolArguments=*/2);
7887 }
7888
7889 // C++ [over.built]p13:
7890 //
7891 // For every cv-qualified or cv-unqualified object type T there
7892 // exist candidate operator functions of the form
7893 //
7894 // T* operator+(T*, ptrdiff_t); [ABOVE]
7895 // T& operator[](T*, ptrdiff_t);
7896 // T* operator-(T*, ptrdiff_t); [ABOVE]
7897 // T* operator+(ptrdiff_t, T*); [ABOVE]
7898 // T& operator[](ptrdiff_t, T*);
7899 void addSubscriptOverloads() {
7900 for (BuiltinCandidateTypeSet::iterator
7901 Ptr = CandidateTypes[0].pointer_begin(),
7902 PtrEnd = CandidateTypes[0].pointer_end();
7903 Ptr != PtrEnd; ++Ptr) {
7904 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7905 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007906 if (!PointeeType->isObjectType())
7907 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007908
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007909 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7910
7911 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007912 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007913 }
7914
7915 for (BuiltinCandidateTypeSet::iterator
7916 Ptr = CandidateTypes[1].pointer_begin(),
7917 PtrEnd = CandidateTypes[1].pointer_end();
7918 Ptr != PtrEnd; ++Ptr) {
7919 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7920 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007921 if (!PointeeType->isObjectType())
7922 continue;
7923
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007924 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7925
7926 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007927 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007928 }
7929 }
7930
7931 // C++ [over.built]p11:
7932 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7933 // C1 is the same type as C2 or is a derived class of C2, T is an object
7934 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7935 // there exist candidate operator functions of the form
7936 //
7937 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7938 //
7939 // where CV12 is the union of CV1 and CV2.
7940 void addArrowStarOverloads() {
7941 for (BuiltinCandidateTypeSet::iterator
7942 Ptr = CandidateTypes[0].pointer_begin(),
7943 PtrEnd = CandidateTypes[0].pointer_end();
7944 Ptr != PtrEnd; ++Ptr) {
7945 QualType C1Ty = (*Ptr);
7946 QualType C1;
7947 QualifierCollector Q1;
7948 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7949 if (!isa<RecordType>(C1))
7950 continue;
7951 // heuristic to reduce number of builtin candidates in the set.
7952 // Add volatile/restrict version only if there are conversions to a
7953 // volatile/restrict type.
7954 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7955 continue;
7956 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7957 continue;
7958 for (BuiltinCandidateTypeSet::iterator
7959 MemPtr = CandidateTypes[1].member_pointer_begin(),
7960 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7961 MemPtr != MemPtrEnd; ++MemPtr) {
7962 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7963 QualType C2 = QualType(mptr->getClass(), 0);
7964 C2 = C2.getUnqualifiedType();
7965 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7966 break;
7967 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7968 // build CV12 T&
7969 QualType T = mptr->getPointeeType();
7970 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7971 T.isVolatileQualified())
7972 continue;
7973 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7974 T.isRestrictQualified())
7975 continue;
7976 T = Q1.apply(S.Context, T);
7977 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007978 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979 }
7980 }
7981 }
7982
7983 // Note that we don't consider the first argument, since it has been
7984 // contextually converted to bool long ago. The candidates below are
7985 // therefore added as binary.
7986 //
7987 // C++ [over.built]p25:
7988 // For every type T, where T is a pointer, pointer-to-member, or scoped
7989 // enumeration type, there exist candidate operator functions of the form
7990 //
7991 // T operator?(bool, T, T);
7992 //
7993 void addConditionalOperatorOverloads() {
7994 /// Set of (canonical) types that we've already handled.
7995 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7996
7997 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7998 for (BuiltinCandidateTypeSet::iterator
7999 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8000 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8001 Ptr != PtrEnd; ++Ptr) {
8002 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
8003 continue;
8004
8005 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008006 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008007 }
8008
8009 for (BuiltinCandidateTypeSet::iterator
8010 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8011 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8012 MemPtr != MemPtrEnd; ++MemPtr) {
8013 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
8014 continue;
8015
8016 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008017 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008018 }
8019
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008020 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008021 for (BuiltinCandidateTypeSet::iterator
8022 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8023 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8024 Enum != EnumEnd; ++Enum) {
8025 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8026 continue;
8027
8028 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
8029 continue;
8030
8031 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008032 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008033 }
8034 }
8035 }
8036 }
8037};
8038
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008039} // end anonymous namespace
8040
8041/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8042/// operator overloads to the candidate set (C++ [over.built]), based
8043/// on the operator @p Op and the arguments given. For example, if the
8044/// operator is a binary '+', this routine might add "int
8045/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008046void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8047 SourceLocation OpLoc,
8048 ArrayRef<Expr *> Args,
8049 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008050 // Find all of the types that the arguments can convert to, but only
8051 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008052 // that make use of these types. Also record whether we encounter non-record
8053 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008054 Qualifiers VisibleTypeConversionsQuals;
8055 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008056 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008057 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008058
8059 bool HasNonRecordCandidateType = false;
8060 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008061 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008062 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008063 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
8064 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8065 OpLoc,
8066 true,
8067 (Op == OO_Exclaim ||
8068 Op == OO_AmpAmp ||
8069 Op == OO_PipePipe),
8070 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008071 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8072 CandidateTypes[ArgIdx].hasNonRecordTypes();
8073 HasArithmeticOrEnumeralCandidateType =
8074 HasArithmeticOrEnumeralCandidateType ||
8075 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008076 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008077
Chandler Carruth00a38332010-12-13 01:44:01 +00008078 // Exit early when no non-record types have been added to the candidate set
8079 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008080 //
8081 // We can't exit early for !, ||, or &&, since there we have always have
8082 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008083 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008084 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008085 return;
8086
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008087 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008088 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008089 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008090 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008091 CandidateTypes, CandidateSet);
8092
8093 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008094 switch (Op) {
8095 case OO_None:
8096 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008097 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008098
Chandler Carruth5184de02010-12-12 08:51:33 +00008099 case OO_New:
8100 case OO_Delete:
8101 case OO_Array_New:
8102 case OO_Array_Delete:
8103 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008104 llvm_unreachable(
8105 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008106
8107 case OO_Comma:
8108 case OO_Arrow:
8109 // C++ [over.match.oper]p3:
8110 // -- For the operator ',', the unary operator '&', or the
8111 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008112 break;
8113
8114 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008115 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008116 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008117 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008118
8119 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008120 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008121 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008122 } else {
8123 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8124 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8125 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008126 break;
8127
Chandler Carruth5184de02010-12-12 08:51:33 +00008128 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008129 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008130 OpBuilder.addUnaryStarPointerOverloads();
8131 else
8132 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8133 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008134
Chandler Carruth5184de02010-12-12 08:51:33 +00008135 case OO_Slash:
8136 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008137 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008138
8139 case OO_PlusPlus:
8140 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008141 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8142 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008143 break;
8144
Douglas Gregor84605ae2009-08-24 13:43:27 +00008145 case OO_EqualEqual:
8146 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008147 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008148 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008149
Douglas Gregora11693b2008-11-12 17:17:38 +00008150 case OO_Less:
8151 case OO_Greater:
8152 case OO_LessEqual:
8153 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008154 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008155 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8156 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008157
Douglas Gregora11693b2008-11-12 17:17:38 +00008158 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008159 case OO_Caret:
8160 case OO_Pipe:
8161 case OO_LessLess:
8162 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008163 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008164 break;
8165
Chandler Carruth5184de02010-12-12 08:51:33 +00008166 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008167 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008168 // C++ [over.match.oper]p3:
8169 // -- For the operator ',', the unary operator '&', or the
8170 // operator '->', the built-in candidates set is empty.
8171 break;
8172
8173 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8174 break;
8175
8176 case OO_Tilde:
8177 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8178 break;
8179
Douglas Gregora11693b2008-11-12 17:17:38 +00008180 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008181 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008182 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008183
8184 case OO_PlusEqual:
8185 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008186 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008187 // Fall through.
8188
8189 case OO_StarEqual:
8190 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008191 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008192 break;
8193
8194 case OO_PercentEqual:
8195 case OO_LessLessEqual:
8196 case OO_GreaterGreaterEqual:
8197 case OO_AmpEqual:
8198 case OO_CaretEqual:
8199 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008200 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008201 break;
8202
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008203 case OO_Exclaim:
8204 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008205 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008206
Douglas Gregora11693b2008-11-12 17:17:38 +00008207 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008208 case OO_PipePipe:
8209 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008210 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008211
8212 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008213 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008214 break;
8215
8216 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008217 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008218 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008219
8220 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008221 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008222 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8223 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008224 }
8225}
8226
Douglas Gregore254f902009-02-04 00:32:51 +00008227/// \brief Add function candidates found via argument-dependent lookup
8228/// to the set of overloading candidates.
8229///
8230/// This routine performs argument-dependent name lookup based on the
8231/// given function name (which may also be an operator name) and adds
8232/// all of the overload candidates found by ADL to the overload
8233/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008234void
Douglas Gregore254f902009-02-04 00:32:51 +00008235Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008236 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008237 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008238 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008239 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008240 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008241 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008242
John McCall91f61fc2010-01-26 06:04:06 +00008243 // FIXME: This approach for uniquing ADL results (and removing
8244 // redundant candidates from the set) relies on pointer-equality,
8245 // which means we need to key off the canonical decl. However,
8246 // always going back to the canonical decl might not get us the
8247 // right set of default arguments. What default arguments are
8248 // we supposed to consider on ADL candidates, anyway?
8249
Douglas Gregorcabea402009-09-22 15:41:20 +00008250 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008251 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008252
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008253 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008254 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8255 CandEnd = CandidateSet.end();
8256 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008257 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008258 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008259 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008260 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008261 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008262
8263 // For each of the ADL candidates we found, add it to the overload
8264 // set.
John McCall8fe68082010-01-26 07:16:45 +00008265 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008266 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008268 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008269 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008270
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008271 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8272 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008273 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008274 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008275 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008276 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008277 }
Douglas Gregore254f902009-02-04 00:32:51 +00008278}
8279
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008280/// isBetterOverloadCandidate - Determines whether the first overload
8281/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00008282bool
John McCall5c32be02010-08-24 20:38:10 +00008283isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008284 const OverloadCandidate &Cand1,
8285 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008286 SourceLocation Loc,
8287 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008288 // Define viable functions to be better candidates than non-viable
8289 // functions.
8290 if (!Cand2.Viable)
8291 return Cand1.Viable;
8292 else if (!Cand1.Viable)
8293 return false;
8294
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008295 // C++ [over.match.best]p1:
8296 //
8297 // -- if F is a static member function, ICS1(F) is defined such
8298 // that ICS1(F) is neither better nor worse than ICS1(G) for
8299 // any function G, and, symmetrically, ICS1(G) is neither
8300 // better nor worse than ICS1(F).
8301 unsigned StartArg = 0;
8302 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8303 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008304
Douglas Gregord3cb3562009-07-07 23:38:56 +00008305 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008306 // A viable function F1 is defined to be a better function than another
8307 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008308 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008309 unsigned NumArgs = Cand1.NumConversions;
8310 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008311 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008312 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008313 switch (CompareImplicitConversionSequences(S,
8314 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008315 Cand2.Conversions[ArgIdx])) {
8316 case ImplicitConversionSequence::Better:
8317 // Cand1 has a better conversion sequence.
8318 HasBetterConversion = true;
8319 break;
8320
8321 case ImplicitConversionSequence::Worse:
8322 // Cand1 can't be better than Cand2.
8323 return false;
8324
8325 case ImplicitConversionSequence::Indistinguishable:
8326 // Do nothing.
8327 break;
8328 }
8329 }
8330
Mike Stump11289f42009-09-09 15:08:12 +00008331 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008332 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008333 if (HasBetterConversion)
8334 return true;
8335
Douglas Gregora1f013e2008-11-07 22:36:19 +00008336 // -- the context is an initialization by user-defined conversion
8337 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8338 // from the return type of F1 to the destination type (i.e.,
8339 // the type of the entity being initialized) is a better
8340 // conversion sequence than the standard conversion sequence
8341 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008342 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008343 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008344 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008345 // First check whether we prefer one of the conversion functions over the
8346 // other. This only distinguishes the results in non-standard, extension
8347 // cases such as the conversion from a lambda closure type to a function
8348 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008349 ImplicitConversionSequence::CompareKind Result =
8350 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8351 if (Result == ImplicitConversionSequence::Indistinguishable)
8352 Result = CompareStandardConversionSequences(S,
8353 Cand1.FinalConversion,
8354 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008355
Richard Smithec2748a2014-05-17 04:36:39 +00008356 if (Result != ImplicitConversionSequence::Indistinguishable)
8357 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008358
8359 // FIXME: Compare kind of reference binding if conversion functions
8360 // convert to a reference type used in direct reference binding, per
8361 // C++14 [over.match.best]p1 section 2 bullet 3.
8362 }
8363
8364 // -- F1 is a non-template function and F2 is a function template
8365 // specialization, or, if not that,
8366 bool Cand1IsSpecialization = Cand1.Function &&
8367 Cand1.Function->getPrimaryTemplate();
8368 bool Cand2IsSpecialization = Cand2.Function &&
8369 Cand2.Function->getPrimaryTemplate();
8370 if (Cand1IsSpecialization != Cand2IsSpecialization)
8371 return Cand2IsSpecialization;
8372
8373 // -- F1 and F2 are function template specializations, and the function
8374 // template for F1 is more specialized than the template for F2
8375 // according to the partial ordering rules described in 14.5.5.2, or,
8376 // if not that,
8377 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8378 if (FunctionTemplateDecl *BetterTemplate
8379 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8380 Cand2.Function->getPrimaryTemplate(),
8381 Loc,
8382 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8383 : TPOC_Call,
8384 Cand1.ExplicitCallArguments,
8385 Cand2.ExplicitCallArguments))
8386 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008387 }
8388
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008389 // Check for enable_if value-based overload resolution.
8390 if (Cand1.Function && Cand2.Function &&
8391 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8392 Cand2.Function->hasAttr<EnableIfAttr>())) {
8393 // FIXME: The next several lines are just
8394 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8395 // instead of reverse order which is how they're stored in the AST.
8396 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008397 if (Cand1.Function->hasAttrs()) {
8398 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008399 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8400 IsNotEnableIfAttr),
8401 Cand1Attrs.end());
8402 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008403 }
8404
8405 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008406 if (Cand2.Function->hasAttrs()) {
8407 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008408 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8409 IsNotEnableIfAttr),
8410 Cand2Attrs.end());
8411 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008412 }
Richard Smith9516eee2014-05-17 02:21:47 +00008413
8414 // Candidate 1 is better if it has strictly more attributes and
8415 // the common sequence is identical.
8416 if (Cand1Attrs.size() <= Cand2Attrs.size())
8417 return false;
8418
8419 auto Cand1I = Cand1Attrs.begin();
8420 for (auto &Cand2A : Cand2Attrs) {
8421 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008422 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008423 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8424 S.getASTContext(), true);
8425 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8426 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008427 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008428 return false;
8429 }
Richard Smith9516eee2014-05-17 02:21:47 +00008430
8431 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008432 }
8433
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008434 return false;
8435}
8436
Mike Stump11289f42009-09-09 15:08:12 +00008437/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008438/// within an overload candidate set.
8439///
James Dennettffad8b72012-06-22 08:10:18 +00008440/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008441/// which overload resolution occurs.
8442///
James Dennettffad8b72012-06-22 08:10:18 +00008443/// \param Best If overload resolution was successful or found a deleted
8444/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008445///
8446/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008447OverloadingResult
8448OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008449 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008450 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008451 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008452 Best = end();
8453 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8454 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008455 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008456 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008457 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008458 }
8459
8460 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008461 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008462 return OR_No_Viable_Function;
8463
8464 // Make sure that this function is better than every other viable
8465 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008466 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008467 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008468 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008469 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008470 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008471 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008472 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008473 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008474 }
Mike Stump11289f42009-09-09 15:08:12 +00008475
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008476 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008477 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008478 (Best->Function->isDeleted() ||
8479 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008480 return OR_Deleted;
8481
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008482 return OR_Success;
8483}
8484
John McCall53262c92010-01-12 02:15:36 +00008485namespace {
8486
8487enum OverloadCandidateKind {
8488 oc_function,
8489 oc_method,
8490 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008491 oc_function_template,
8492 oc_method_template,
8493 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008494 oc_implicit_default_constructor,
8495 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008496 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008497 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008498 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008499 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008500};
8501
John McCalle1ac8d12010-01-13 00:25:19 +00008502OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8503 FunctionDecl *Fn,
8504 std::string &Description) {
8505 bool isTemplate = false;
8506
8507 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8508 isTemplate = true;
8509 Description = S.getTemplateArgumentBindingsText(
8510 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8511 }
John McCallfd0b2f82010-01-06 09:43:14 +00008512
8513 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008514 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008515 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008516
Sebastian Redl08905022011-02-05 19:23:19 +00008517 if (Ctor->getInheritedConstructor())
8518 return oc_implicit_inherited_constructor;
8519
Alexis Hunt119c10e2011-05-25 23:16:36 +00008520 if (Ctor->isDefaultConstructor())
8521 return oc_implicit_default_constructor;
8522
8523 if (Ctor->isMoveConstructor())
8524 return oc_implicit_move_constructor;
8525
8526 assert(Ctor->isCopyConstructor() &&
8527 "unexpected sort of implicit constructor");
8528 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008529 }
8530
8531 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8532 // This actually gets spelled 'candidate function' for now, but
8533 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008534 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008535 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008536
Alexis Hunt119c10e2011-05-25 23:16:36 +00008537 if (Meth->isMoveAssignmentOperator())
8538 return oc_implicit_move_assignment;
8539
Douglas Gregor12695102012-02-10 08:36:38 +00008540 if (Meth->isCopyAssignmentOperator())
8541 return oc_implicit_copy_assignment;
8542
8543 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8544 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008545 }
8546
John McCalle1ac8d12010-01-13 00:25:19 +00008547 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008548}
8549
Larisse Voufo98b20f12013-07-19 23:00:19 +00008550void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008551 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8552 if (!Ctor) return;
8553
8554 Ctor = Ctor->getInheritedConstructor();
8555 if (!Ctor) return;
8556
8557 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8558}
8559
John McCall53262c92010-01-12 02:15:36 +00008560} // end anonymous namespace
8561
8562// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008563void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008564 std::string FnDesc;
8565 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008566 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8567 << (unsigned) K << FnDesc;
8568 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8569 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008570 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008571}
8572
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008573// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008574// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008575void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008576 assert(OverloadedExpr->getType() == Context.OverloadTy);
8577
8578 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8579 OverloadExpr *OvlExpr = Ovl.Expression;
8580
8581 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8582 IEnd = OvlExpr->decls_end();
8583 I != IEnd; ++I) {
8584 if (FunctionTemplateDecl *FunTmpl =
8585 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008586 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008587 } else if (FunctionDecl *Fun
8588 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008589 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008590 }
8591 }
8592}
8593
John McCall0d1da222010-01-12 00:44:57 +00008594/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8595/// "lead" diagnostic; it will be given two arguments, the source and
8596/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008597void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8598 Sema &S,
8599 SourceLocation CaretLoc,
8600 const PartialDiagnostic &PDiag) const {
8601 S.Diag(CaretLoc, PDiag)
8602 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008603 // FIXME: The note limiting machinery is borrowed from
8604 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8605 // refactoring here.
8606 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8607 unsigned CandsShown = 0;
8608 AmbiguousConversionSequence::const_iterator I, E;
8609 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8610 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8611 break;
8612 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008613 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008614 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008615 if (I != E)
8616 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008617}
8618
John McCall0d1da222010-01-12 00:44:57 +00008619namespace {
8620
John McCall6a61b522010-01-13 09:16:55 +00008621void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8622 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8623 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008624 assert(Cand->Function && "for now, candidate must be a function");
8625 FunctionDecl *Fn = Cand->Function;
8626
8627 // There's a conversion slot for the object argument if this is a
8628 // non-constructor method. Note that 'I' corresponds the
8629 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008630 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008631 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008632 if (I == 0)
8633 isObjectArgument = true;
8634 else
8635 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008636 }
8637
John McCalle1ac8d12010-01-13 00:25:19 +00008638 std::string FnDesc;
8639 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8640
John McCall6a61b522010-01-13 09:16:55 +00008641 Expr *FromExpr = Conv.Bad.FromExpr;
8642 QualType FromTy = Conv.Bad.getFromType();
8643 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008644
John McCallfb7ad0f2010-02-02 02:42:52 +00008645 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008646 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008647 Expr *E = FromExpr->IgnoreParens();
8648 if (isa<UnaryOperator>(E))
8649 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008650 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008651
8652 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8653 << (unsigned) FnKind << FnDesc
8654 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8655 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008656 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008657 return;
8658 }
8659
John McCall6d174642010-01-23 08:10:49 +00008660 // Do some hand-waving analysis to see if the non-viability is due
8661 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008662 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8663 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8664 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8665 CToTy = RT->getPointeeType();
8666 else {
8667 // TODO: detect and diagnose the full richness of const mismatches.
8668 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8669 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8670 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8671 }
8672
8673 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8674 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008675 Qualifiers FromQs = CFromTy.getQualifiers();
8676 Qualifiers ToQs = CToTy.getQualifiers();
8677
8678 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8679 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8680 << (unsigned) FnKind << FnDesc
8681 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8682 << FromTy
8683 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8684 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008685 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008686 return;
8687 }
8688
John McCall31168b02011-06-15 23:02:42 +00008689 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008690 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008691 << (unsigned) FnKind << FnDesc
8692 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8693 << FromTy
8694 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8695 << (unsigned) isObjectArgument << I+1;
8696 MaybeEmitInheritedConstructorNote(S, Fn);
8697 return;
8698 }
8699
Douglas Gregoraec25842011-04-26 23:16:46 +00008700 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8702 << (unsigned) FnKind << FnDesc
8703 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8704 << FromTy
8705 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8706 << (unsigned) isObjectArgument << I+1;
8707 MaybeEmitInheritedConstructorNote(S, Fn);
8708 return;
8709 }
8710
John McCall47000992010-01-14 03:28:57 +00008711 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8712 assert(CVR && "unexpected qualifiers mismatch");
8713
8714 if (isObjectArgument) {
8715 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8716 << (unsigned) FnKind << FnDesc
8717 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8718 << FromTy << (CVR - 1);
8719 } else {
8720 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8721 << (unsigned) FnKind << FnDesc
8722 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8723 << FromTy << (CVR - 1) << I+1;
8724 }
Sebastian Redl08905022011-02-05 19:23:19 +00008725 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008726 return;
8727 }
8728
Sebastian Redla72462c2011-09-24 17:48:32 +00008729 // Special diagnostic for failure to convert an initializer list, since
8730 // telling the user that it has type void is not useful.
8731 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8732 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8733 << (unsigned) FnKind << FnDesc
8734 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8735 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8736 MaybeEmitInheritedConstructorNote(S, Fn);
8737 return;
8738 }
8739
John McCall6d174642010-01-23 08:10:49 +00008740 // Diagnose references or pointers to incomplete types differently,
8741 // since it's far from impossible that the incompleteness triggered
8742 // the failure.
8743 QualType TempFromTy = FromTy.getNonReferenceType();
8744 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8745 TempFromTy = PTy->getPointeeType();
8746 if (TempFromTy->isIncompleteType()) {
8747 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8748 << (unsigned) FnKind << FnDesc
8749 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8750 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008751 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008752 return;
8753 }
8754
Douglas Gregor56f2e342010-06-30 23:01:39 +00008755 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008756 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008757 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8758 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8759 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8760 FromPtrTy->getPointeeType()) &&
8761 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8762 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008763 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008764 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008765 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008766 }
8767 } else if (const ObjCObjectPointerType *FromPtrTy
8768 = FromTy->getAs<ObjCObjectPointerType>()) {
8769 if (const ObjCObjectPointerType *ToPtrTy
8770 = ToTy->getAs<ObjCObjectPointerType>())
8771 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8772 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8773 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8774 FromPtrTy->getPointeeType()) &&
8775 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008776 BaseToDerivedConversion = 2;
8777 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008778 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8779 !FromTy->isIncompleteType() &&
8780 !ToRefTy->getPointeeType()->isIncompleteType() &&
8781 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8782 BaseToDerivedConversion = 3;
8783 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8784 ToTy.getNonReferenceType().getCanonicalType() ==
8785 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008786 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8787 << (unsigned) FnKind << FnDesc
8788 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8789 << (unsigned) isObjectArgument << I + 1;
8790 MaybeEmitInheritedConstructorNote(S, Fn);
8791 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008792 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008794
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008795 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008796 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008797 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008798 << (unsigned) FnKind << FnDesc
8799 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008800 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008801 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008802 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008803 return;
8804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008805
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008806 if (isa<ObjCObjectPointerType>(CFromTy) &&
8807 isa<PointerType>(CToTy)) {
8808 Qualifiers FromQs = CFromTy.getQualifiers();
8809 Qualifiers ToQs = CToTy.getQualifiers();
8810 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8811 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8812 << (unsigned) FnKind << FnDesc
8813 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8814 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8815 MaybeEmitInheritedConstructorNote(S, Fn);
8816 return;
8817 }
8818 }
8819
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008820 // Emit the generic diagnostic and, optionally, add the hints to it.
8821 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8822 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008823 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008824 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8825 << (unsigned) (Cand->Fix.Kind);
8826
8827 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008828 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8829 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008830 FDiag << *HI;
8831 S.Diag(Fn->getLocation(), FDiag);
8832
Sebastian Redl08905022011-02-05 19:23:19 +00008833 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008834}
8835
Larisse Voufo98b20f12013-07-19 23:00:19 +00008836/// Additional arity mismatch diagnosis specific to a function overload
8837/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8838/// over a candidate in any candidate set.
8839bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8840 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008841 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008842 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008843
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008844 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008845 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008846 // right number of arguments, because only overloaded operators have
8847 // the weird behavior of overloading member and non-member functions.
8848 // Just don't report anything.
8849 if (Fn->isInvalidDecl() &&
8850 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008851 return true;
8852
8853 if (NumArgs < MinParams) {
8854 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8855 (Cand->FailureKind == ovl_fail_bad_deduction &&
8856 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8857 } else {
8858 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8859 (Cand->FailureKind == ovl_fail_bad_deduction &&
8860 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8861 }
8862
8863 return false;
8864}
8865
8866/// General arity mismatch diagnosis over a candidate in a candidate set.
8867void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8868 assert(isa<FunctionDecl>(D) &&
8869 "The templated declaration should at least be a function"
8870 " when diagnosing bad template argument deduction due to too many"
8871 " or too few arguments");
8872
8873 FunctionDecl *Fn = cast<FunctionDecl>(D);
8874
8875 // TODO: treat calls to a missing default constructor as a special case
8876 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8877 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008878
John McCall6a61b522010-01-13 09:16:55 +00008879 // at least / at most / exactly
8880 unsigned mode, modeCount;
8881 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008882 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8883 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008884 mode = 0; // "at least"
8885 else
8886 mode = 2; // "exactly"
8887 modeCount = MinParams;
8888 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008889 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008890 mode = 1; // "at most"
8891 else
8892 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008893 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008894 }
8895
8896 std::string Description;
8897 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8898
Richard Smith10ff50d2012-05-11 05:16:41 +00008899 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8900 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008901 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8902 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008903 else
8904 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008905 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8906 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008907 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008908}
8909
Larisse Voufo98b20f12013-07-19 23:00:19 +00008910/// Arity mismatch diagnosis specific to a function overload candidate.
8911void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8912 unsigned NumFormalArgs) {
8913 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8914 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8915}
Larisse Voufo47c08452013-07-19 22:53:23 +00008916
Larisse Voufo98b20f12013-07-19 23:00:19 +00008917TemplateDecl *getDescribedTemplate(Decl *Templated) {
8918 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8919 return FD->getDescribedFunctionTemplate();
8920 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8921 return RD->getDescribedClassTemplate();
8922
8923 llvm_unreachable("Unsupported: Getting the described template declaration"
8924 " for bad deduction diagnosis");
8925}
8926
8927/// Diagnose a failed template-argument deduction.
8928void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8929 DeductionFailureInfo &DeductionFailure,
8930 unsigned NumArgs) {
8931 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008932 NamedDecl *ParamD;
8933 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8934 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8935 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008936 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008937 case Sema::TDK_Success:
8938 llvm_unreachable("TDK_success while diagnosing bad deduction");
8939
8940 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008941 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008942 S.Diag(Templated->getLocation(),
8943 diag::note_ovl_candidate_incomplete_deduction)
8944 << ParamD->getDeclName();
8945 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008946 return;
8947 }
8948
John McCall42d7d192010-08-05 09:05:08 +00008949 case Sema::TDK_Underqualified: {
8950 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8951 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8952
Larisse Voufo98b20f12013-07-19 23:00:19 +00008953 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008954
8955 // Param will have been canonicalized, but it should just be a
8956 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008957 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008958 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008959 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008960 assert(S.Context.hasSameType(Param, NonCanonParam));
8961
8962 // Arg has also been canonicalized, but there's nothing we can do
8963 // about that. It also doesn't matter as much, because it won't
8964 // have any template parameters in it (because deduction isn't
8965 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008966 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008967
Larisse Voufo98b20f12013-07-19 23:00:19 +00008968 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8969 << ParamD->getDeclName() << Arg << NonCanonParam;
8970 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008971 return;
8972 }
8973
8974 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008975 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008976 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008977 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008978 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008979 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008980 which = 1;
8981 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008982 which = 2;
8983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008984
Larisse Voufo98b20f12013-07-19 23:00:19 +00008985 S.Diag(Templated->getLocation(),
8986 diag::note_ovl_candidate_inconsistent_deduction)
8987 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8988 << *DeductionFailure.getSecondArg();
8989 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008990 return;
8991 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008992
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008993 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008994 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008995 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008996 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008997 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008998 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008999 else {
9000 int index = 0;
9001 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9002 index = TTP->getIndex();
9003 else if (NonTypeTemplateParmDecl *NTTP
9004 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9005 index = NTTP->getIndex();
9006 else
9007 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009008 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009009 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009010 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009011 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009012 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009013 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009014
Douglas Gregor02eb4832010-05-08 18:13:28 +00009015 case Sema::TDK_TooManyArguments:
9016 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009017 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009018 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009019
9020 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009021 S.Diag(Templated->getLocation(),
9022 diag::note_ovl_candidate_instantiation_depth);
9023 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009024 return;
9025
9026 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009027 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009028 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009029 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009030 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009031 TemplateArgString = " ";
9032 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009033 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009034 }
9035
Richard Smith6f8d2c62012-05-09 05:17:00 +00009036 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009037 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009038 if (PDiag && PDiag->second.getDiagID() ==
9039 diag::err_typename_nested_not_found_enable_if) {
9040 // FIXME: Use the source range of the condition, and the fully-qualified
9041 // name of the enable_if template. These are both present in PDiag.
9042 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9043 << "'enable_if'" << TemplateArgString;
9044 return;
9045 }
9046
Richard Smith9ca64612012-05-07 09:03:25 +00009047 // Format the SFINAE diagnostic into the argument string.
9048 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9049 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009050 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009051 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009052 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009053 SFINAEArgString = ": ";
9054 R = SourceRange(PDiag->first, PDiag->first);
9055 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9056 }
9057
Larisse Voufo98b20f12013-07-19 23:00:19 +00009058 S.Diag(Templated->getLocation(),
9059 diag::note_ovl_candidate_substitution_failure)
9060 << TemplateArgString << SFINAEArgString << R;
9061 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009062 return;
9063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009064
Richard Smith8c6eeb92013-01-31 04:03:12 +00009065 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009066 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9067 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009068 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009069 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009070 return;
9071 }
9072
Richard Trieue3732352013-04-08 21:11:40 +00009073 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009074 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009075 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9076 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009077 if (FirstTA.getKind() == TemplateArgument::Template &&
9078 SecondTA.getKind() == TemplateArgument::Template) {
9079 TemplateName FirstTN = FirstTA.getAsTemplate();
9080 TemplateName SecondTN = SecondTA.getAsTemplate();
9081 if (FirstTN.getKind() == TemplateName::Template &&
9082 SecondTN.getKind() == TemplateName::Template) {
9083 if (FirstTN.getAsTemplateDecl()->getName() ==
9084 SecondTN.getAsTemplateDecl()->getName()) {
9085 // FIXME: This fixes a bad diagnostic where both templates are named
9086 // the same. This particular case is a bit difficult since:
9087 // 1) It is passed as a string to the diagnostic printer.
9088 // 2) The diagnostic printer only attempts to find a better
9089 // name for types, not decls.
9090 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009091 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009092 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9093 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9094 return;
9095 }
9096 }
9097 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009098 // FIXME: For generic lambda parameters, check if the function is a lambda
9099 // call operator, and if so, emit a prettier and more informative
9100 // diagnostic that mentions 'auto' and lambda in addition to
9101 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009102 S.Diag(Templated->getLocation(),
9103 diag::note_ovl_candidate_non_deduced_mismatch)
9104 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009105 return;
Richard Trieue3732352013-04-08 21:11:40 +00009106 }
John McCall8b9ed552010-02-01 18:53:26 +00009107 // TODO: diagnose these individually, then kill off
9108 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009109 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009110 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9111 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009112 return;
9113 }
9114}
9115
Larisse Voufo98b20f12013-07-19 23:00:19 +00009116/// Diagnose a failed template-argument deduction, for function calls.
9117void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
9118 unsigned TDK = Cand->DeductionFailure.Result;
9119 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9120 if (CheckArityMismatch(S, Cand, NumArgs))
9121 return;
9122 }
9123 DiagnoseBadDeduction(S, Cand->Function, // pattern
9124 Cand->DeductionFailure, NumArgs);
9125}
9126
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009127/// CUDA: diagnose an invalid call across targets.
9128void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9129 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9130 FunctionDecl *Callee = Cand->Function;
9131
9132 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9133 CalleeTarget = S.IdentifyCUDATarget(Callee);
9134
9135 std::string FnDesc;
9136 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9137
9138 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9139 << (unsigned) FnKind << CalleeTarget << CallerTarget;
9140}
9141
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009142void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9143 FunctionDecl *Callee = Cand->Function;
9144 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9145
9146 S.Diag(Callee->getLocation(),
9147 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9148 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9149}
9150
John McCall8b9ed552010-02-01 18:53:26 +00009151/// Generates a 'note' diagnostic for an overload candidate. We've
9152/// already generated a primary error at the call site.
9153///
9154/// It really does need to be a single diagnostic with its caret
9155/// pointed at the candidate declaration. Yes, this creates some
9156/// major challenges of technical writing. Yes, this makes pointing
9157/// out problems with specific arguments quite awkward. It's still
9158/// better than generating twenty screens of text for every failed
9159/// overload.
9160///
9161/// It would be great to be able to express per-candidate problems
9162/// more richly for those diagnostic clients that cared, but we'd
9163/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00009164void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009165 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009166 FunctionDecl *Fn = Cand->Function;
9167
John McCall12f97bc2010-01-08 04:41:39 +00009168 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009169 if (Cand->Viable && (Fn->isDeleted() ||
9170 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009171 std::string FnDesc;
9172 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009173
9174 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009175 << FnKind << FnDesc
9176 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009177 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009178 return;
John McCall12f97bc2010-01-08 04:41:39 +00009179 }
9180
John McCalle1ac8d12010-01-13 00:25:19 +00009181 // We don't really have anything else to say about viable candidates.
9182 if (Cand->Viable) {
9183 S.NoteOverloadCandidate(Fn);
9184 return;
9185 }
John McCall0d1da222010-01-12 00:44:57 +00009186
John McCall6a61b522010-01-13 09:16:55 +00009187 switch (Cand->FailureKind) {
9188 case ovl_fail_too_many_arguments:
9189 case ovl_fail_too_few_arguments:
9190 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009191
John McCall6a61b522010-01-13 09:16:55 +00009192 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009193 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009194
John McCallfe796dd2010-01-23 05:17:32 +00009195 case ovl_fail_trivial_conversion:
9196 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009197 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009198 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009199
John McCall65eb8792010-02-25 01:37:24 +00009200 case ovl_fail_bad_conversion: {
9201 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009202 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009203 if (Cand->Conversions[I].isBad())
9204 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009205
John McCall6a61b522010-01-13 09:16:55 +00009206 // FIXME: this currently happens when we're called from SemaInit
9207 // when user-conversion overload fails. Figure out how to handle
9208 // those conditions and diagnose them well.
9209 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009210 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009211
9212 case ovl_fail_bad_target:
9213 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009214
9215 case ovl_fail_enable_if:
9216 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009217 }
John McCalld3224162010-01-08 00:58:21 +00009218}
9219
9220void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9221 // Desugar the type of the surrogate down to a function type,
9222 // retaining as many typedefs as possible while still showing
9223 // the function type (and, therefore, its parameter types).
9224 QualType FnType = Cand->Surrogate->getConversionType();
9225 bool isLValueReference = false;
9226 bool isRValueReference = false;
9227 bool isPointer = false;
9228 if (const LValueReferenceType *FnTypeRef =
9229 FnType->getAs<LValueReferenceType>()) {
9230 FnType = FnTypeRef->getPointeeType();
9231 isLValueReference = true;
9232 } else if (const RValueReferenceType *FnTypeRef =
9233 FnType->getAs<RValueReferenceType>()) {
9234 FnType = FnTypeRef->getPointeeType();
9235 isRValueReference = true;
9236 }
9237 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9238 FnType = FnTypePtr->getPointeeType();
9239 isPointer = true;
9240 }
9241 // Desugar down to a function type.
9242 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9243 // Reconstruct the pointer/reference as appropriate.
9244 if (isPointer) FnType = S.Context.getPointerType(FnType);
9245 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9246 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9247
9248 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9249 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009250 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009251}
9252
9253void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00009254 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00009255 SourceLocation OpLoc,
9256 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009257 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009258 std::string TypeStr("operator");
9259 TypeStr += Opc;
9260 TypeStr += "(";
9261 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009262 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009263 TypeStr += ")";
9264 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9265 } else {
9266 TypeStr += ", ";
9267 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9268 TypeStr += ")";
9269 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9270 }
9271}
9272
9273void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9274 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009275 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009276 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9277 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009278 if (ICS.isBad()) break; // all meaningless after first invalid
9279 if (!ICS.isAmbiguous()) continue;
9280
John McCall5c32be02010-08-24 20:38:10 +00009281 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009282 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009283 }
9284}
9285
Larisse Voufo98b20f12013-07-19 23:00:19 +00009286static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009287 if (Cand->Function)
9288 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009289 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009290 return Cand->Surrogate->getLocation();
9291 return SourceLocation();
9292}
9293
Larisse Voufo98b20f12013-07-19 23:00:19 +00009294static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009295 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009296 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009297 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009298
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009299 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009300 case Sema::TDK_Incomplete:
9301 return 1;
9302
9303 case Sema::TDK_Underqualified:
9304 case Sema::TDK_Inconsistent:
9305 return 2;
9306
9307 case Sema::TDK_SubstitutionFailure:
9308 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009309 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009310 return 3;
9311
9312 case Sema::TDK_InstantiationDepth:
9313 case Sema::TDK_FailedOverloadResolution:
9314 return 4;
9315
9316 case Sema::TDK_InvalidExplicitArguments:
9317 return 5;
9318
9319 case Sema::TDK_TooManyArguments:
9320 case Sema::TDK_TooFewArguments:
9321 return 6;
9322 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009323 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009324}
9325
John McCallad2587a2010-01-12 00:48:53 +00009326struct CompareOverloadCandidatesForDisplay {
9327 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009328 size_t NumArgs;
9329
9330 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9331 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009332
9333 bool operator()(const OverloadCandidate *L,
9334 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009335 // Fast-path this check.
9336 if (L == R) return false;
9337
John McCall12f97bc2010-01-08 04:41:39 +00009338 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009339 if (L->Viable) {
9340 if (!R->Viable) return true;
9341
9342 // TODO: introduce a tri-valued comparison for overload
9343 // candidates. Would be more worthwhile if we had a sort
9344 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009345 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9346 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009347 } else if (R->Viable)
9348 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009349
John McCall3712d9e2010-01-15 23:32:50 +00009350 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009351
John McCall3712d9e2010-01-15 23:32:50 +00009352 // Criteria by which we can sort non-viable candidates:
9353 if (!L->Viable) {
9354 // 1. Arity mismatches come after other candidates.
9355 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009356 L->FailureKind == ovl_fail_too_few_arguments) {
9357 if (R->FailureKind == ovl_fail_too_many_arguments ||
9358 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009359 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9360 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9361 if (LDist == RDist) {
9362 if (L->FailureKind == R->FailureKind)
9363 // Sort non-surrogates before surrogates.
9364 return !L->IsSurrogate && R->IsSurrogate;
9365 // Sort candidates requiring fewer parameters than there were
9366 // arguments given after candidates requiring more parameters
9367 // than there were arguments given.
9368 return L->FailureKind == ovl_fail_too_many_arguments;
9369 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009370 return LDist < RDist;
9371 }
John McCall3712d9e2010-01-15 23:32:50 +00009372 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009373 }
John McCall3712d9e2010-01-15 23:32:50 +00009374 if (R->FailureKind == ovl_fail_too_many_arguments ||
9375 R->FailureKind == ovl_fail_too_few_arguments)
9376 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009377
John McCallfe796dd2010-01-23 05:17:32 +00009378 // 2. Bad conversions come first and are ordered by the number
9379 // of bad conversions and quality of good conversions.
9380 if (L->FailureKind == ovl_fail_bad_conversion) {
9381 if (R->FailureKind != ovl_fail_bad_conversion)
9382 return true;
9383
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009384 // The conversion that can be fixed with a smaller number of changes,
9385 // comes first.
9386 unsigned numLFixes = L->Fix.NumConversionsFixed;
9387 unsigned numRFixes = R->Fix.NumConversionsFixed;
9388 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9389 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009390 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009391 if (numLFixes < numRFixes)
9392 return true;
9393 else
9394 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009395 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009396
John McCallfe796dd2010-01-23 05:17:32 +00009397 // If there's any ordering between the defined conversions...
9398 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009399 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009400
9401 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009402 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009403 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009404 switch (CompareImplicitConversionSequences(S,
9405 L->Conversions[I],
9406 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009407 case ImplicitConversionSequence::Better:
9408 leftBetter++;
9409 break;
9410
9411 case ImplicitConversionSequence::Worse:
9412 leftBetter--;
9413 break;
9414
9415 case ImplicitConversionSequence::Indistinguishable:
9416 break;
9417 }
9418 }
9419 if (leftBetter > 0) return true;
9420 if (leftBetter < 0) return false;
9421
9422 } else if (R->FailureKind == ovl_fail_bad_conversion)
9423 return false;
9424
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009425 if (L->FailureKind == ovl_fail_bad_deduction) {
9426 if (R->FailureKind != ovl_fail_bad_deduction)
9427 return true;
9428
9429 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9430 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009431 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009432 } else if (R->FailureKind == ovl_fail_bad_deduction)
9433 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009434
John McCall3712d9e2010-01-15 23:32:50 +00009435 // TODO: others?
9436 }
9437
9438 // Sort everything else by location.
9439 SourceLocation LLoc = GetLocationForCandidate(L);
9440 SourceLocation RLoc = GetLocationForCandidate(R);
9441
9442 // Put candidates without locations (e.g. builtins) at the end.
9443 if (LLoc.isInvalid()) return false;
9444 if (RLoc.isInvalid()) return true;
9445
9446 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009447 }
9448};
9449
John McCallfe796dd2010-01-23 05:17:32 +00009450/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009451/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00009452void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009453 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009454 assert(!Cand->Viable);
9455
9456 // Don't do anything on failures other than bad conversion.
9457 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9458
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009459 // We only want the FixIts if all the arguments can be corrected.
9460 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009461 // Use a implicit copy initialization to check conversion fixes.
9462 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009463
John McCallfe796dd2010-01-23 05:17:32 +00009464 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009465 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009466 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009467 while (true) {
9468 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9469 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009470 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009471 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009472 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009473 }
John McCallfe796dd2010-01-23 05:17:32 +00009474 }
9475
9476 if (ConvIdx == ConvCount)
9477 return;
9478
John McCall65eb8792010-02-25 01:37:24 +00009479 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9480 "remaining conversion is initialized?");
9481
Douglas Gregoradc7a702010-04-16 17:45:54 +00009482 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009483 // operation somehow.
9484 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009485
9486 const FunctionProtoType* Proto;
9487 unsigned ArgIdx = ConvIdx;
9488
9489 if (Cand->IsSurrogate) {
9490 QualType ConvType
9491 = Cand->Surrogate->getConversionType().getNonReferenceType();
9492 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9493 ConvType = ConvPtrType->getPointeeType();
9494 Proto = ConvType->getAs<FunctionProtoType>();
9495 ArgIdx--;
9496 } else if (Cand->Function) {
9497 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9498 if (isa<CXXMethodDecl>(Cand->Function) &&
9499 !isa<CXXConstructorDecl>(Cand->Function))
9500 ArgIdx--;
9501 } else {
9502 // Builtin binary operator with a bad first conversion.
9503 assert(ConvCount <= 3);
9504 for (; ConvIdx != ConvCount; ++ConvIdx)
9505 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009506 = TryCopyInitialization(S, Args[ConvIdx],
9507 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009508 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009509 /*InOverloadResolution*/ true,
9510 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009511 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009512 return;
9513 }
9514
9515 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009516 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009517 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009518 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009519 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9520 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9521 /*InOverloadResolution=*/true,
9522 /*AllowObjCWritebackConversion=*/
9523 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009524 // Store the FixIt in the candidate if it exists.
9525 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009526 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009527 }
John McCallfe796dd2010-01-23 05:17:32 +00009528 else
9529 Cand->Conversions[ConvIdx].setEllipsis();
9530 }
9531}
9532
John McCalld3224162010-01-08 00:58:21 +00009533} // end anonymous namespace
9534
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009535/// PrintOverloadCandidates - When overload resolution fails, prints
9536/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009537/// set.
John McCall5c32be02010-08-24 20:38:10 +00009538void OverloadCandidateSet::NoteCandidates(Sema &S,
9539 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009540 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009541 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009542 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009543 // Sort the candidates by viability and position. Sorting directly would
9544 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009545 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009546 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9547 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009548 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009549 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009550 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009551 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009552 if (Cand->Function || Cand->IsSurrogate)
9553 Cands.push_back(Cand);
9554 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9555 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009556 }
9557 }
9558
John McCallad2587a2010-01-12 00:48:53 +00009559 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009560 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009561
John McCall0d1da222010-01-12 00:44:57 +00009562 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009563
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009564 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009565 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009566 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009567 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9568 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009569
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009570 // Set an arbitrary limit on the number of candidate functions we'll spam
9571 // the user with. FIXME: This limit should depend on details of the
9572 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009573 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009574 break;
9575 }
9576 ++CandsShown;
9577
John McCalld3224162010-01-08 00:58:21 +00009578 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009579 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009580 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009581 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009582 else {
9583 assert(Cand->Viable &&
9584 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009585 // Generally we only see ambiguities including viable builtin
9586 // operators if overload resolution got screwed up by an
9587 // ambiguous user-defined conversion.
9588 //
9589 // FIXME: It's quite possible for different conversions to see
9590 // different ambiguities, though.
9591 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009592 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009593 ReportedAmbiguousConversions = true;
9594 }
John McCalld3224162010-01-08 00:58:21 +00009595
John McCall0d1da222010-01-12 00:44:57 +00009596 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009597 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009598 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009599 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009600
9601 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009602 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009603}
9604
Larisse Voufo98b20f12013-07-19 23:00:19 +00009605static SourceLocation
9606GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9607 return Cand->Specialization ? Cand->Specialization->getLocation()
9608 : SourceLocation();
9609}
9610
9611struct CompareTemplateSpecCandidatesForDisplay {
9612 Sema &S;
9613 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9614
9615 bool operator()(const TemplateSpecCandidate *L,
9616 const TemplateSpecCandidate *R) {
9617 // Fast-path this check.
9618 if (L == R)
9619 return false;
9620
9621 // Assuming that both candidates are not matches...
9622
9623 // Sort by the ranking of deduction failures.
9624 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9625 return RankDeductionFailure(L->DeductionFailure) <
9626 RankDeductionFailure(R->DeductionFailure);
9627
9628 // Sort everything else by location.
9629 SourceLocation LLoc = GetLocationForCandidate(L);
9630 SourceLocation RLoc = GetLocationForCandidate(R);
9631
9632 // Put candidates without locations (e.g. builtins) at the end.
9633 if (LLoc.isInvalid())
9634 return false;
9635 if (RLoc.isInvalid())
9636 return true;
9637
9638 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9639 }
9640};
9641
9642/// Diagnose a template argument deduction failure.
9643/// We are treating these failures as overload failures due to bad
9644/// deductions.
9645void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9646 DiagnoseBadDeduction(S, Specialization, // pattern
9647 DeductionFailure, /*NumArgs=*/0);
9648}
9649
9650void TemplateSpecCandidateSet::destroyCandidates() {
9651 for (iterator i = begin(), e = end(); i != e; ++i) {
9652 i->DeductionFailure.Destroy();
9653 }
9654}
9655
9656void TemplateSpecCandidateSet::clear() {
9657 destroyCandidates();
9658 Candidates.clear();
9659}
9660
9661/// NoteCandidates - When no template specialization match is found, prints
9662/// diagnostic messages containing the non-matching specializations that form
9663/// the candidate set.
9664/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9665/// OCD == OCD_AllCandidates and Cand->Viable == false.
9666void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9667 // Sort the candidates by position (assuming no candidate is a match).
9668 // Sorting directly would be prohibitive, so we make a set of pointers
9669 // and sort those.
9670 SmallVector<TemplateSpecCandidate *, 32> Cands;
9671 Cands.reserve(size());
9672 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9673 if (Cand->Specialization)
9674 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009675 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009676 // in general, want to list every possible builtin candidate.
9677 }
9678
9679 std::sort(Cands.begin(), Cands.end(),
9680 CompareTemplateSpecCandidatesForDisplay(S));
9681
9682 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9683 // for generalization purposes (?).
9684 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9685
9686 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9687 unsigned CandsShown = 0;
9688 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9689 TemplateSpecCandidate *Cand = *I;
9690
9691 // Set an arbitrary limit on the number of candidates we'll spam
9692 // the user with. FIXME: This limit should depend on details of the
9693 // candidate list.
9694 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9695 break;
9696 ++CandsShown;
9697
9698 assert(Cand->Specialization &&
9699 "Non-matching built-in candidates are not added to Cands.");
9700 Cand->NoteDeductionFailure(S);
9701 }
9702
9703 if (I != E)
9704 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9705}
9706
Douglas Gregorb491ed32011-02-19 21:32:49 +00009707// [PossiblyAFunctionType] --> [Return]
9708// NonFunctionType --> NonFunctionType
9709// R (A) --> R(A)
9710// R (*)(A) --> R (A)
9711// R (&)(A) --> R (A)
9712// R (S::*)(A) --> R (A)
9713QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9714 QualType Ret = PossiblyAFunctionType;
9715 if (const PointerType *ToTypePtr =
9716 PossiblyAFunctionType->getAs<PointerType>())
9717 Ret = ToTypePtr->getPointeeType();
9718 else if (const ReferenceType *ToTypeRef =
9719 PossiblyAFunctionType->getAs<ReferenceType>())
9720 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009721 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009722 PossiblyAFunctionType->getAs<MemberPointerType>())
9723 Ret = MemTypePtr->getPointeeType();
9724 Ret =
9725 Context.getCanonicalType(Ret).getUnqualifiedType();
9726 return Ret;
9727}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009728
Douglas Gregorb491ed32011-02-19 21:32:49 +00009729// A helper class to help with address of function resolution
9730// - allows us to avoid passing around all those ugly parameters
9731class AddressOfFunctionResolver
9732{
9733 Sema& S;
9734 Expr* SourceExpr;
9735 const QualType& TargetType;
9736 QualType TargetFunctionType; // Extracted function type from target type
9737
9738 bool Complain;
9739 //DeclAccessPair& ResultFunctionAccessPair;
9740 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009741
Douglas Gregorb491ed32011-02-19 21:32:49 +00009742 bool TargetTypeIsNonStaticMemberFunction;
9743 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009744 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009745
Douglas Gregorb491ed32011-02-19 21:32:49 +00009746 OverloadExpr::FindResult OvlExprInfo;
9747 OverloadExpr *OvlExpr;
9748 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009749 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009750 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009751
Douglas Gregorb491ed32011-02-19 21:32:49 +00009752public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009753 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9754 const QualType &TargetType, bool Complain)
9755 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9756 Complain(Complain), Context(S.getASTContext()),
9757 TargetTypeIsNonStaticMemberFunction(
9758 !!TargetType->getAs<MemberPointerType>()),
9759 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009760 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009761 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9762 OvlExpr(OvlExprInfo.Expression),
9763 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009764 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009765
David Majnemera4f7c7a2013-08-01 06:13:59 +00009766 if (TargetFunctionType->isFunctionType()) {
9767 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9768 if (!UME->isImplicitAccess() &&
9769 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9770 StaticMemberFunctionFromBoundPointer = true;
9771 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9772 DeclAccessPair dap;
9773 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9774 OvlExpr, false, &dap)) {
9775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9776 if (!Method->isStatic()) {
9777 // If the target type is a non-function type and the function found
9778 // is a non-static member function, pretend as if that was the
9779 // target, it's the only possible type to end up with.
9780 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009781
David Majnemera4f7c7a2013-08-01 06:13:59 +00009782 // And skip adding the function if its not in the proper form.
9783 // We'll diagnose this due to an empty set of functions.
9784 if (!OvlExprInfo.HasFormOfMemberPointer)
9785 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009786 }
9787
David Majnemera4f7c7a2013-08-01 06:13:59 +00009788 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009789 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009790 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009791 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009792
9793 if (OvlExpr->hasExplicitTemplateArgs())
9794 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009795
Douglas Gregorb491ed32011-02-19 21:32:49 +00009796 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9797 // C++ [over.over]p4:
9798 // If more than one function is selected, [...]
9799 if (Matches.size() > 1) {
9800 if (FoundNonTemplateFunction)
9801 EliminateAllTemplateMatches();
9802 else
9803 EliminateAllExceptMostSpecializedTemplate();
9804 }
9805 }
9806 }
9807
9808private:
9809 bool isTargetTypeAFunction() const {
9810 return TargetFunctionType->isFunctionType();
9811 }
9812
9813 // [ToType] [Return]
9814
9815 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9816 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9817 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9818 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9819 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9820 }
9821
9822 // return true if any matching specializations were found
9823 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9824 const DeclAccessPair& CurAccessFunPair) {
9825 if (CXXMethodDecl *Method
9826 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9827 // Skip non-static function templates when converting to pointer, and
9828 // static when converting to member pointer.
9829 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9830 return false;
9831 }
9832 else if (TargetTypeIsNonStaticMemberFunction)
9833 return false;
9834
9835 // C++ [over.over]p2:
9836 // If the name is a function template, template argument deduction is
9837 // done (14.8.2.2), and if the argument deduction succeeds, the
9838 // resulting template argument list is used to generate a single
9839 // function template specialization, which is added to the set of
9840 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009841 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009842 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009843 if (Sema::TemplateDeductionResult Result
9844 = S.DeduceTemplateArguments(FunctionTemplate,
9845 &OvlExplicitTemplateArgs,
9846 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009847 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009848 // Make a note of the failed deduction for diagnostics.
9849 FailedCandidates.addCandidate()
9850 .set(FunctionTemplate->getTemplatedDecl(),
9851 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009852 return false;
9853 }
9854
Douglas Gregor19a41f12013-04-17 08:45:07 +00009855 // Template argument deduction ensures that we have an exact match or
9856 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009857 // This function template specicalization works.
9858 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009859 assert(S.isSameOrCompatibleFunctionType(
9860 Context.getCanonicalType(Specialization->getType()),
9861 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009862 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9863 return true;
9864 }
9865
9866 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9867 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009868 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009869 // Skip non-static functions when converting to pointer, and static
9870 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009871 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9872 return false;
9873 }
9874 else if (TargetTypeIsNonStaticMemberFunction)
9875 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009876
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009877 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009878 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009879 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9880 if (S.CheckCUDATarget(Caller, FunDecl))
9881 return false;
9882
Richard Smith2a7d4812013-05-04 07:00:32 +00009883 // If any candidate has a placeholder return type, trigger its deduction
9884 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00009885 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +00009886 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00009887 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9888 return false;
9889
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009890 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009891 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9892 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009893 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9894 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009895 Matches.push_back(std::make_pair(CurAccessFunPair,
9896 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009897 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009898 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009899 }
Mike Stump11289f42009-09-09 15:08:12 +00009900 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009901
9902 return false;
9903 }
9904
9905 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9906 bool Ret = false;
9907
9908 // If the overload expression doesn't have the form of a pointer to
9909 // member, don't try to convert it to a pointer-to-member type.
9910 if (IsInvalidFormOfPointerToMemberFunction())
9911 return false;
9912
9913 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9914 E = OvlExpr->decls_end();
9915 I != E; ++I) {
9916 // Look through any using declarations to find the underlying function.
9917 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9918
9919 // C++ [over.over]p3:
9920 // Non-member functions and static member functions match
9921 // targets of type "pointer-to-function" or "reference-to-function."
9922 // Nonstatic member functions match targets of
9923 // type "pointer-to-member-function."
9924 // Note that according to DR 247, the containing class does not matter.
9925 if (FunctionTemplateDecl *FunctionTemplate
9926 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9927 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9928 Ret = true;
9929 }
9930 // If we have explicit template arguments supplied, skip non-templates.
9931 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9932 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9933 Ret = true;
9934 }
9935 assert(Ret || Matches.empty());
9936 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009937 }
9938
Douglas Gregorb491ed32011-02-19 21:32:49 +00009939 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009940 // [...] and any given function template specialization F1 is
9941 // eliminated if the set contains a second function template
9942 // specialization whose function template is more specialized
9943 // than the function template of F1 according to the partial
9944 // ordering rules of 14.5.5.2.
9945
9946 // The algorithm specified above is quadratic. We instead use a
9947 // two-pass algorithm (similar to the one used to identify the
9948 // best viable function in an overload set) that identifies the
9949 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009950
9951 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9952 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9953 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009954
Larisse Voufo98b20f12013-07-19 23:00:19 +00009955 // TODO: It looks like FailedCandidates does not serve much purpose
9956 // here, since the no_viable diagnostic has index 0.
9957 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009958 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009959 SourceExpr->getLocStart(), S.PDiag(),
9960 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9961 .second->getDeclName(),
9962 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9963 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009964
Douglas Gregorb491ed32011-02-19 21:32:49 +00009965 if (Result != MatchesCopy.end()) {
9966 // Make it the first and only element
9967 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9968 Matches[0].second = cast<FunctionDecl>(*Result);
9969 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009970 }
9971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009972
Douglas Gregorb491ed32011-02-19 21:32:49 +00009973 void EliminateAllTemplateMatches() {
9974 // [...] any function template specializations in the set are
9975 // eliminated if the set also contains a non-template function, [...]
9976 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009977 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009978 ++I;
9979 else {
9980 Matches[I] = Matches[--N];
9981 Matches.set_size(N);
9982 }
9983 }
9984 }
9985
9986public:
9987 void ComplainNoMatchesFound() const {
9988 assert(Matches.empty());
9989 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9990 << OvlExpr->getName() << TargetFunctionType
9991 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +00009992 if (FailedCandidates.empty())
9993 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9994 else {
9995 // We have some deduction failure messages. Use them to diagnose
9996 // the function templates, and diagnose the non-template candidates
9997 // normally.
9998 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9999 IEnd = OvlExpr->decls_end();
10000 I != IEnd; ++I)
10001 if (FunctionDecl *Fun =
10002 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10003 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10004 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10005 }
10006 }
10007
Douglas Gregorb491ed32011-02-19 21:32:49 +000010008 bool IsInvalidFormOfPointerToMemberFunction() const {
10009 return TargetTypeIsNonStaticMemberFunction &&
10010 !OvlExprInfo.HasFormOfMemberPointer;
10011 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010012
Douglas Gregorb491ed32011-02-19 21:32:49 +000010013 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10014 // TODO: Should we condition this on whether any functions might
10015 // have matched, or is it more appropriate to do that in callers?
10016 // TODO: a fixit wouldn't hurt.
10017 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10018 << TargetType << OvlExpr->getSourceRange();
10019 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010020
10021 bool IsStaticMemberFunctionFromBoundPointer() const {
10022 return StaticMemberFunctionFromBoundPointer;
10023 }
10024
10025 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10026 S.Diag(OvlExpr->getLocStart(),
10027 diag::err_invalid_form_pointer_member_function)
10028 << OvlExpr->getSourceRange();
10029 }
10030
Douglas Gregorb491ed32011-02-19 21:32:49 +000010031 void ComplainOfInvalidConversion() const {
10032 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10033 << OvlExpr->getName() << TargetType;
10034 }
10035
10036 void ComplainMultipleMatchesFound() const {
10037 assert(Matches.size() > 1);
10038 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10039 << OvlExpr->getName()
10040 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010041 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010042 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010043
10044 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10045
Douglas Gregorb491ed32011-02-19 21:32:49 +000010046 int getNumMatches() const { return Matches.size(); }
10047
10048 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010049 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010050 return Matches[0].second;
10051 }
10052
10053 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010054 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010055 return &Matches[0].first;
10056 }
10057};
10058
10059/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10060/// an overloaded function (C++ [over.over]), where @p From is an
10061/// expression with overloaded function type and @p ToType is the type
10062/// we're trying to resolve to. For example:
10063///
10064/// @code
10065/// int f(double);
10066/// int f(int);
10067///
10068/// int (*pfd)(double) = f; // selects f(double)
10069/// @endcode
10070///
10071/// This routine returns the resulting FunctionDecl if it could be
10072/// resolved, and NULL otherwise. When @p Complain is true, this
10073/// routine will emit diagnostics if there is an error.
10074FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010075Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10076 QualType TargetType,
10077 bool Complain,
10078 DeclAccessPair &FoundResult,
10079 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010080 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010081
10082 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10083 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010084 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010085 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010086 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010087 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10088 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10089 else
10090 Resolver.ComplainNoMatchesFound();
10091 }
10092 else if (NumMatches > 1 && Complain)
10093 Resolver.ComplainMultipleMatchesFound();
10094 else if (NumMatches == 1) {
10095 Fn = Resolver.getMatchingFunctionDecl();
10096 assert(Fn);
10097 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010098 if (Complain) {
10099 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10100 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10101 else
10102 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10103 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010104 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010105
10106 if (pHadMultipleCandidates)
10107 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010108 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010109}
10110
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010111/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010112/// resolve that overloaded function expression down to a single function.
10113///
10114/// This routine can only resolve template-ids that refer to a single function
10115/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010116/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010117/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010118///
10119/// If no template-ids are found, no diagnostics are emitted and NULL is
10120/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010121FunctionDecl *
10122Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10123 bool Complain,
10124 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010125 // C++ [over.over]p1:
10126 // [...] [Note: any redundant set of parentheses surrounding the
10127 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010128 // C++ [over.over]p1:
10129 // [...] The overloaded function name can be preceded by the &
10130 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010131
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010132 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010133 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010134 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010135
10136 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010137 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010138 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010139
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010140 // Look through all of the overloaded functions, searching for one
10141 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010142 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010143 for (UnresolvedSetIterator I = ovl->decls_begin(),
10144 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010145 // C++0x [temp.arg.explicit]p3:
10146 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010147 // where deduction is not done, if a template argument list is
10148 // specified and it, along with any default template arguments,
10149 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010150 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010151 FunctionTemplateDecl *FunctionTemplate
10152 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010153
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010154 // C++ [over.over]p2:
10155 // If the name is a function template, template argument deduction is
10156 // done (14.8.2.2), and if the argument deduction succeeds, the
10157 // resulting template argument list is used to generate a single
10158 // function template specialization, which is added to the set of
10159 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010160 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010161 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010162 if (TemplateDeductionResult Result
10163 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010164 Specialization, Info,
10165 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010166 // Make a note of the failed deduction for diagnostics.
10167 // TODO: Actually use the failed-deduction info?
10168 FailedCandidates.addCandidate()
10169 .set(FunctionTemplate->getTemplatedDecl(),
10170 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010171 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010172 }
10173
John McCall0009fcc2011-04-26 20:42:42 +000010174 assert(Specialization && "no specialization and no error?");
10175
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010176 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010177 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010178 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010179 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10180 << ovl->getName();
10181 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010182 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010183 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010184 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010185
John McCall0009fcc2011-04-26 20:42:42 +000010186 Matched = Specialization;
10187 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010189
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010190 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010191 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010192 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010193 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010194
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010195 return Matched;
10196}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010197
Douglas Gregor1beec452011-03-12 01:48:56 +000010198
10199
10200
John McCall50a2c2c2011-10-11 23:14:30 +000010201// Resolve and fix an overloaded expression that can be resolved
10202// because it identifies a single function template specialization.
10203//
Douglas Gregor1beec452011-03-12 01:48:56 +000010204// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010205//
10206// Return true if it was logically possible to so resolve the
10207// expression, regardless of whether or not it succeeded. Always
10208// returns true if 'complain' is set.
10209bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10210 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10211 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010212 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010213 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010214 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010215
John McCall50a2c2c2011-10-11 23:14:30 +000010216 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010217
John McCall0009fcc2011-04-26 20:42:42 +000010218 DeclAccessPair found;
10219 ExprResult SingleFunctionExpression;
10220 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10221 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010222 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010223 SrcExpr = ExprError();
10224 return true;
10225 }
John McCall0009fcc2011-04-26 20:42:42 +000010226
10227 // It is only correct to resolve to an instance method if we're
10228 // resolving a form that's permitted to be a pointer to member.
10229 // Otherwise we'll end up making a bound member expression, which
10230 // is illegal in all the contexts we resolve like this.
10231 if (!ovl.HasFormOfMemberPointer &&
10232 isa<CXXMethodDecl>(fn) &&
10233 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010234 if (!complain) return false;
10235
10236 Diag(ovl.Expression->getExprLoc(),
10237 diag::err_bound_member_function)
10238 << 0 << ovl.Expression->getSourceRange();
10239
10240 // TODO: I believe we only end up here if there's a mix of
10241 // static and non-static candidates (otherwise the expression
10242 // would have 'bound member' type, not 'overload' type).
10243 // Ideally we would note which candidate was chosen and why
10244 // the static candidates were rejected.
10245 SrcExpr = ExprError();
10246 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010247 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010248
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010249 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010250 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010251 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010252
10253 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010254 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010255 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010256 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010257 if (SingleFunctionExpression.isInvalid()) {
10258 SrcExpr = ExprError();
10259 return true;
10260 }
10261 }
John McCall0009fcc2011-04-26 20:42:42 +000010262 }
10263
10264 if (!SingleFunctionExpression.isUsable()) {
10265 if (complain) {
10266 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10267 << ovl.Expression->getName()
10268 << DestTypeForComplaining
10269 << OpRangeForComplaining
10270 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010271 NoteAllOverloadCandidates(SrcExpr.get());
10272
10273 SrcExpr = ExprError();
10274 return true;
10275 }
10276
10277 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010278 }
10279
John McCall50a2c2c2011-10-11 23:14:30 +000010280 SrcExpr = SingleFunctionExpression;
10281 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010282}
10283
Douglas Gregorcabea402009-09-22 15:41:20 +000010284/// \brief Add a single candidate to the overload set.
10285static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010286 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010287 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010288 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010289 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010290 bool PartialOverloading,
10291 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010292 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010293 if (isa<UsingShadowDecl>(Callee))
10294 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10295
Douglas Gregorcabea402009-09-22 15:41:20 +000010296 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010297 if (ExplicitTemplateArgs) {
10298 assert(!KnownValid && "Explicit template arguments?");
10299 return;
10300 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010301 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10302 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010303 return;
John McCalld14a8642009-11-21 08:51:07 +000010304 }
10305
10306 if (FunctionTemplateDecl *FuncTemplate
10307 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010308 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010309 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010310 return;
10311 }
10312
Richard Smith95ce4f62011-06-26 22:19:54 +000010313 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010314}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010315
Douglas Gregorcabea402009-09-22 15:41:20 +000010316/// \brief Add the overload candidates named by callee and/or found by argument
10317/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010318void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010319 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010320 OverloadCandidateSet &CandidateSet,
10321 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010322
10323#ifndef NDEBUG
10324 // Verify that ArgumentDependentLookup is consistent with the rules
10325 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010326 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010327 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10328 // and let Y be the lookup set produced by argument dependent
10329 // lookup (defined as follows). If X contains
10330 //
10331 // -- a declaration of a class member, or
10332 //
10333 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010334 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010335 //
10336 // -- a declaration that is neither a function or a function
10337 // template
10338 //
10339 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010340
John McCall57500772009-12-16 12:17:52 +000010341 if (ULE->requiresADL()) {
10342 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10343 E = ULE->decls_end(); I != E; ++I) {
10344 assert(!(*I)->getDeclContext()->isRecord());
10345 assert(isa<UsingShadowDecl>(*I) ||
10346 !(*I)->getDeclContext()->isFunctionOrMethod());
10347 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010348 }
10349 }
10350#endif
10351
John McCall57500772009-12-16 12:17:52 +000010352 // It would be nice to avoid this copy.
10353 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010354 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010355 if (ULE->hasExplicitTemplateArgs()) {
10356 ULE->copyTemplateArgumentsInto(TABuffer);
10357 ExplicitTemplateArgs = &TABuffer;
10358 }
10359
10360 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10361 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010362 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10363 CandidateSet, PartialOverloading,
10364 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010365
John McCall57500772009-12-16 12:17:52 +000010366 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010367 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010368 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010369 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010370}
John McCalld681c392009-12-16 08:11:27 +000010371
Richard Smith0603bbb2013-06-12 22:56:54 +000010372/// Determine whether a declaration with the specified name could be moved into
10373/// a different namespace.
10374static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10375 switch (Name.getCXXOverloadedOperator()) {
10376 case OO_New: case OO_Array_New:
10377 case OO_Delete: case OO_Array_Delete:
10378 return false;
10379
10380 default:
10381 return true;
10382 }
10383}
10384
Richard Smith998a5912011-06-05 22:42:48 +000010385/// Attempt to recover from an ill-formed use of a non-dependent name in a
10386/// template, where the non-dependent name was declared after the template
10387/// was defined. This is common in code written for a compilers which do not
10388/// correctly implement two-stage name lookup.
10389///
10390/// Returns true if a viable candidate was found and a diagnostic was issued.
10391static bool
10392DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10393 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010394 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010395 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010396 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010397 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10398 return false;
10399
10400 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010401 if (DC->isTransparentContext())
10402 continue;
10403
Richard Smith998a5912011-06-05 22:42:48 +000010404 SemaRef.LookupQualifiedName(R, DC);
10405
10406 if (!R.empty()) {
10407 R.suppressDiagnostics();
10408
10409 if (isa<CXXRecordDecl>(DC)) {
10410 // Don't diagnose names we find in classes; we get much better
10411 // diagnostics for these from DiagnoseEmptyLookup.
10412 R.clear();
10413 return false;
10414 }
10415
Richard Smith100b24a2014-04-17 01:52:14 +000010416 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010417 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10418 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010419 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010420 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010421
10422 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010423 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010424 // No viable functions. Don't bother the user with notes for functions
10425 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010426 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010427 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010428 }
Richard Smith998a5912011-06-05 22:42:48 +000010429
10430 // Find the namespaces where ADL would have looked, and suggest
10431 // declaring the function there instead.
10432 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10433 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010434 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010435 AssociatedNamespaces,
10436 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010437 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010438 if (canBeDeclaredInNamespace(R.getLookupName())) {
10439 DeclContext *Std = SemaRef.getStdNamespace();
10440 for (Sema::AssociatedNamespaceSet::iterator
10441 it = AssociatedNamespaces.begin(),
10442 end = AssociatedNamespaces.end(); it != end; ++it) {
10443 // Never suggest declaring a function within namespace 'std'.
10444 if (Std && Std->Encloses(*it))
10445 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010446
Richard Smith0603bbb2013-06-12 22:56:54 +000010447 // Never suggest declaring a function within a namespace with a
10448 // reserved name, like __gnu_cxx.
10449 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10450 if (NS &&
10451 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10452 continue;
10453
10454 SuggestedNamespaces.insert(*it);
10455 }
Richard Smith998a5912011-06-05 22:42:48 +000010456 }
10457
10458 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10459 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010460 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010461 SemaRef.Diag(Best->Function->getLocation(),
10462 diag::note_not_found_by_two_phase_lookup)
10463 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010464 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010465 SemaRef.Diag(Best->Function->getLocation(),
10466 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010467 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010468 } else {
10469 // FIXME: It would be useful to list the associated namespaces here,
10470 // but the diagnostics infrastructure doesn't provide a way to produce
10471 // a localized representation of a list of items.
10472 SemaRef.Diag(Best->Function->getLocation(),
10473 diag::note_not_found_by_two_phase_lookup)
10474 << R.getLookupName() << 2;
10475 }
10476
10477 // Try to recover by calling this function.
10478 return true;
10479 }
10480
10481 R.clear();
10482 }
10483
10484 return false;
10485}
10486
10487/// Attempt to recover from ill-formed use of a non-dependent operator in a
10488/// template, where the non-dependent operator was declared after the template
10489/// was defined.
10490///
10491/// Returns true if a viable candidate was found and a diagnostic was issued.
10492static bool
10493DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10494 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010495 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010496 DeclarationName OpName =
10497 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10498 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10499 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010500 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010501 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010502}
10503
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010504namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010505class BuildRecoveryCallExprRAII {
10506 Sema &SemaRef;
10507public:
10508 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10509 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10510 SemaRef.IsBuildingRecoveryCallExpr = true;
10511 }
10512
10513 ~BuildRecoveryCallExprRAII() {
10514 SemaRef.IsBuildingRecoveryCallExpr = false;
10515 }
10516};
10517
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010518}
10519
John McCalld681c392009-12-16 08:11:27 +000010520/// Attempts to recover from a call where no functions were found.
10521///
10522/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010523static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010524BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010525 UnresolvedLookupExpr *ULE,
10526 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010527 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010528 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010529 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010530 // Do not try to recover if it is already building a recovery call.
10531 // This stops infinite loops for template instantiations like
10532 //
10533 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10534 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10535 //
10536 if (SemaRef.IsBuildingRecoveryCallExpr)
10537 return ExprError();
10538 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010539
10540 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010541 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010542 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010543
John McCall57500772009-12-16 12:17:52 +000010544 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010545 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010546 if (ULE->hasExplicitTemplateArgs()) {
10547 ULE->copyTemplateArgumentsInto(TABuffer);
10548 ExplicitTemplateArgs = &TABuffer;
10549 }
10550
John McCalld681c392009-12-16 08:11:27 +000010551 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10552 Sema::LookupOrdinaryName);
Kaelyn Uhrain53e72192013-07-08 23:13:39 +000010553 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010554 ExplicitTemplateArgs != nullptr,
Kaelyn Takatafb271f02014-04-04 22:16:30 +000010555 dyn_cast<MemberExpr>(Fn));
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010556 NoTypoCorrectionCCC RejectAll;
10557 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10558 (CorrectionCandidateCallback*)&Validator :
10559 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +000010560 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010561 OverloadCandidateSet::CSK_Normal,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010562 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010563 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010564 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010565 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010566 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010567
John McCall57500772009-12-16 12:17:52 +000010568 assert(!R.empty() && "lookup results empty despite recovery");
10569
10570 // Build an implicit member call if appropriate. Just drop the
10571 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010572 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010573 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010574 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10575 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010576 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010577 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010578 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010579 else
10580 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10581
10582 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010583 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010584
10585 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010586 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010587 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010588 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010589 MultiExprArg(Args.data(), Args.size()),
10590 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010591}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010592
Sam Panzer0f384432012-08-21 00:52:01 +000010593/// \brief Constructs and populates an OverloadedCandidateSet from
10594/// the given function.
10595/// \returns true when an the ExprResult output parameter has been set.
10596bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10597 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010598 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010599 SourceLocation RParenLoc,
10600 OverloadCandidateSet *CandidateSet,
10601 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010602#ifndef NDEBUG
10603 if (ULE->requiresADL()) {
10604 // To do ADL, we must have found an unqualified name.
10605 assert(!ULE->getQualifier() && "qualified name with ADL");
10606
10607 // We don't perform ADL for implicit declarations of builtins.
10608 // Verify that this was correctly set up.
10609 FunctionDecl *F;
10610 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10611 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10612 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010613 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010614
John McCall57500772009-12-16 12:17:52 +000010615 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010616 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010617 }
John McCall57500772009-12-16 12:17:52 +000010618#endif
10619
John McCall4124c492011-10-17 18:40:02 +000010620 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010621 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010622 *Result = ExprError();
10623 return true;
10624 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010625
John McCall57500772009-12-16 12:17:52 +000010626 // Add the functions denoted by the callee to the set of candidate
10627 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010628 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010629
10630 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010631 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10632 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010633 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010634 // In Microsoft mode, if we are inside a template class member function then
10635 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010636 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010637 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010638 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010639 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010640 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010641 Context.DependentTy, VK_RValue,
10642 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010643 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010644 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010645 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010646 }
Sam Panzer0f384432012-08-21 00:52:01 +000010647 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010648 }
John McCalld681c392009-12-16 08:11:27 +000010649
John McCall4124c492011-10-17 18:40:02 +000010650 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010651 return false;
10652}
John McCall4124c492011-10-17 18:40:02 +000010653
Sam Panzer0f384432012-08-21 00:52:01 +000010654/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10655/// the completed call expression. If overload resolution fails, emits
10656/// diagnostics and returns ExprError()
10657static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10658 UnresolvedLookupExpr *ULE,
10659 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010660 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010661 SourceLocation RParenLoc,
10662 Expr *ExecConfig,
10663 OverloadCandidateSet *CandidateSet,
10664 OverloadCandidateSet::iterator *Best,
10665 OverloadingResult OverloadResult,
10666 bool AllowTypoCorrection) {
10667 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010668 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010669 RParenLoc, /*EmptyLookup=*/true,
10670 AllowTypoCorrection);
10671
10672 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010673 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010674 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010675 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010676 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10677 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010678 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010679 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10680 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010681 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010682
Richard Smith998a5912011-06-05 22:42:48 +000010683 case OR_No_Viable_Function: {
10684 // Try to recover by looking for viable functions which the user might
10685 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010686 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010687 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010688 /*EmptyLookup=*/false,
10689 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010690 if (!Recovery.isInvalid())
10691 return Recovery;
10692
Sam Panzer0f384432012-08-21 00:52:01 +000010693 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010694 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010695 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010696 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010697 break;
Richard Smith998a5912011-06-05 22:42:48 +000010698 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010699
10700 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010701 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010702 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010703 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010704 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010705
Sam Panzer0f384432012-08-21 00:52:01 +000010706 case OR_Deleted: {
10707 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10708 << (*Best)->Function->isDeleted()
10709 << ULE->getName()
10710 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10711 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010712 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010713
Sam Panzer0f384432012-08-21 00:52:01 +000010714 // We emitted an error for the unvailable/deleted function call but keep
10715 // the call in the AST.
10716 FunctionDecl *FDecl = (*Best)->Function;
10717 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010718 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10719 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010720 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010721 }
10722
Douglas Gregorb412e172010-07-25 18:17:45 +000010723 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010724 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010725}
10726
Sam Panzer0f384432012-08-21 00:52:01 +000010727/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10728/// (which eventually refers to the declaration Func) and the call
10729/// arguments Args/NumArgs, attempt to resolve the function call down
10730/// to a specific function. If overload resolution succeeds, returns
10731/// the call expression produced by overload resolution.
10732/// Otherwise, emits diagnostics and returns ExprError.
10733ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10734 UnresolvedLookupExpr *ULE,
10735 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010736 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010737 SourceLocation RParenLoc,
10738 Expr *ExecConfig,
10739 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010740 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10741 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010742 ExprResult result;
10743
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010744 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10745 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010746 return result;
10747
10748 OverloadCandidateSet::iterator Best;
10749 OverloadingResult OverloadResult =
10750 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10751
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010752 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010753 RParenLoc, ExecConfig, &CandidateSet,
10754 &Best, OverloadResult,
10755 AllowTypoCorrection);
10756}
10757
John McCall4c4c1df2010-01-26 03:27:55 +000010758static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010759 return Functions.size() > 1 ||
10760 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10761}
10762
Douglas Gregor084d8552009-03-13 23:49:33 +000010763/// \brief Create a unary operation that may resolve to an overloaded
10764/// operator.
10765///
10766/// \param OpLoc The location of the operator itself (e.g., '*').
10767///
10768/// \param OpcIn The UnaryOperator::Opcode that describes this
10769/// operator.
10770///
James Dennett18348b62012-06-22 08:52:37 +000010771/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010772/// considered by overload resolution. The caller needs to build this
10773/// set based on the context using, e.g.,
10774/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10775/// set should not contain any member functions; those will be added
10776/// by CreateOverloadedUnaryOp().
10777///
James Dennett91738ff2012-06-22 10:32:46 +000010778/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010779ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010780Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10781 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010782 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010783 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010784
10785 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10786 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10787 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010788 // TODO: provide better source location info.
10789 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010790
John McCall4124c492011-10-17 18:40:02 +000010791 if (checkPlaceholderForOverload(*this, Input))
10792 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010793
Craig Topperc3ec1492014-05-26 06:22:03 +000010794 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010795 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010796
Douglas Gregor084d8552009-03-13 23:49:33 +000010797 // For post-increment and post-decrement, add the implicit '0' as
10798 // the second argument, so that we know this is a post-increment or
10799 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010800 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010801 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010802 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10803 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010804 NumArgs = 2;
10805 }
10806
Richard Smithe54c3072013-05-05 15:51:06 +000010807 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10808
Douglas Gregor084d8552009-03-13 23:49:33 +000010809 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010810 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010811 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10812 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010813
Craig Topperc3ec1492014-05-26 06:22:03 +000010814 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010815 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010816 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010817 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010818 /*ADL*/ true, IsOverloaded(Fns),
10819 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010820 return new (Context)
10821 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10822 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010823 }
10824
10825 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010826 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010827
10828 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010829 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010830
10831 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010832 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010833
John McCall4c4c1df2010-01-26 03:27:55 +000010834 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010835 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010836 /*ExplicitTemplateArgs*/nullptr,
10837 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010838
Douglas Gregor084d8552009-03-13 23:49:33 +000010839 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010840 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010841
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010842 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10843
Douglas Gregor084d8552009-03-13 23:49:33 +000010844 // Perform overload resolution.
10845 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010846 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010847 case OR_Success: {
10848 // We found a built-in operator or an overloaded operator.
10849 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010850
Douglas Gregor084d8552009-03-13 23:49:33 +000010851 if (FnDecl) {
10852 // We matched an overloaded operator. Build a call to that
10853 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010854
Douglas Gregor084d8552009-03-13 23:49:33 +000010855 // Convert the arguments.
10856 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010857 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010858
John Wiegley01296292011-04-08 18:41:53 +000010859 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010860 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010861 Best->FoundDecl, Method);
10862 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010863 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010864 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010865 } else {
10866 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010867 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010868 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010869 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010870 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010871 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010872 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010873 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010874 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010875 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010876 }
10877
Douglas Gregor084d8552009-03-13 23:49:33 +000010878 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010879 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010880 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010881 if (FnExpr.isInvalid())
10882 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010883
Richard Smithc1564702013-11-15 02:58:23 +000010884 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000010885 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000010886 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10887 ResultTy = ResultTy.getNonLValueExprType(Context);
10888
Eli Friedman030eee42009-11-18 03:58:17 +000010889 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010890 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010891 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010892 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010893
Alp Toker314cc812014-01-25 16:55:45 +000010894 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010895 return ExprError();
10896
John McCallb268a282010-08-23 23:25:46 +000010897 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010898 } else {
10899 // We matched a built-in operator. Convert the arguments, then
10900 // break out so that we will build the appropriate built-in
10901 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010902 ExprResult InputRes =
10903 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10904 Best->Conversions[0], AA_Passing);
10905 if (InputRes.isInvalid())
10906 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010907 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010908 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010909 }
John Wiegley01296292011-04-08 18:41:53 +000010910 }
10911
10912 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010913 // This is an erroneous use of an operator which can be overloaded by
10914 // a non-member function. Check for non-member operators which were
10915 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010916 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010917 // FIXME: Recover by calling the found function.
10918 return ExprError();
10919
John Wiegley01296292011-04-08 18:41:53 +000010920 // No viable function; fall through to handling this as a
10921 // built-in operator, which will produce an error message for us.
10922 break;
10923
10924 case OR_Ambiguous:
10925 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10926 << UnaryOperator::getOpcodeStr(Opc)
10927 << Input->getType()
10928 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010929 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010930 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10931 return ExprError();
10932
10933 case OR_Deleted:
10934 Diag(OpLoc, diag::err_ovl_deleted_oper)
10935 << Best->Function->isDeleted()
10936 << UnaryOperator::getOpcodeStr(Opc)
10937 << getDeletedOrUnavailableSuffix(Best->Function)
10938 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010939 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010940 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010941 return ExprError();
10942 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010943
10944 // Either we found no viable overloaded operator or we matched a
10945 // built-in operator. In either case, fall through to trying to
10946 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010947 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010948}
10949
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010950/// \brief Create a binary operation that may resolve to an overloaded
10951/// operator.
10952///
10953/// \param OpLoc The location of the operator itself (e.g., '+').
10954///
10955/// \param OpcIn The BinaryOperator::Opcode that describes this
10956/// operator.
10957///
James Dennett18348b62012-06-22 08:52:37 +000010958/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010959/// considered by overload resolution. The caller needs to build this
10960/// set based on the context using, e.g.,
10961/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10962/// set should not contain any member functions; those will be added
10963/// by CreateOverloadedBinOp().
10964///
10965/// \param LHS Left-hand argument.
10966/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010967ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010968Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010969 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010970 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010971 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010972 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000010973 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010974
10975 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10976 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10977 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10978
10979 // If either side is type-dependent, create an appropriate dependent
10980 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010981 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010982 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010983 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010984 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010985 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010986 return new (Context) BinaryOperator(
10987 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
10988 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010989
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010990 return new (Context) CompoundAssignOperator(
10991 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
10992 Context.DependentTy, Context.DependentTy, OpLoc,
10993 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000010994 }
John McCall4c4c1df2010-01-26 03:27:55 +000010995
10996 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000010997 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010998 // TODO: provide better source location info in DNLoc component.
10999 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011000 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011001 = UnresolvedLookupExpr::Create(Context, NamingClass,
11002 NestedNameSpecifierLoc(), OpNameInfo,
11003 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011004 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011005 return new (Context)
11006 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11007 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011008 }
11009
John McCall4124c492011-10-17 18:40:02 +000011010 // Always do placeholder-like conversions on the RHS.
11011 if (checkPlaceholderForOverload(*this, Args[1]))
11012 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011013
John McCall526ab472011-10-25 17:37:35 +000011014 // Do placeholder-like conversion on the LHS; note that we should
11015 // not get here with a PseudoObject LHS.
11016 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011017 if (checkPlaceholderForOverload(*this, Args[0]))
11018 return ExprError();
11019
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011020 // If this is the assignment operator, we only perform overload resolution
11021 // if the left-hand side is a class or enumeration type. This is actually
11022 // a hack. The standard requires that we do overload resolution between the
11023 // various built-in candidates, but as DR507 points out, this can lead to
11024 // problems. So we do it this way, which pretty much follows what GCC does.
11025 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011026 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011027 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011028
John McCalle26a8722010-12-04 08:14:53 +000011029 // If this is the .* operator, which is not overloadable, just
11030 // create a built-in binary operator.
11031 if (Opc == BO_PtrMemD)
11032 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11033
Douglas Gregor084d8552009-03-13 23:49:33 +000011034 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011035 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011036
11037 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011038 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011039
11040 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011041 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011042
Richard Smith0daabd72014-09-23 20:31:39 +000011043 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11044 // performed for an assignment operator (nor for operator[] nor operator->,
11045 // which don't get here).
11046 if (Opc != BO_Assign)
11047 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11048 /*ExplicitTemplateArgs*/ nullptr,
11049 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011050
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011051 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011052 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011053
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011054 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11055
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011056 // Perform overload resolution.
11057 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011058 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011059 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011060 // We found a built-in operator or an overloaded operator.
11061 FunctionDecl *FnDecl = Best->Function;
11062
11063 if (FnDecl) {
11064 // We matched an overloaded operator. Build a call to that
11065 // operator.
11066
11067 // Convert the arguments.
11068 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011069 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011070 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011071
Chandler Carruth8e543b32010-12-12 08:17:55 +000011072 ExprResult Arg1 =
11073 PerformCopyInitialization(
11074 InitializedEntity::InitializeParameter(Context,
11075 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011076 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011077 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011078 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011079
John Wiegley01296292011-04-08 18:41:53 +000011080 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011081 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011082 Best->FoundDecl, Method);
11083 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011084 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011085 Args[0] = Arg0.getAs<Expr>();
11086 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011087 } else {
11088 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011089 ExprResult Arg0 = PerformCopyInitialization(
11090 InitializedEntity::InitializeParameter(Context,
11091 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011092 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011093 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011094 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011095
Chandler Carruth8e543b32010-12-12 08:17:55 +000011096 ExprResult Arg1 =
11097 PerformCopyInitialization(
11098 InitializedEntity::InitializeParameter(Context,
11099 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011100 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011101 if (Arg1.isInvalid())
11102 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011103 Args[0] = LHS = Arg0.getAs<Expr>();
11104 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011105 }
11106
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011107 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011108 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011109 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011110 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011111 if (FnExpr.isInvalid())
11112 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011113
Richard Smithc1564702013-11-15 02:58:23 +000011114 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011115 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011116 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11117 ResultTy = ResultTy.getNonLValueExprType(Context);
11118
John McCallb268a282010-08-23 23:25:46 +000011119 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011120 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011121 Args, ResultTy, VK, OpLoc,
11122 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011123
Alp Toker314cc812014-01-25 16:55:45 +000011124 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011125 FnDecl))
11126 return ExprError();
11127
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011128 ArrayRef<const Expr *> ArgsArray(Args, 2);
11129 // Cut off the implicit 'this'.
11130 if (isa<CXXMethodDecl>(FnDecl))
11131 ArgsArray = ArgsArray.slice(1);
11132 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11133 TheCall->getSourceRange(), VariadicDoesNotApply);
11134
John McCallb268a282010-08-23 23:25:46 +000011135 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011136 } else {
11137 // We matched a built-in operator. Convert the arguments, then
11138 // break out so that we will build the appropriate built-in
11139 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011140 ExprResult ArgsRes0 =
11141 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11142 Best->Conversions[0], AA_Passing);
11143 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011144 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011145 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011146
John Wiegley01296292011-04-08 18:41:53 +000011147 ExprResult ArgsRes1 =
11148 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11149 Best->Conversions[1], AA_Passing);
11150 if (ArgsRes1.isInvalid())
11151 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011152 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011153 break;
11154 }
11155 }
11156
Douglas Gregor66950a32009-09-30 21:46:01 +000011157 case OR_No_Viable_Function: {
11158 // C++ [over.match.oper]p9:
11159 // If the operator is the operator , [...] and there are no
11160 // viable functions, then the operator is assumed to be the
11161 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011162 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011163 break;
11164
Chandler Carruth8e543b32010-12-12 08:17:55 +000011165 // For class as left operand for assignment or compound assigment
11166 // operator do not fall through to handling in built-in, but report that
11167 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011168 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011169 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011170 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011171 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11172 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011173 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011174 if (Args[0]->getType()->isIncompleteType()) {
11175 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11176 << Args[0]->getType()
11177 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11178 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011179 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011180 // This is an erroneous use of an operator which can be overloaded by
11181 // a non-member function. Check for non-member operators which were
11182 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011183 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011184 // FIXME: Recover by calling the found function.
11185 return ExprError();
11186
Douglas Gregor66950a32009-09-30 21:46:01 +000011187 // No viable function; try to create a built-in operation, which will
11188 // produce an error. Then, show the non-viable candidates.
11189 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011191 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011192 "C++ binary operator overloading is missing candidates!");
11193 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011194 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011195 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011196 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011197 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011198
11199 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011200 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011201 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011202 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011203 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011204 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011205 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011206 return ExprError();
11207
11208 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011209 if (isImplicitlyDeleted(Best->Function)) {
11210 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11211 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011212 << Context.getRecordType(Method->getParent())
11213 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011214
Richard Smithde1a4872012-12-28 12:23:24 +000011215 // The user probably meant to call this special member. Just
11216 // explain why it's deleted.
11217 NoteDeletedFunction(Method);
11218 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011219 } else {
11220 Diag(OpLoc, diag::err_ovl_deleted_oper)
11221 << Best->Function->isDeleted()
11222 << BinaryOperator::getOpcodeStr(Opc)
11223 << getDeletedOrUnavailableSuffix(Best->Function)
11224 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11225 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011226 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011227 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011228 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011229 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011230
Douglas Gregor66950a32009-09-30 21:46:01 +000011231 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011232 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011233}
11234
John McCalldadc5752010-08-24 06:29:42 +000011235ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011236Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11237 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011238 Expr *Base, Expr *Idx) {
11239 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011240 DeclarationName OpName =
11241 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11242
11243 // If either side is type-dependent, create an appropriate dependent
11244 // expression.
11245 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11246
Craig Topperc3ec1492014-05-26 06:22:03 +000011247 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011248 // CHECKME: no 'operator' keyword?
11249 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11250 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011251 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011252 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011253 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011254 /*ADL*/ true, /*Overloaded*/ false,
11255 UnresolvedSetIterator(),
11256 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011257 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011258
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011259 return new (Context)
11260 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11261 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011262 }
11263
John McCall4124c492011-10-17 18:40:02 +000011264 // Handle placeholders on both operands.
11265 if (checkPlaceholderForOverload(*this, Args[0]))
11266 return ExprError();
11267 if (checkPlaceholderForOverload(*this, Args[1]))
11268 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011269
Sebastian Redladba46e2009-10-29 20:17:01 +000011270 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011271 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011272
11273 // Subscript can only be overloaded as a member function.
11274
11275 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011276 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011277
11278 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011279 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011280
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011281 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11282
Sebastian Redladba46e2009-10-29 20:17:01 +000011283 // Perform overload resolution.
11284 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011285 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011286 case OR_Success: {
11287 // We found a built-in operator or an overloaded operator.
11288 FunctionDecl *FnDecl = Best->Function;
11289
11290 if (FnDecl) {
11291 // We matched an overloaded operator. Build a call to that
11292 // operator.
11293
John McCalla0296f72010-03-19 07:35:19 +000011294 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011295
Sebastian Redladba46e2009-10-29 20:17:01 +000011296 // Convert the arguments.
11297 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011298 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011299 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011300 Best->FoundDecl, Method);
11301 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011302 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011303 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011304
Anders Carlssona68e51e2010-01-29 18:37:50 +000011305 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011306 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011307 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011308 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011309 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011310 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011311 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011312 if (InputInit.isInvalid())
11313 return ExprError();
11314
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011315 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011316
Sebastian Redladba46e2009-10-29 20:17:01 +000011317 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011318 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11319 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011320 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011321 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011322 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011323 OpLocInfo.getLoc(),
11324 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011325 if (FnExpr.isInvalid())
11326 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011327
Richard Smithc1564702013-11-15 02:58:23 +000011328 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011329 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011330 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11331 ResultTy = ResultTy.getNonLValueExprType(Context);
11332
John McCallb268a282010-08-23 23:25:46 +000011333 CXXOperatorCallExpr *TheCall =
11334 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011335 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011336 ResultTy, VK, RLoc,
11337 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011338
Alp Toker314cc812014-01-25 16:55:45 +000011339 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011340 return ExprError();
11341
John McCallb268a282010-08-23 23:25:46 +000011342 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011343 } else {
11344 // We matched a built-in operator. Convert the arguments, then
11345 // break out so that we will build the appropriate built-in
11346 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011347 ExprResult ArgsRes0 =
11348 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11349 Best->Conversions[0], AA_Passing);
11350 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011351 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011352 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011353
11354 ExprResult ArgsRes1 =
11355 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11356 Best->Conversions[1], AA_Passing);
11357 if (ArgsRes1.isInvalid())
11358 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011359 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011360
11361 break;
11362 }
11363 }
11364
11365 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011366 if (CandidateSet.empty())
11367 Diag(LLoc, diag::err_ovl_no_oper)
11368 << Args[0]->getType() << /*subscript*/ 0
11369 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11370 else
11371 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11372 << Args[0]->getType()
11373 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011374 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011375 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011376 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011377 }
11378
11379 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011380 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011381 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011382 << Args[0]->getType() << Args[1]->getType()
11383 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011384 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011385 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011386 return ExprError();
11387
11388 case OR_Deleted:
11389 Diag(LLoc, diag::err_ovl_deleted_oper)
11390 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011391 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011392 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011393 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011394 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011395 return ExprError();
11396 }
11397
11398 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011399 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011400}
11401
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011402/// BuildCallToMemberFunction - Build a call to a member
11403/// function. MemExpr is the expression that refers to the member
11404/// function (and includes the object parameter), Args/NumArgs are the
11405/// arguments to the function call (not including the object
11406/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011407/// expression refers to a non-static member function or an overloaded
11408/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011409ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011410Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011411 SourceLocation LParenLoc,
11412 MultiExprArg Args,
11413 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011414 assert(MemExprE->getType() == Context.BoundMemberTy ||
11415 MemExprE->getType() == Context.OverloadTy);
11416
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011417 // Dig out the member expression. This holds both the object
11418 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011419 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011420
John McCall0009fcc2011-04-26 20:42:42 +000011421 // Determine whether this is a call to a pointer-to-member function.
11422 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11423 assert(op->getType() == Context.BoundMemberTy);
11424 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11425
11426 QualType fnType =
11427 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11428
11429 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11430 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011431 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011432
11433 // Check that the object type isn't more qualified than the
11434 // member function we're calling.
11435 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11436
11437 QualType objectType = op->getLHS()->getType();
11438 if (op->getOpcode() == BO_PtrMemI)
11439 objectType = objectType->castAs<PointerType>()->getPointeeType();
11440 Qualifiers objectQuals = objectType.getQualifiers();
11441
11442 Qualifiers difference = objectQuals - funcQuals;
11443 difference.removeObjCGCAttr();
11444 difference.removeAddressSpace();
11445 if (difference) {
11446 std::string qualsString = difference.getAsString();
11447 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11448 << fnType.getUnqualifiedType()
11449 << qualsString
11450 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11451 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011452
David Majnemerb3e56542014-08-07 22:56:13 +000011453 if (resultType->isMemberPointerType())
11454 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11455 RequireCompleteType(LParenLoc, resultType, 0);
11456
John McCall0009fcc2011-04-26 20:42:42 +000011457 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011458 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011459 resultType, valueKind, RParenLoc);
11460
Alp Toker314cc812014-01-25 16:55:45 +000011461 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011462 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011463 return ExprError();
11464
Craig Topperc3ec1492014-05-26 06:22:03 +000011465 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011466 return ExprError();
11467
Richard Trieu9be9c682013-06-22 02:30:38 +000011468 if (CheckOtherCall(call, proto))
11469 return ExprError();
11470
John McCall0009fcc2011-04-26 20:42:42 +000011471 return MaybeBindToTemporary(call);
11472 }
11473
John McCall4124c492011-10-17 18:40:02 +000011474 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011475 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011476 return ExprError();
11477
John McCall10eae182009-11-30 22:42:35 +000011478 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011479 CXXMethodDecl *Method = nullptr;
11480 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11481 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011482 if (isa<MemberExpr>(NakedMemExpr)) {
11483 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011484 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011485 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011486 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011487 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011488 } else {
11489 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011490 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011491
John McCall6e9f8f62009-12-03 04:06:58 +000011492 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011493 Expr::Classification ObjectClassification
11494 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11495 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011496
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011497 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011498 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11499 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011500
John McCall2d74de92009-12-01 22:10:20 +000011501 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011502 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011503 if (UnresExpr->hasExplicitTemplateArgs()) {
11504 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11505 TemplateArgs = &TemplateArgsBuffer;
11506 }
11507
John McCall10eae182009-11-30 22:42:35 +000011508 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11509 E = UnresExpr->decls_end(); I != E; ++I) {
11510
John McCall6e9f8f62009-12-03 04:06:58 +000011511 NamedDecl *Func = *I;
11512 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11513 if (isa<UsingShadowDecl>(Func))
11514 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11515
Douglas Gregor02824322011-01-26 19:30:28 +000011516
Francois Pichet64225792011-01-18 05:04:39 +000011517 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011518 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011519 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011520 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011521 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011522 // If explicit template arguments were provided, we can't call a
11523 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011524 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011525 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011526
John McCalla0296f72010-03-19 07:35:19 +000011527 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011528 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011529 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011530 } else {
John McCall10eae182009-11-30 22:42:35 +000011531 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011532 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011533 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011534 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011535 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011536 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011537 }
Mike Stump11289f42009-09-09 15:08:12 +000011538
John McCall10eae182009-11-30 22:42:35 +000011539 DeclarationName DeclName = UnresExpr->getMemberName();
11540
John McCall4124c492011-10-17 18:40:02 +000011541 UnbridgedCasts.restore();
11542
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011543 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011544 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011545 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011546 case OR_Success:
11547 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011548 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011549 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011550 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11551 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011552 // If FoundDecl is different from Method (such as if one is a template
11553 // and the other a specialization), make sure DiagnoseUseOfDecl is
11554 // called on both.
11555 // FIXME: This would be more comprehensively addressed by modifying
11556 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11557 // being used.
11558 if (Method != FoundDecl.getDecl() &&
11559 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11560 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011561 break;
11562
11563 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011564 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011565 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011566 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011567 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011568 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011569 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011570
11571 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011572 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011573 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011574 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011575 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011576 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011577
11578 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011579 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011580 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011581 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011582 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011583 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011584 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011585 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011586 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011587 }
11588
John McCall16df1e52010-03-30 21:47:33 +000011589 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011590
John McCall2d74de92009-12-01 22:10:20 +000011591 // If overload resolution picked a static member, build a
11592 // non-member call based on that function.
11593 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011594 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11595 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011596 }
11597
John McCall10eae182009-11-30 22:42:35 +000011598 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011599 }
11600
Alp Toker314cc812014-01-25 16:55:45 +000011601 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011602 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11603 ResultType = ResultType.getNonLValueExprType(Context);
11604
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011605 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011606 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011607 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011608 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011609
Eli Bendersky291a57e2014-09-25 23:59:08 +000011610 // (CUDA B.1): Check for invalid calls between targets.
11611 if (getLangOpts().CUDA) {
11612 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11613 if (CheckCUDATarget(Caller, Method)) {
11614 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11615 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11616 << IdentifyCUDATarget(Caller);
11617 return ExprError();
11618 }
11619 }
11620 }
11621
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011622 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011623 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011624 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011625 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011626
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011627 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011628 // We only need to do this if there was actually an overload; otherwise
11629 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011630 if (!Method->isStatic()) {
11631 ExprResult ObjectArg =
11632 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11633 FoundDecl, Method);
11634 if (ObjectArg.isInvalid())
11635 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011636 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011637 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011638
11639 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011640 const FunctionProtoType *Proto =
11641 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011642 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011643 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011644 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011645
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011646 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011647
Richard Smith55ce3522012-06-25 20:30:08 +000011648 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011649 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011650
Anders Carlsson47061ee2011-05-06 14:25:31 +000011651 if ((isa<CXXConstructorDecl>(CurContext) ||
11652 isa<CXXDestructorDecl>(CurContext)) &&
11653 TheCall->getMethodDecl()->isPure()) {
11654 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11655
Chandler Carruth59259262011-06-27 08:31:58 +000011656 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011657 Diag(MemExpr->getLocStart(),
11658 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11659 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11660 << MD->getParent()->getDeclName();
11661
11662 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011663 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011664 }
John McCallb268a282010-08-23 23:25:46 +000011665 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011666}
11667
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011668/// BuildCallToObjectOfClassType - Build a call to an object of class
11669/// type (C++ [over.call.object]), which can end up invoking an
11670/// overloaded function call operator (@c operator()) or performing a
11671/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011672ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011673Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011674 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011675 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011676 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011677 if (checkPlaceholderForOverload(*this, Obj))
11678 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011679 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011680
11681 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011682 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011683 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011684
John Wiegley01296292011-04-08 18:41:53 +000011685 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11686 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011687
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011688 // C++ [over.call.object]p1:
11689 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011690 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011691 // candidate functions includes at least the function call
11692 // operators of T. The function call operators of T are obtained by
11693 // ordinary lookup of the name operator() in the context of
11694 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011695 OverloadCandidateSet CandidateSet(LParenLoc,
11696 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011697 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011698
John Wiegley01296292011-04-08 18:41:53 +000011699 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011700 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011701 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011702
John McCall27b18f82009-11-17 02:14:36 +000011703 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11704 LookupQualifiedName(R, Record->getDecl());
11705 R.suppressDiagnostics();
11706
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011707 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011708 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011709 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011710 Object.get()->Classify(Context),
11711 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011712 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011714
Douglas Gregorab7897a2008-11-19 22:57:39 +000011715 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011716 // In addition, for each (non-explicit in C++0x) conversion function
11717 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011718 //
11719 // operator conversion-type-id () cv-qualifier;
11720 //
11721 // where cv-qualifier is the same cv-qualification as, or a
11722 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011723 // denotes the type "pointer to function of (P1,...,Pn) returning
11724 // R", or the type "reference to pointer to function of
11725 // (P1,...,Pn) returning R", or the type "reference to function
11726 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011727 // is also considered as a candidate function. Similarly,
11728 // surrogate call functions are added to the set of candidate
11729 // functions for each conversion function declared in an
11730 // accessible base class provided the function is not hidden
11731 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011732 std::pair<CXXRecordDecl::conversion_iterator,
11733 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011734 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011735 for (CXXRecordDecl::conversion_iterator
11736 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011737 NamedDecl *D = *I;
11738 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11739 if (isa<UsingShadowDecl>(D))
11740 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011741
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011742 // Skip over templated conversion functions; they aren't
11743 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011744 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011745 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011746
John McCall6e9f8f62009-12-03 04:06:58 +000011747 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011748 if (!Conv->isExplicit()) {
11749 // Strip the reference type (if any) and then the pointer type (if
11750 // any) to get down to what might be a function type.
11751 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11752 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11753 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011754
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011755 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11756 {
11757 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011758 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011759 }
11760 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011761 }
Mike Stump11289f42009-09-09 15:08:12 +000011762
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011763 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11764
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011765 // Perform overload resolution.
11766 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011767 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011768 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011769 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011770 // Overload resolution succeeded; we'll build the appropriate call
11771 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011772 break;
11773
11774 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011775 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011776 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011777 << Object.get()->getType() << /*call*/ 1
11778 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011779 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011780 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011781 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011782 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011783 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011784 break;
11785
11786 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011787 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011788 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011789 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011790 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011791 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011792
11793 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011794 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011795 diag::err_ovl_deleted_object_call)
11796 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011797 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011798 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011799 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011800 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011801 break;
Mike Stump11289f42009-09-09 15:08:12 +000011802 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011803
Douglas Gregorb412e172010-07-25 18:17:45 +000011804 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011805 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011806
John McCall4124c492011-10-17 18:40:02 +000011807 UnbridgedCasts.restore();
11808
Craig Topperc3ec1492014-05-26 06:22:03 +000011809 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011810 // Since there is no function declaration, this is one of the
11811 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011812 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011813 = cast<CXXConversionDecl>(
11814 Best->Conversions[0].UserDefined.ConversionFunction);
11815
Craig Topperc3ec1492014-05-26 06:22:03 +000011816 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11817 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011818 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11819 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011820 assert(Conv == Best->FoundDecl.getDecl() &&
11821 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011822 // We selected one of the surrogate functions that converts the
11823 // object parameter to a function pointer. Perform the conversion
11824 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011825
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011826 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011827 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011828 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11829 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011830 if (Call.isInvalid())
11831 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011832 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011833 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11834 CK_UserDefinedConversion, Call.get(),
11835 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011836
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011837 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011838 }
11839
Craig Topperc3ec1492014-05-26 06:22:03 +000011840 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011841
Douglas Gregorab7897a2008-11-19 22:57:39 +000011842 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11843 // that calls this method, using Object for the implicit object
11844 // parameter and passing along the remaining arguments.
11845 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011846
11847 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011848 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011849 return ExprError();
11850
Chandler Carruth8e543b32010-12-12 08:17:55 +000011851 const FunctionProtoType *Proto =
11852 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011853
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011854 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011855
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011856 DeclarationNameInfo OpLocInfo(
11857 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11858 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011859 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011860 HadMultipleCandidates,
11861 OpLocInfo.getLoc(),
11862 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011863 if (NewFn.isInvalid())
11864 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011865
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011866 // Build the full argument list for the method call (the implicit object
11867 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000011868 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011869 MethodArgs[0] = Object.get();
11870 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11871
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011872 // Once we've built TheCall, all of the expressions are properly
11873 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000011874 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011875 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11876 ResultTy = ResultTy.getNonLValueExprType(Context);
11877
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011878 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011879 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011880 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11881 ResultTy, VK, RParenLoc, false);
11882 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011883
Alp Toker314cc812014-01-25 16:55:45 +000011884 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011885 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011886
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011887 // We may have default arguments. If so, we need to allocate more
11888 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011889 if (Args.size() < NumParams)
11890 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011891
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011892 bool IsError = false;
11893
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011894 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011895 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011896 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011897 Best->FoundDecl, Method);
11898 if (ObjRes.isInvalid())
11899 IsError = true;
11900 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011901 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011902 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011903
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011904 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011905 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011906 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011907 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011908 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011909
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011910 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011911
John McCalldadc5752010-08-24 06:29:42 +000011912 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011913 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011914 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011915 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011916 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011917
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011918 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011919 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011920 } else {
John McCalldadc5752010-08-24 06:29:42 +000011921 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011922 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11923 if (DefArg.isInvalid()) {
11924 IsError = true;
11925 break;
11926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011927
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011928 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011929 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011930
11931 TheCall->setArg(i + 1, Arg);
11932 }
11933
11934 // If this is a variadic call, handle args passed through "...".
11935 if (Proto->isVariadic()) {
11936 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011937 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011938 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
11939 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000011940 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011941 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011942 }
11943 }
11944
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011945 if (IsError) return true;
11946
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011947 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011948
Richard Smith55ce3522012-06-25 20:30:08 +000011949 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011950 return true;
11951
John McCalle172be52010-08-24 06:09:16 +000011952 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011953}
11954
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011955/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011956/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011957/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011958ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011959Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11960 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011961 assert(Base->getType()->isRecordType() &&
11962 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011963
John McCall4124c492011-10-17 18:40:02 +000011964 if (checkPlaceholderForOverload(*this, Base))
11965 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011966
John McCallbc077cf2010-02-08 23:07:23 +000011967 SourceLocation Loc = Base->getExprLoc();
11968
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011969 // C++ [over.ref]p1:
11970 //
11971 // [...] An expression x->m is interpreted as (x.operator->())->m
11972 // for a class object x of type T if T::operator->() exists and if
11973 // the operator is selected as the best match function by the
11974 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011975 DeclarationName OpName =
11976 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000011977 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011978 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011979
John McCallbc077cf2010-02-08 23:07:23 +000011980 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011981 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011982 return ExprError();
11983
John McCall27b18f82009-11-17 02:14:36 +000011984 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11985 LookupQualifiedName(R, BaseRecord->getDecl());
11986 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011987
11988 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011989 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011990 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011991 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011992 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011993
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011994 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11995
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011996 // Perform overload resolution.
11997 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011998 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011999 case OR_Success:
12000 // Overload resolution succeeded; we'll build the call below.
12001 break;
12002
12003 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012004 if (CandidateSet.empty()) {
12005 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012006 if (NoArrowOperatorFound) {
12007 // Report this specific error to the caller instead of emitting a
12008 // diagnostic, as requested.
12009 *NoArrowOperatorFound = true;
12010 return ExprError();
12011 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012012 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12013 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012014 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012015 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012016 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012017 }
12018 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012019 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012020 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012021 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012022 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012023
12024 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012025 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12026 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012027 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012028 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012029
12030 case OR_Deleted:
12031 Diag(OpLoc, diag::err_ovl_deleted_oper)
12032 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012033 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012034 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012035 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012036 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012037 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012038 }
12039
Craig Topperc3ec1492014-05-26 06:22:03 +000012040 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012041
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012042 // Convert the object parameter.
12043 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012044 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012045 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012046 Best->FoundDecl, Method);
12047 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012048 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012049 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012050
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012051 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012052 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012053 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012054 if (FnExpr.isInvalid())
12055 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012056
Alp Toker314cc812014-01-25 16:55:45 +000012057 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012058 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12059 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012060 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012061 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012062 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012063
Alp Toker314cc812014-01-25 16:55:45 +000012064 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012065 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012066
12067 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012068}
12069
Richard Smithbcc22fc2012-03-09 08:00:36 +000012070/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12071/// a literal operator described by the provided lookup results.
12072ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12073 DeclarationNameInfo &SuffixInfo,
12074 ArrayRef<Expr*> Args,
12075 SourceLocation LitEndLoc,
12076 TemplateArgumentListInfo *TemplateArgs) {
12077 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012078
Richard Smith100b24a2014-04-17 01:52:14 +000012079 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12080 OverloadCandidateSet::CSK_Normal);
Richard Smithbcc22fc2012-03-09 08:00:36 +000012081 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
12082 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000012083
Richard Smithbcc22fc2012-03-09 08:00:36 +000012084 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12085
Richard Smithbcc22fc2012-03-09 08:00:36 +000012086 // Perform overload resolution. This will usually be trivial, but might need
12087 // to perform substitutions for a literal operator template.
12088 OverloadCandidateSet::iterator Best;
12089 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12090 case OR_Success:
12091 case OR_Deleted:
12092 break;
12093
12094 case OR_No_Viable_Function:
12095 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12096 << R.getLookupName();
12097 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12098 return ExprError();
12099
12100 case OR_Ambiguous:
12101 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12102 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12103 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012104 }
12105
Richard Smithbcc22fc2012-03-09 08:00:36 +000012106 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012107 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12108 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012109 SuffixInfo.getLoc(),
12110 SuffixInfo.getInfo());
12111 if (Fn.isInvalid())
12112 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012113
12114 // Check the argument types. This should almost always be a no-op, except
12115 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012116 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012117 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012118 ExprResult InputInit = PerformCopyInitialization(
12119 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12120 SourceLocation(), Args[ArgIdx]);
12121 if (InputInit.isInvalid())
12122 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012123 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012124 }
12125
Alp Toker314cc812014-01-25 16:55:45 +000012126 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012127 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12128 ResultTy = ResultTy.getNonLValueExprType(Context);
12129
Richard Smithc67fdd42012-03-07 08:35:16 +000012130 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012131 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012132 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012133 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12134
Alp Toker314cc812014-01-25 16:55:45 +000012135 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012136 return ExprError();
12137
Craig Topperc3ec1492014-05-26 06:22:03 +000012138 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012139 return ExprError();
12140
12141 return MaybeBindToTemporary(UDL);
12142}
12143
Sam Panzer0f384432012-08-21 00:52:01 +000012144/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12145/// given LookupResult is non-empty, it is assumed to describe a member which
12146/// will be invoked. Otherwise, the function will be found via argument
12147/// dependent lookup.
12148/// CallExpr is set to a valid expression and FRS_Success returned on success,
12149/// otherwise CallExpr is set to ExprError() and some non-success value
12150/// is returned.
12151Sema::ForRangeStatus
12152Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12153 SourceLocation RangeLoc, VarDecl *Decl,
12154 BeginEndFunction BEF,
12155 const DeclarationNameInfo &NameInfo,
12156 LookupResult &MemberLookup,
12157 OverloadCandidateSet *CandidateSet,
12158 Expr *Range, ExprResult *CallExpr) {
12159 CandidateSet->clear();
12160 if (!MemberLookup.empty()) {
12161 ExprResult MemberRef =
12162 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12163 /*IsPtr=*/false, CXXScopeSpec(),
12164 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012165 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012166 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +000012167 /*TemplateArgs=*/nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012168 if (MemberRef.isInvalid()) {
12169 *CallExpr = ExprError();
12170 Diag(Range->getLocStart(), diag::note_in_for_range)
12171 << RangeLoc << BEF << Range->getType();
12172 return FRS_DiagnosticIssued;
12173 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012174 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012175 if (CallExpr->isInvalid()) {
12176 *CallExpr = ExprError();
12177 Diag(Range->getLocStart(), diag::note_in_for_range)
12178 << RangeLoc << BEF << Range->getType();
12179 return FRS_DiagnosticIssued;
12180 }
12181 } else {
12182 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012183 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012184 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012185 NestedNameSpecifierLoc(), NameInfo,
12186 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012187 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012188
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012189 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012190 CandidateSet, CallExpr);
12191 if (CandidateSet->empty() || CandidateSetError) {
12192 *CallExpr = ExprError();
12193 return FRS_NoViableFunction;
12194 }
12195 OverloadCandidateSet::iterator Best;
12196 OverloadingResult OverloadResult =
12197 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12198
12199 if (OverloadResult == OR_No_Viable_Function) {
12200 *CallExpr = ExprError();
12201 return FRS_NoViableFunction;
12202 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012203 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012204 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012205 OverloadResult,
12206 /*AllowTypoCorrection=*/false);
12207 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12208 *CallExpr = ExprError();
12209 Diag(Range->getLocStart(), diag::note_in_for_range)
12210 << RangeLoc << BEF << Range->getType();
12211 return FRS_DiagnosticIssued;
12212 }
12213 }
12214 return FRS_Success;
12215}
12216
12217
Douglas Gregorcd695e52008-11-10 20:40:00 +000012218/// FixOverloadedFunctionReference - E is an expression that refers to
12219/// a C++ overloaded function (possibly with some parentheses and
12220/// perhaps a '&' around it). We have resolved the overloaded function
12221/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012222/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012223Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012224 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012225 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012226 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12227 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012228 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012229 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012230
Douglas Gregor51c538b2009-11-20 19:42:02 +000012231 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012232 }
12233
Douglas Gregor51c538b2009-11-20 19:42:02 +000012234 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012235 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12236 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012237 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012238 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012239 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012240 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012241 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012242 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012243
12244 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012245 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012246 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012247 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012248 }
12249
Douglas Gregor51c538b2009-11-20 19:42:02 +000012250 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012251 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012252 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012253 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12254 if (Method->isStatic()) {
12255 // Do nothing: static member functions aren't any different
12256 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012257 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012258 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012259 // UnresolvedLookupExpr holding an overloaded member function
12260 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012261 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12262 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012263 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012264 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012265
John McCalld14a8642009-11-21 08:51:07 +000012266 assert(isa<DeclRefExpr>(SubExpr)
12267 && "fixed to something other than a decl ref");
12268 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12269 && "fixed to a member ref with no nested name qualifier");
12270
12271 // We have taken the address of a pointer to member
12272 // function. Perform the computation here so that we get the
12273 // appropriate pointer to member type.
12274 QualType ClassType
12275 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12276 QualType MemPtrType
12277 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12278
John McCall7decc9e2010-11-18 06:31:45 +000012279 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12280 VK_RValue, OK_Ordinary,
12281 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012282 }
12283 }
John McCall16df1e52010-03-30 21:47:33 +000012284 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12285 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012286 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012287 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012288
John McCalle3027922010-08-25 11:45:40 +000012289 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012290 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012291 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012292 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012293 }
John McCalld14a8642009-11-21 08:51:07 +000012294
12295 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012296 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012297 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012298 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012299 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12300 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012301 }
12302
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012303 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12304 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012305 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012306 Fn,
John McCall113bee02012-03-10 09:33:50 +000012307 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012308 ULE->getNameLoc(),
12309 Fn->getType(),
12310 VK_LValue,
12311 Found.getDecl(),
12312 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012313 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012314 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12315 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012316 }
12317
John McCall10eae182009-11-30 22:42:35 +000012318 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012319 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012320 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012321 if (MemExpr->hasExplicitTemplateArgs()) {
12322 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12323 TemplateArgs = &TemplateArgsBuffer;
12324 }
John McCall6b51f282009-11-23 01:53:49 +000012325
John McCall2d74de92009-12-01 22:10:20 +000012326 Expr *Base;
12327
John McCall7decc9e2010-11-18 06:31:45 +000012328 // If we're filling in a static method where we used to have an
12329 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012330 if (MemExpr->isImplicitAccess()) {
12331 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012332 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12333 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012334 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012335 Fn,
John McCall113bee02012-03-10 09:33:50 +000012336 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012337 MemExpr->getMemberLoc(),
12338 Fn->getType(),
12339 VK_LValue,
12340 Found.getDecl(),
12341 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012342 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012343 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12344 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012345 } else {
12346 SourceLocation Loc = MemExpr->getMemberLoc();
12347 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012348 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012349 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012350 Base = new (Context) CXXThisExpr(Loc,
12351 MemExpr->getBaseType(),
12352 /*isImplicit=*/true);
12353 }
John McCall2d74de92009-12-01 22:10:20 +000012354 } else
John McCallc3007a22010-10-26 07:05:15 +000012355 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012356
John McCall4adb38c2011-04-27 00:36:17 +000012357 ExprValueKind valueKind;
12358 QualType type;
12359 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12360 valueKind = VK_LValue;
12361 type = Fn->getType();
12362 } else {
12363 valueKind = VK_RValue;
12364 type = Context.BoundMemberTy;
12365 }
12366
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012367 MemberExpr *ME = MemberExpr::Create(Context, Base,
12368 MemExpr->isArrow(),
12369 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012370 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012371 Fn,
12372 Found,
12373 MemExpr->getMemberNameInfo(),
12374 TemplateArgs,
12375 type, valueKind, OK_Ordinary);
12376 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012377 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012378 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012380
John McCallc3007a22010-10-26 07:05:15 +000012381 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012382}
12383
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012384ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012385 DeclAccessPair Found,
12386 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012387 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012388}
12389
Douglas Gregor5251f1b2008-10-21 16:13:35 +000012390} // end namespace clang