blob: e5db60b2002b12fa59920924e68bb566b9b045e6 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley429bb272011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000052}
53
John McCall120d63c2010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor60d62c22008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202}
203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000242bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregorf9af5242011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000261/// Skip any implicit casts which could be either part of a narrowing conversion
262/// or after one in an implicit conversion.
263static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265 switch (ICE->getCastKind()) {
266 case CK_NoOp:
267 case CK_IntegralCast:
268 case CK_IntegralToBoolean:
269 case CK_IntegralToFloating:
270 case CK_FloatingToIntegral:
271 case CK_FloatingToBoolean:
272 case CK_FloatingCast:
273 Converted = ICE->getSubExpr();
274 continue;
275
276 default:
277 return Converted;
278 }
279 }
280
281 return Converted;
282}
283
284/// Check if this standard conversion sequence represents a narrowing
285/// conversion, according to C++11 [dcl.init.list]p7.
286///
287/// \param Ctx The AST context.
288/// \param Converted The result of applying this standard conversion sequence.
289/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
290/// value of the expression prior to the narrowing conversion.
291NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue) const {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000295 assert(Ctx.getLangOptions().CPlusPlus && "narrowing check outside C++");
296
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
301 switch (Second) {
302 // -- from a floating-point type to an integer type, or
303 //
304 // -- from an integer type or unscoped enumeration type to a floating-point
305 // type, except where the source is a constant expression and the actual
306 // value after conversion will fit into the target type and will produce
307 // the original value when converted back to the original type, or
308 case ICK_Floating_Integral:
309 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
310 return NK_Type_Narrowing;
311 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
312 llvm::APSInt IntConstantValue;
313 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
314 if (Initializer &&
315 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
316 // Convert the integer to the floating type.
317 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
318 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
319 llvm::APFloat::rmNearestTiesToEven);
320 // And back.
321 llvm::APSInt ConvertedValue = IntConstantValue;
322 bool ignored;
323 Result.convertToInteger(ConvertedValue,
324 llvm::APFloat::rmTowardZero, &ignored);
325 // If the resulting value is different, this was a narrowing conversion.
326 if (IntConstantValue != ConvertedValue) {
327 ConstantValue = APValue(IntConstantValue);
328 return NK_Constant_Narrowing;
329 }
330 } else {
331 // Variables are always narrowings.
332 return NK_Variable_Narrowing;
333 }
334 }
335 return NK_Not_Narrowing;
336
337 // -- from long double to double or float, or from double to float, except
338 // where the source is a constant expression and the actual value after
339 // conversion is within the range of values that can be represented (even
340 // if it cannot be represented exactly), or
341 case ICK_Floating_Conversion:
342 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
343 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
344 // FromType is larger than ToType.
345 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
346 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
347 // Constant!
348 assert(ConstantValue.isFloat());
349 llvm::APFloat FloatVal = ConstantValue.getFloat();
350 // Convert the source value into the target type.
351 bool ignored;
352 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
353 Ctx.getFloatTypeSemantics(ToType),
354 llvm::APFloat::rmNearestTiesToEven, &ignored);
355 // If there was no overflow, the source value is within the range of
356 // values that can be represented.
357 if (ConvertStatus & llvm::APFloat::opOverflow)
358 return NK_Constant_Narrowing;
359 } else {
360 return NK_Variable_Narrowing;
361 }
362 }
363 return NK_Not_Narrowing;
364
365 // -- from an integer type or unscoped enumeration type to an integer type
366 // that cannot represent all the values of the original type, except where
367 // the source is a constant expression and the actual value after
368 // conversion will fit into the target type and will produce the original
369 // value when converted back to the original type.
370 case ICK_Boolean_Conversion: // Bools are integers too.
371 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
372 // Boolean conversions can be from pointers and pointers to members
373 // [conv.bool], and those aren't considered narrowing conversions.
374 return NK_Not_Narrowing;
375 } // Otherwise, fall through to the integral case.
376 case ICK_Integral_Conversion: {
377 assert(FromType->isIntegralOrUnscopedEnumerationType());
378 assert(ToType->isIntegralOrUnscopedEnumerationType());
379 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
380 const unsigned FromWidth = Ctx.getIntWidth(FromType);
381 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
382 const unsigned ToWidth = Ctx.getIntWidth(ToType);
383
384 if (FromWidth > ToWidth ||
385 (FromWidth == ToWidth && FromSigned != ToSigned)) {
386 // Not all values of FromType can be represented in ToType.
387 llvm::APSInt InitializerValue;
388 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
389 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
390 ConstantValue = APValue(InitializerValue);
391
392 // Add a bit to the InitializerValue so we don't have to worry about
393 // signed vs. unsigned comparisons.
394 InitializerValue = InitializerValue.extend(
395 InitializerValue.getBitWidth() + 1);
396 // Convert the initializer to and from the target width and signed-ness.
397 llvm::APSInt ConvertedValue = InitializerValue;
398 ConvertedValue = ConvertedValue.trunc(ToWidth);
399 ConvertedValue.setIsSigned(ToSigned);
400 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
401 ConvertedValue.setIsSigned(InitializerValue.isSigned());
402 // If the result is different, this was a narrowing conversion.
403 if (ConvertedValue != InitializerValue)
404 return NK_Constant_Narrowing;
405 } else {
406 // Variables are always narrowings.
407 return NK_Variable_Narrowing;
408 }
409 }
410 return NK_Not_Narrowing;
411 }
412
413 default:
414 // Other kinds of conversions are not narrowings.
415 return NK_Not_Narrowing;
416 }
417}
418
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000419/// DebugPrint - Print this standard conversion sequence to standard
420/// error. Useful for debugging overloading issues.
421void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000422 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000423 bool PrintedSomething = false;
424 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000425 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000426 PrintedSomething = true;
427 }
428
429 if (Second != ICK_Identity) {
430 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000431 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000432 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434
435 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000436 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000437 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000438 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000439 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000440 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000441 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 PrintedSomething = true;
443 }
444
445 if (Third != ICK_Identity) {
446 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000447 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000448 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000449 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 }
456}
457
458/// DebugPrint - Print this user-defined conversion sequence to standard
459/// error. Useful for debugging overloading issues.
460void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000461 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000462 if (Before.First || Before.Second || Before.Third) {
463 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000464 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000465 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000466 if (ConversionFunction)
467 OS << '\'' << *ConversionFunction << '\'';
468 else
469 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000470 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000472 After.DebugPrint();
473 }
474}
475
476/// DebugPrint - Print this implicit conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 switch (ConversionKind) {
481 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000482 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 Standard.DebugPrint();
484 break;
485 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000486 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 UserDefined.DebugPrint();
488 break;
489 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000490 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 break;
John McCall1d318332010-01-12 00:44:57 +0000492 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000493 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000494 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000496 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 break;
498 }
499
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000500 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501}
502
John McCall1d318332010-01-12 00:44:57 +0000503void AmbiguousConversionSequence::construct() {
504 new (&conversions()) ConversionSet();
505}
506
507void AmbiguousConversionSequence::destruct() {
508 conversions().~ConversionSet();
509}
510
511void
512AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
513 FromTypePtr = O.FromTypePtr;
514 ToTypePtr = O.ToTypePtr;
515 new (&conversions()) ConversionSet(O.conversions());
516}
517
Douglas Gregora9333192010-05-08 17:41:32 +0000518namespace {
519 // Structure used by OverloadCandidate::DeductionFailureInfo to store
520 // template parameter and template argument information.
521 struct DFIParamWithArguments {
522 TemplateParameter Param;
523 TemplateArgument FirstArg;
524 TemplateArgument SecondArg;
525 };
526}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000527
Douglas Gregora9333192010-05-08 17:41:32 +0000528/// \brief Convert from Sema's representation of template deduction information
529/// to the form used in overload-candidate information.
530OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000531static MakeDeductionFailureInfo(ASTContext &Context,
532 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000533 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000534 OverloadCandidate::DeductionFailureInfo Result;
535 Result.Result = static_cast<unsigned>(TDK);
536 Result.Data = 0;
537 switch (TDK) {
538 case Sema::TDK_Success:
539 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000540 case Sema::TDK_TooManyArguments:
541 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000542 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000543
Douglas Gregora9333192010-05-08 17:41:32 +0000544 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000545 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000546 Result.Data = Info.Param.getOpaqueValue();
547 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000548
Douglas Gregora9333192010-05-08 17:41:32 +0000549 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000550 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000551 // FIXME: Should allocate from normal heap so that we can free this later.
552 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000553 Saved->Param = Info.Param;
554 Saved->FirstArg = Info.FirstArg;
555 Saved->SecondArg = Info.SecondArg;
556 Result.Data = Saved;
557 break;
558 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000559
Douglas Gregora9333192010-05-08 17:41:32 +0000560 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000561 Result.Data = Info.take();
562 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000565 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora9333192010-05-08 17:41:32 +0000569 return Result;
570}
John McCall1d318332010-01-12 00:44:57 +0000571
Douglas Gregora9333192010-05-08 17:41:32 +0000572void OverloadCandidate::DeductionFailureInfo::Destroy() {
573 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
574 case Sema::TDK_Success:
575 case Sema::TDK_InstantiationDepth:
576 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000577 case Sema::TDK_TooManyArguments:
578 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000579 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000580 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581
Douglas Gregora9333192010-05-08 17:41:32 +0000582 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000583 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000584 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000585 Data = 0;
586 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000587
588 case Sema::TDK_SubstitutionFailure:
589 // FIXME: Destroy the template arugment list?
590 Data = 0;
591 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000592
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000593 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000594 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000595 case Sema::TDK_FailedOverloadResolution:
596 break;
597 }
598}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599
600TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000601OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
602 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
603 case Sema::TDK_Success:
604 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000607 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000608 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora9333192010-05-08 17:41:32 +0000610 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000611 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000612 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000613
614 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000615 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000616 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora9333192010-05-08 17:41:32 +0000618 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
621 break;
622 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
Douglas Gregora9333192010-05-08 17:41:32 +0000624 return TemplateParameter();
625}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000626
Douglas Gregorec20f462010-05-08 20:07:26 +0000627TemplateArgumentList *
628OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
631 case Sema::TDK_InstantiationDepth:
632 case Sema::TDK_TooManyArguments:
633 case Sema::TDK_TooFewArguments:
634 case Sema::TDK_Incomplete:
635 case Sema::TDK_InvalidExplicitArguments:
636 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000637 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000638 return 0;
639
640 case Sema::TDK_SubstitutionFailure:
641 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642
Douglas Gregorec20f462010-05-08 20:07:26 +0000643 // Unhandled
644 case Sema::TDK_NonDeducedMismatch:
645 case Sema::TDK_FailedOverloadResolution:
646 break;
647 }
648
649 return 0;
650}
651
Douglas Gregora9333192010-05-08 17:41:32 +0000652const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
654 case Sema::TDK_Success:
655 case Sema::TDK_InstantiationDepth:
656 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000657 case Sema::TDK_TooManyArguments:
658 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000659 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000660 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000661 return 0;
662
Douglas Gregora9333192010-05-08 17:41:32 +0000663 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000664 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000666
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000667 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000668 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000669 case Sema::TDK_FailedOverloadResolution:
670 break;
671 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000672
Douglas Gregora9333192010-05-08 17:41:32 +0000673 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000674}
Douglas Gregora9333192010-05-08 17:41:32 +0000675
676const TemplateArgument *
677OverloadCandidate::DeductionFailureInfo::getSecondArg() {
678 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
679 case Sema::TDK_Success:
680 case Sema::TDK_InstantiationDepth:
681 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000682 case Sema::TDK_TooManyArguments:
683 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000685 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000686 return 0;
687
Douglas Gregora9333192010-05-08 17:41:32 +0000688 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000689 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000690 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
691
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000692 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000693 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000694 case Sema::TDK_FailedOverloadResolution:
695 break;
696 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Douglas Gregora9333192010-05-08 17:41:32 +0000698 return 0;
699}
700
701void OverloadCandidateSet::clear() {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000702 for (iterator i = begin(), e = end(); i != e; ++i)
703 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
704 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000705 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000706 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000707 Functions.clear();
708}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000709
John McCall5acb0c92011-10-17 18:40:02 +0000710namespace {
711 class UnbridgedCastsSet {
712 struct Entry {
713 Expr **Addr;
714 Expr *Saved;
715 };
716 SmallVector<Entry, 2> Entries;
717
718 public:
719 void save(Sema &S, Expr *&E) {
720 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
721 Entry entry = { &E, E };
722 Entries.push_back(entry);
723 E = S.stripARCUnbridgedCast(E);
724 }
725
726 void restore() {
727 for (SmallVectorImpl<Entry>::iterator
728 i = Entries.begin(), e = Entries.end(); i != e; ++i)
729 *i->Addr = i->Saved;
730 }
731 };
732}
733
734/// checkPlaceholderForOverload - Do any interesting placeholder-like
735/// preprocessing on the given expression.
736///
737/// \param unbridgedCasts a collection to which to add unbridged casts;
738/// without this, they will be immediately diagnosed as errors
739///
740/// Return true on unrecoverable error.
741static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
742 UnbridgedCastsSet *unbridgedCasts = 0) {
Richard Smith76f3f692012-02-22 02:04:18 +0000743 S.RequireCompleteType(E->getExprLoc(), E->getType(), 0);
744
John McCall5acb0c92011-10-17 18:40:02 +0000745 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
746 // We can't handle overloaded expressions here because overload
747 // resolution might reasonably tweak them.
748 if (placeholder->getKind() == BuiltinType::Overload) return false;
749
750 // If the context potentially accepts unbridged ARC casts, strip
751 // the unbridged cast and add it to the collection for later restoration.
752 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
753 unbridgedCasts) {
754 unbridgedCasts->save(S, E);
755 return false;
756 }
757
758 // Go ahead and check everything else.
759 ExprResult result = S.CheckPlaceholderExpr(E);
760 if (result.isInvalid())
761 return true;
762
763 E = result.take();
764 return false;
765 }
766
767 // Nothing to do.
768 return false;
769}
770
771/// checkArgPlaceholdersForOverload - Check a set of call operands for
772/// placeholders.
773static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
774 unsigned numArgs,
775 UnbridgedCastsSet &unbridged) {
776 for (unsigned i = 0; i != numArgs; ++i)
777 if (checkPlaceholderForOverload(S, args[i], &unbridged))
778 return true;
779
780 return false;
781}
782
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000783// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000784// overload of the declarations in Old. This routine returns false if
785// New and Old cannot be overloaded, e.g., if New has the same
786// signature as some function in Old (C++ 1.3.10) or if the Old
787// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000788// it does return false, MatchedDecl will point to the decl that New
789// cannot be overloaded with. This decl may be a UsingShadowDecl on
790// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000791//
792// Example: Given the following input:
793//
794// void f(int, float); // #1
795// void f(int, int); // #2
796// int f(int, int); // #3
797//
798// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000799// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000800//
John McCall51fa86f2009-12-02 08:47:38 +0000801// When we process #2, Old contains only the FunctionDecl for #1. By
802// comparing the parameter types, we see that #1 and #2 are overloaded
803// (since they have different signatures), so this routine returns
804// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000805//
John McCall51fa86f2009-12-02 08:47:38 +0000806// When we process #3, Old is an overload set containing #1 and #2. We
807// compare the signatures of #3 to #1 (they're overloaded, so we do
808// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
809// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000810// signature), IsOverload returns false and MatchedDecl will be set to
811// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000812//
813// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
814// into a class by a using declaration. The rules for whether to hide
815// shadow declarations ignore some properties which otherwise figure
816// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000817Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000818Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
819 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000820 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000821 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000822 NamedDecl *OldD = *I;
823
824 bool OldIsUsingDecl = false;
825 if (isa<UsingShadowDecl>(OldD)) {
826 OldIsUsingDecl = true;
827
828 // We can always introduce two using declarations into the same
829 // context, even if they have identical signatures.
830 if (NewIsUsingDecl) continue;
831
832 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
833 }
834
835 // If either declaration was introduced by a using declaration,
836 // we'll need to use slightly different rules for matching.
837 // Essentially, these rules are the normal rules, except that
838 // function templates hide function templates with different
839 // return types or template parameter lists.
840 bool UseMemberUsingDeclRules =
841 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
842
John McCall51fa86f2009-12-02 08:47:38 +0000843 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000844 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
845 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
846 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
847 continue;
848 }
849
John McCall871b2e72009-12-09 03:35:25 +0000850 Match = *I;
851 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000852 }
John McCall51fa86f2009-12-02 08:47:38 +0000853 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000854 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
855 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
856 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
857 continue;
858 }
859
John McCall871b2e72009-12-09 03:35:25 +0000860 Match = *I;
861 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000862 }
John McCalld7945c62010-11-10 03:01:53 +0000863 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000864 // We can overload with these, which can show up when doing
865 // redeclaration checks for UsingDecls.
866 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000867 } else if (isa<TagDecl>(OldD)) {
868 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000869 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
870 // Optimistically assume that an unresolved using decl will
871 // overload; if it doesn't, we'll have to diagnose during
872 // template instantiation.
873 } else {
John McCall68263142009-11-18 22:49:29 +0000874 // (C++ 13p1):
875 // Only function declarations can be overloaded; object and type
876 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000877 Match = *I;
878 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000879 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000880 }
John McCall68263142009-11-18 22:49:29 +0000881
John McCall871b2e72009-12-09 03:35:25 +0000882 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000883}
884
John McCallad00b772010-06-16 08:42:20 +0000885bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
886 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000887 // If both of the functions are extern "C", then they are not
888 // overloads.
889 if (Old->isExternC() && New->isExternC())
890 return false;
891
John McCall68263142009-11-18 22:49:29 +0000892 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
893 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
894
895 // C++ [temp.fct]p2:
896 // A function template can be overloaded with other function templates
897 // and with normal (non-template) functions.
898 if ((OldTemplate == 0) != (NewTemplate == 0))
899 return true;
900
901 // Is the function New an overload of the function Old?
902 QualType OldQType = Context.getCanonicalType(Old->getType());
903 QualType NewQType = Context.getCanonicalType(New->getType());
904
905 // Compare the signatures (C++ 1.3.10) of the two functions to
906 // determine whether they are overloads. If we find any mismatch
907 // in the signature, they are overloads.
908
909 // If either of these functions is a K&R-style function (no
910 // prototype), then we consider them to have matching signatures.
911 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
912 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
913 return false;
914
John McCallf4c73712011-01-19 06:33:43 +0000915 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
916 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000917
918 // The signature of a function includes the types of its
919 // parameters (C++ 1.3.10), which includes the presence or absence
920 // of the ellipsis; see C++ DR 357).
921 if (OldQType != NewQType &&
922 (OldType->getNumArgs() != NewType->getNumArgs() ||
923 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000924 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000925 return true;
926
927 // C++ [temp.over.link]p4:
928 // The signature of a function template consists of its function
929 // signature, its return type and its template parameter list. The names
930 // of the template parameters are significant only for establishing the
931 // relationship between the template parameters and the rest of the
932 // signature.
933 //
934 // We check the return type and template parameter lists for function
935 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000936 //
937 // However, we don't consider either of these when deciding whether
938 // a member introduced by a shadow declaration is hidden.
939 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000940 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
941 OldTemplate->getTemplateParameters(),
942 false, TPL_TemplateMatch) ||
943 OldType->getResultType() != NewType->getResultType()))
944 return true;
945
946 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000947 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000948 //
949 // As part of this, also check whether one of the member functions
950 // is static, in which case they are not overloads (C++
951 // 13.1p2). While not part of the definition of the signature,
952 // this check is important to determine whether these functions
953 // can be overloaded.
954 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
955 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
956 if (OldMethod && NewMethod &&
957 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000958 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000959 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
960 if (!UseUsingDeclRules &&
961 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
962 (OldMethod->getRefQualifier() == RQ_None ||
963 NewMethod->getRefQualifier() == RQ_None)) {
964 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000965 // - Member function declarations with the same name and the same
966 // parameter-type-list as well as member function template
967 // declarations with the same name, the same parameter-type-list, and
968 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000969 // them, but not all, have a ref-qualifier (8.3.5).
970 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
971 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
972 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
973 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000974
John McCall68263142009-11-18 22:49:29 +0000975 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000976 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000977
John McCall68263142009-11-18 22:49:29 +0000978 // The signatures match; this is not an overload.
979 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000980}
981
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +0000982/// \brief Checks availability of the function depending on the current
983/// function context. Inside an unavailable function, unavailability is ignored.
984///
985/// \returns true if \arg FD is unavailable and current context is inside
986/// an available function, false otherwise.
987bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
988 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
989}
990
Sebastian Redlcf15cef2011-12-22 18:58:38 +0000991/// \brief Tries a user-defined conversion from From to ToType.
992///
993/// Produces an implicit conversion sequence for when a standard conversion
994/// is not an option. See TryImplicitConversion for more information.
995static ImplicitConversionSequence
996TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
997 bool SuppressUserConversions,
998 bool AllowExplicit,
999 bool InOverloadResolution,
1000 bool CStyle,
1001 bool AllowObjCWritebackConversion) {
1002 ImplicitConversionSequence ICS;
1003
1004 if (SuppressUserConversions) {
1005 // We're not in the case above, so there is no conversion that
1006 // we can perform.
1007 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1008 return ICS;
1009 }
1010
1011 // Attempt user-defined conversion.
1012 OverloadCandidateSet Conversions(From->getExprLoc());
1013 OverloadingResult UserDefResult
1014 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1015 AllowExplicit);
1016
1017 if (UserDefResult == OR_Success) {
1018 ICS.setUserDefined();
1019 // C++ [over.ics.user]p4:
1020 // A conversion of an expression of class type to the same class
1021 // type is given Exact Match rank, and a conversion of an
1022 // expression of class type to a base class of that type is
1023 // given Conversion rank, in spite of the fact that a copy
1024 // constructor (i.e., a user-defined conversion function) is
1025 // called for those cases.
1026 if (CXXConstructorDecl *Constructor
1027 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1028 QualType FromCanon
1029 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1030 QualType ToCanon
1031 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1032 if (Constructor->isCopyConstructor() &&
1033 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1034 // Turn this into a "standard" conversion sequence, so that it
1035 // gets ranked with standard conversion sequences.
1036 ICS.setStandard();
1037 ICS.Standard.setAsIdentityConversion();
1038 ICS.Standard.setFromType(From->getType());
1039 ICS.Standard.setAllToTypes(ToType);
1040 ICS.Standard.CopyConstructor = Constructor;
1041 if (ToCanon != FromCanon)
1042 ICS.Standard.Second = ICK_Derived_To_Base;
1043 }
1044 }
1045
1046 // C++ [over.best.ics]p4:
1047 // However, when considering the argument of a user-defined
1048 // conversion function that is a candidate by 13.3.1.3 when
1049 // invoked for the copying of the temporary in the second step
1050 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1051 // 13.3.1.6 in all cases, only standard conversion sequences and
1052 // ellipsis conversion sequences are allowed.
1053 if (SuppressUserConversions && ICS.isUserDefined()) {
1054 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1055 }
1056 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1057 ICS.setAmbiguous();
1058 ICS.Ambiguous.setFromType(From->getType());
1059 ICS.Ambiguous.setToType(ToType);
1060 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1061 Cand != Conversions.end(); ++Cand)
1062 if (Cand->Viable)
1063 ICS.Ambiguous.addConversion(Cand->Function);
1064 } else {
1065 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1066 }
1067
1068 return ICS;
1069}
1070
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001071/// TryImplicitConversion - Attempt to perform an implicit conversion
1072/// from the given expression (Expr) to the given type (ToType). This
1073/// function returns an implicit conversion sequence that can be used
1074/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001075///
1076/// void f(float f);
1077/// void g(int i) { f(i); }
1078///
1079/// this routine would produce an implicit conversion sequence to
1080/// describe the initialization of f from i, which will be a standard
1081/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1082/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1083//
1084/// Note that this routine only determines how the conversion can be
1085/// performed; it does not actually perform the conversion. As such,
1086/// it will not produce any diagnostics if no conversion is available,
1087/// but will instead return an implicit conversion sequence of kind
1088/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001089///
1090/// If @p SuppressUserConversions, then user-defined conversions are
1091/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001092/// If @p AllowExplicit, then explicit user-defined conversions are
1093/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001094///
1095/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1096/// writeback conversion, which allows __autoreleasing id* parameters to
1097/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001098static ImplicitConversionSequence
1099TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1100 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001101 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001102 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001103 bool CStyle,
1104 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001105 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001106 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001107 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001108 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001109 return ICS;
1110 }
1111
John McCall120d63c2010-08-24 20:38:10 +00001112 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001113 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001114 return ICS;
1115 }
1116
Douglas Gregor604eb652010-08-11 02:15:33 +00001117 // C++ [over.ics.user]p4:
1118 // A conversion of an expression of class type to the same class
1119 // type is given Exact Match rank, and a conversion of an
1120 // expression of class type to a base class of that type is
1121 // given Conversion rank, in spite of the fact that a copy/move
1122 // constructor (i.e., a user-defined conversion function) is
1123 // called for those cases.
1124 QualType FromType = From->getType();
1125 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001126 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1127 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001128 ICS.setStandard();
1129 ICS.Standard.setAsIdentityConversion();
1130 ICS.Standard.setFromType(FromType);
1131 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001132
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001133 // We don't actually check at this point whether there is a valid
1134 // copy/move constructor, since overloading just assumes that it
1135 // exists. When we actually perform initialization, we'll find the
1136 // appropriate constructor to copy the returned object, if needed.
1137 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001138
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001139 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001140 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001141 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001142
Douglas Gregor604eb652010-08-11 02:15:33 +00001143 return ICS;
1144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001145
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001146 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1147 AllowExplicit, InOverloadResolution, CStyle,
1148 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001149}
1150
John McCallf85e1932011-06-15 23:02:42 +00001151ImplicitConversionSequence
1152Sema::TryImplicitConversion(Expr *From, QualType ToType,
1153 bool SuppressUserConversions,
1154 bool AllowExplicit,
1155 bool InOverloadResolution,
1156 bool CStyle,
1157 bool AllowObjCWritebackConversion) {
1158 return clang::TryImplicitConversion(*this, From, ToType,
1159 SuppressUserConversions, AllowExplicit,
1160 InOverloadResolution, CStyle,
1161 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001162}
1163
Douglas Gregor575c63a2010-04-16 22:27:05 +00001164/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001165/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001166/// converted expression. Flavor is the kind of conversion we're
1167/// performing, used in the error message. If @p AllowExplicit,
1168/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001169ExprResult
1170Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001171 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001172 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001173 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001174}
1175
John Wiegley429bb272011-04-08 18:41:53 +00001176ExprResult
1177Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001178 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001179 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001180 if (checkPlaceholderForOverload(*this, From))
1181 return ExprError();
1182
John McCallf85e1932011-06-15 23:02:42 +00001183 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1184 bool AllowObjCWritebackConversion
1185 = getLangOptions().ObjCAutoRefCount &&
1186 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001187
John McCall120d63c2010-08-24 20:38:10 +00001188 ICS = clang::TryImplicitConversion(*this, From, ToType,
1189 /*SuppressUserConversions=*/false,
1190 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001191 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001192 /*CStyle=*/false,
1193 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001194 return PerformImplicitConversion(From, ToType, ICS, Action);
1195}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001196
1197/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001198/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001199bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1200 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001201 if (Context.hasSameUnqualifiedType(FromType, ToType))
1202 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001203
John McCall00ccbef2010-12-21 00:44:39 +00001204 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1205 // where F adds one of the following at most once:
1206 // - a pointer
1207 // - a member pointer
1208 // - a block pointer
1209 CanQualType CanTo = Context.getCanonicalType(ToType);
1210 CanQualType CanFrom = Context.getCanonicalType(FromType);
1211 Type::TypeClass TyClass = CanTo->getTypeClass();
1212 if (TyClass != CanFrom->getTypeClass()) return false;
1213 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1214 if (TyClass == Type::Pointer) {
1215 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1216 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1217 } else if (TyClass == Type::BlockPointer) {
1218 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1219 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1220 } else if (TyClass == Type::MemberPointer) {
1221 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1222 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1223 } else {
1224 return false;
1225 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001226
John McCall00ccbef2010-12-21 00:44:39 +00001227 TyClass = CanTo->getTypeClass();
1228 if (TyClass != CanFrom->getTypeClass()) return false;
1229 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1230 return false;
1231 }
1232
1233 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1234 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1235 if (!EInfo.getNoReturn()) return false;
1236
1237 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1238 assert(QualType(FromFn, 0).isCanonical());
1239 if (QualType(FromFn, 0) != CanTo) return false;
1240
1241 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001242 return true;
1243}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001245/// \brief Determine whether the conversion from FromType to ToType is a valid
1246/// vector conversion.
1247///
1248/// \param ICK Will be set to the vector conversion kind, if this is a vector
1249/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1251 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001252 // We need at least one of these types to be a vector type to have a vector
1253 // conversion.
1254 if (!ToType->isVectorType() && !FromType->isVectorType())
1255 return false;
1256
1257 // Identical types require no conversions.
1258 if (Context.hasSameUnqualifiedType(FromType, ToType))
1259 return false;
1260
1261 // There are no conversions between extended vector types, only identity.
1262 if (ToType->isExtVectorType()) {
1263 // There are no conversions between extended vector types other than the
1264 // identity conversion.
1265 if (FromType->isExtVectorType())
1266 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001268 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001269 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001270 ICK = ICK_Vector_Splat;
1271 return true;
1272 }
1273 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001274
1275 // We can perform the conversion between vector types in the following cases:
1276 // 1)vector types are equivalent AltiVec and GCC vector types
1277 // 2)lax vector conversions are permitted and the vector types are of the
1278 // same size
1279 if (ToType->isVectorType() && FromType->isVectorType()) {
1280 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001281 (Context.getLangOptions().LaxVectorConversions &&
1282 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001283 ICK = ICK_Vector_Conversion;
1284 return true;
1285 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001286 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001287
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001288 return false;
1289}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001290
Douglas Gregor60d62c22008-10-31 16:23:19 +00001291/// IsStandardConversion - Determines whether there is a standard
1292/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1293/// expression From to the type ToType. Standard conversion sequences
1294/// only consider non-class types; for conversions that involve class
1295/// types, use TryImplicitConversion. If a conversion exists, SCS will
1296/// contain the standard conversion sequence required to perform this
1297/// conversion and this routine will return true. Otherwise, this
1298/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001299static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1300 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001301 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001302 bool CStyle,
1303 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001304 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001305
Douglas Gregor60d62c22008-10-31 16:23:19 +00001306 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001307 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001308 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001309 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001310 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001311 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001312
Douglas Gregorf9201e02009-02-11 23:02:49 +00001313 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001314 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001315 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001316 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001317 return false;
1318
Mike Stump1eb44332009-09-09 15:08:12 +00001319 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001320 }
1321
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001322 // The first conversion can be an lvalue-to-rvalue conversion,
1323 // array-to-pointer conversion, or function-to-pointer conversion
1324 // (C++ 4p1).
1325
John McCall120d63c2010-08-24 20:38:10 +00001326 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001327 DeclAccessPair AccessPair;
1328 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001329 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001330 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001331 // We were able to resolve the address of the overloaded function,
1332 // so we can convert to the type of that function.
1333 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001334
1335 // we can sometimes resolve &foo<int> regardless of ToType, so check
1336 // if the type matches (identity) or we are converting to bool
1337 if (!S.Context.hasSameUnqualifiedType(
1338 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1339 QualType resultTy;
1340 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001341 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001342 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1343 // otherwise, only a boolean conversion is standard
1344 if (!ToType->isBooleanType())
1345 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001346 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347
Chandler Carruth90434232011-03-29 08:08:18 +00001348 // Check if the "from" expression is taking the address of an overloaded
1349 // function and recompute the FromType accordingly. Take advantage of the
1350 // fact that non-static member functions *must* have such an address-of
1351 // expression.
1352 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1353 if (Method && !Method->isStatic()) {
1354 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1355 "Non-unary operator on non-static member address");
1356 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1357 == UO_AddrOf &&
1358 "Non-address-of operator on non-static member address");
1359 const Type *ClassType
1360 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1361 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001362 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1363 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1364 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001365 "Non-address-of operator for overloaded function expression");
1366 FromType = S.Context.getPointerType(FromType);
1367 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001368
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001369 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001370 assert(S.Context.hasSameType(
1371 FromType,
1372 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001373 } else {
1374 return false;
1375 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001376 }
John McCall21480112011-08-30 00:57:29 +00001377 // Lvalue-to-rvalue conversion (C++11 4.1):
1378 // A glvalue (3.10) of a non-function, non-array type T can
1379 // be converted to a prvalue.
1380 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001381 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001382 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001383 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001384 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001385
1386 // If T is a non-class type, the type of the rvalue is the
1387 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001388 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1389 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001390 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001391 } else if (FromType->isArrayType()) {
1392 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001393 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001394
1395 // An lvalue or rvalue of type "array of N T" or "array of unknown
1396 // bound of T" can be converted to an rvalue of type "pointer to
1397 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001398 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001399
John McCall120d63c2010-08-24 20:38:10 +00001400 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001401 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001402 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001403
1404 // For the purpose of ranking in overload resolution
1405 // (13.3.3.1.1), this conversion is considered an
1406 // array-to-pointer conversion followed by a qualification
1407 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001408 SCS.Second = ICK_Identity;
1409 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001410 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001411 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001412 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001413 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001414 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001415 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001416 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001417
1418 // An lvalue of function type T can be converted to an rvalue of
1419 // type "pointer to T." The result is a pointer to the
1420 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001421 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001422 } else {
1423 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001424 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001425 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001426 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001427
1428 // The second conversion can be an integral promotion, floating
1429 // point promotion, integral conversion, floating point conversion,
1430 // floating-integral conversion, pointer conversion,
1431 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001432 // For overloading in C, this can also be a "compatible-type"
1433 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001434 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001435 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001436 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001437 // The unqualified versions of the types are the same: there's no
1438 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001439 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001440 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001441 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001442 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001443 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001444 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001445 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001446 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001447 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001448 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001449 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001450 SCS.Second = ICK_Complex_Promotion;
1451 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001452 } else if (ToType->isBooleanType() &&
1453 (FromType->isArithmeticType() ||
1454 FromType->isAnyPointerType() ||
1455 FromType->isBlockPointerType() ||
1456 FromType->isMemberPointerType() ||
1457 FromType->isNullPtrType())) {
1458 // Boolean conversions (C++ 4.12).
1459 SCS.Second = ICK_Boolean_Conversion;
1460 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001461 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001462 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001463 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001464 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001465 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001466 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001467 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001468 SCS.Second = ICK_Complex_Conversion;
1469 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001470 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1471 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001472 // Complex-real conversions (C99 6.3.1.7)
1473 SCS.Second = ICK_Complex_Real;
1474 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001475 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001476 // Floating point conversions (C++ 4.8).
1477 SCS.Second = ICK_Floating_Conversion;
1478 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001479 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001480 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001481 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001482 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001483 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001484 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001485 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001486 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001487 SCS.Second = ICK_Block_Pointer_Conversion;
1488 } else if (AllowObjCWritebackConversion &&
1489 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1490 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001491 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1492 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001493 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001494 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001495 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001496 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001497 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001498 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001499 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001500 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001501 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001502 SCS.Second = SecondICK;
1503 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001504 } else if (!S.getLangOptions().CPlusPlus &&
1505 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001506 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001507 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001508 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001509 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001510 // Treat a conversion that strips "noreturn" as an identity conversion.
1511 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001512 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1513 InOverloadResolution,
1514 SCS, CStyle)) {
1515 SCS.Second = ICK_TransparentUnionConversion;
1516 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001517 } else {
1518 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001519 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001520 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001521 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001522
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001523 QualType CanonFrom;
1524 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001525 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001526 bool ObjCLifetimeConversion;
1527 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1528 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001529 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001530 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001532 CanonFrom = S.Context.getCanonicalType(FromType);
1533 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001534 } else {
1535 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001536 SCS.Third = ICK_Identity;
1537
Mike Stump1eb44332009-09-09 15:08:12 +00001538 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001539 // [...] Any difference in top-level cv-qualification is
1540 // subsumed by the initialization itself and does not constitute
1541 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001542 CanonFrom = S.Context.getCanonicalType(FromType);
1543 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001544 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001545 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001546 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001547 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1548 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001549 FromType = ToType;
1550 CanonFrom = CanonTo;
1551 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001552 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001553 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001554
1555 // If we have not converted the argument type to the parameter type,
1556 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001557 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001558 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001559
Douglas Gregor60d62c22008-10-31 16:23:19 +00001560 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001561}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001562
1563static bool
1564IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1565 QualType &ToType,
1566 bool InOverloadResolution,
1567 StandardConversionSequence &SCS,
1568 bool CStyle) {
1569
1570 const RecordType *UT = ToType->getAsUnionType();
1571 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1572 return false;
1573 // The field to initialize within the transparent union.
1574 RecordDecl *UD = UT->getDecl();
1575 // It's compatible if the expression matches any of the fields.
1576 for (RecordDecl::field_iterator it = UD->field_begin(),
1577 itend = UD->field_end();
1578 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001579 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1580 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001581 ToType = it->getType();
1582 return true;
1583 }
1584 }
1585 return false;
1586}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001587
1588/// IsIntegralPromotion - Determines whether the conversion from the
1589/// expression From (whose potentially-adjusted type is FromType) to
1590/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1591/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001592bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001593 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001594 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001595 if (!To) {
1596 return false;
1597 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001598
1599 // An rvalue of type char, signed char, unsigned char, short int, or
1600 // unsigned short int can be converted to an rvalue of type int if
1601 // int can represent all the values of the source type; otherwise,
1602 // the source rvalue can be converted to an rvalue of type unsigned
1603 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001604 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1605 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001606 if (// We can promote any signed, promotable integer type to an int
1607 (FromType->isSignedIntegerType() ||
1608 // We can promote any unsigned integer type whose size is
1609 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001610 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001611 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001612 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001613 }
1614
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001615 return To->getKind() == BuiltinType::UInt;
1616 }
1617
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001618 // C++0x [conv.prom]p3:
1619 // A prvalue of an unscoped enumeration type whose underlying type is not
1620 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1621 // following types that can represent all the values of the enumeration
1622 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1623 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001624 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001625 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001626 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001627 // with lowest integer conversion rank (4.13) greater than the rank of long
1628 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001629 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001630 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1631 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1632 // provided for a scoped enumeration.
1633 if (FromEnumType->getDecl()->isScoped())
1634 return false;
1635
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001636 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001637 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001638 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001639 return Context.hasSameUnqualifiedType(ToType,
1640 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001641 }
John McCall842aef82009-12-09 09:09:27 +00001642
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001643 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001644 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1645 // to an rvalue a prvalue of the first of the following types that can
1646 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001647 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001649 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001651 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001652 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001653 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001654 // Determine whether the type we're converting from is signed or
1655 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001656 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001657 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001658
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001659 // The types we'll try to promote to, in the appropriate
1660 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001661 QualType PromoteTypes[6] = {
1662 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001663 Context.LongTy, Context.UnsignedLongTy ,
1664 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001665 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001666 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1668 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001669 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1671 // We found the type that we can promote to. If this is the
1672 // type we wanted, we have a promotion. Otherwise, no
1673 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001674 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001675 }
1676 }
1677 }
1678
1679 // An rvalue for an integral bit-field (9.6) can be converted to an
1680 // rvalue of type int if int can represent all the values of the
1681 // bit-field; otherwise, it can be converted to unsigned int if
1682 // unsigned int can represent all the values of the bit-field. If
1683 // the bit-field is larger yet, no integral promotion applies to
1684 // it. If the bit-field has an enumerated type, it is treated as any
1685 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001686 // FIXME: We should delay checking of bit-fields until we actually perform the
1687 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001688 using llvm::APSInt;
1689 if (From)
1690 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001691 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001692 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001693 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1694 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1695 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Douglas Gregor86f19402008-12-20 23:49:58 +00001697 // Are we promoting to an int from a bitfield that fits in an int?
1698 if (BitWidth < ToSize ||
1699 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1700 return To->getKind() == BuiltinType::Int;
1701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregor86f19402008-12-20 23:49:58 +00001703 // Are we promoting to an unsigned int from an unsigned bitfield
1704 // that fits into an unsigned int?
1705 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1706 return To->getKind() == BuiltinType::UInt;
1707 }
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor86f19402008-12-20 23:49:58 +00001709 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001710 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001713 // An rvalue of type bool can be converted to an rvalue of type int,
1714 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001715 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001716 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001717 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001718
1719 return false;
1720}
1721
1722/// IsFloatingPointPromotion - Determines whether the conversion from
1723/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1724/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001725bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001726 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1727 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001728 /// An rvalue of type float can be converted to an rvalue of type
1729 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001730 if (FromBuiltin->getKind() == BuiltinType::Float &&
1731 ToBuiltin->getKind() == BuiltinType::Double)
1732 return true;
1733
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001734 // C99 6.3.1.5p1:
1735 // When a float is promoted to double or long double, or a
1736 // double is promoted to long double [...].
1737 if (!getLangOptions().CPlusPlus &&
1738 (FromBuiltin->getKind() == BuiltinType::Float ||
1739 FromBuiltin->getKind() == BuiltinType::Double) &&
1740 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1741 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001742
1743 // Half can be promoted to float.
1744 if (FromBuiltin->getKind() == BuiltinType::Half &&
1745 ToBuiltin->getKind() == BuiltinType::Float)
1746 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001747 }
1748
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001749 return false;
1750}
1751
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001752/// \brief Determine if a conversion is a complex promotion.
1753///
1754/// A complex promotion is defined as a complex -> complex conversion
1755/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001756/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001757bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001758 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001759 if (!FromComplex)
1760 return false;
1761
John McCall183700f2009-09-21 23:43:11 +00001762 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001763 if (!ToComplex)
1764 return false;
1765
1766 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001767 ToComplex->getElementType()) ||
1768 IsIntegralPromotion(0, FromComplex->getElementType(),
1769 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001770}
1771
Douglas Gregorcb7de522008-11-26 23:31:11 +00001772/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1773/// the pointer type FromPtr to a pointer to type ToPointee, with the
1774/// same type qualifiers as FromPtr has on its pointee type. ToType,
1775/// if non-empty, will be a pointer to ToType that may or may not have
1776/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001777///
Mike Stump1eb44332009-09-09 15:08:12 +00001778static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001779BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001780 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001781 ASTContext &Context,
1782 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001783 assert((FromPtr->getTypeClass() == Type::Pointer ||
1784 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1785 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786
John McCallf85e1932011-06-15 23:02:42 +00001787 /// Conversions to 'id' subsume cv-qualifier conversions.
1788 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001789 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001790
1791 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001792 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001793 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001794 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001795
John McCallf85e1932011-06-15 23:02:42 +00001796 if (StripObjCLifetime)
1797 Quals.removeObjCLifetime();
1798
Mike Stump1eb44332009-09-09 15:08:12 +00001799 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001800 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001801 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001802 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001803 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001804
1805 // Build a pointer to ToPointee. It has the right qualifiers
1806 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001807 if (isa<ObjCObjectPointerType>(ToType))
1808 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001809 return Context.getPointerType(ToPointee);
1810 }
1811
1812 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001813 QualType QualifiedCanonToPointee
1814 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001815
Douglas Gregorda80f742010-12-01 21:43:58 +00001816 if (isa<ObjCObjectPointerType>(ToType))
1817 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1818 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001819}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001820
Mike Stump1eb44332009-09-09 15:08:12 +00001821static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001822 bool InOverloadResolution,
1823 ASTContext &Context) {
1824 // Handle value-dependent integral null pointer constants correctly.
1825 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1826 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001827 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001828 return !InOverloadResolution;
1829
Douglas Gregorce940492009-09-25 04:25:58 +00001830 return Expr->isNullPointerConstant(Context,
1831 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1832 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001833}
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001835/// IsPointerConversion - Determines whether the conversion of the
1836/// expression From, which has the (possibly adjusted) type FromType,
1837/// can be converted to the type ToType via a pointer conversion (C++
1838/// 4.10). If so, returns true and places the converted type (that
1839/// might differ from ToType in its cv-qualifiers at some level) into
1840/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001841///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001842/// This routine also supports conversions to and from block pointers
1843/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1844/// pointers to interfaces. FIXME: Once we've determined the
1845/// appropriate overloading rules for Objective-C, we may want to
1846/// split the Objective-C checks into a different routine; however,
1847/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001848/// conversions, so for now they live here. IncompatibleObjC will be
1849/// set if the conversion is an allowed Objective-C conversion that
1850/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001851bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001852 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001853 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001854 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001855 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001856 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1857 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001858 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001859
Mike Stump1eb44332009-09-09 15:08:12 +00001860 // Conversion from a null pointer constant to any Objective-C pointer type.
1861 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001862 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001863 ConvertedType = ToType;
1864 return true;
1865 }
1866
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001867 // Blocks: Block pointers can be converted to void*.
1868 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001869 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001870 ConvertedType = ToType;
1871 return true;
1872 }
1873 // Blocks: A null pointer constant can be converted to a block
1874 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001875 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001876 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001877 ConvertedType = ToType;
1878 return true;
1879 }
1880
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001881 // If the left-hand-side is nullptr_t, the right side can be a null
1882 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001883 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001884 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001885 ConvertedType = ToType;
1886 return true;
1887 }
1888
Ted Kremenek6217b802009-07-29 21:53:49 +00001889 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001890 if (!ToTypePtr)
1891 return false;
1892
1893 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001894 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001895 ConvertedType = ToType;
1896 return true;
1897 }
Sebastian Redl07779722008-10-31 14:43:28 +00001898
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001899 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001900 // , including objective-c pointers.
1901 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001902 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1903 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001904 ConvertedType = BuildSimilarlyQualifiedPointerType(
1905 FromType->getAs<ObjCObjectPointerType>(),
1906 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001907 ToType, Context);
1908 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001909 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001910 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001911 if (!FromTypePtr)
1912 return false;
1913
1914 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001915
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001916 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001917 // pointer conversion, so don't do all of the work below.
1918 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1919 return false;
1920
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001921 // An rvalue of type "pointer to cv T," where T is an object type,
1922 // can be converted to an rvalue of type "pointer to cv void" (C++
1923 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001924 if (FromPointeeType->isIncompleteOrObjectType() &&
1925 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001926 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001927 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001928 ToType, Context,
1929 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001930 return true;
1931 }
1932
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001933 // MSVC allows implicit function to void* type conversion.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001934 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001935 ToPointeeType->isVoidType()) {
1936 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1937 ToPointeeType,
1938 ToType, Context);
1939 return true;
1940 }
1941
Douglas Gregorf9201e02009-02-11 23:02:49 +00001942 // When we're overloading in C, we allow a special kind of pointer
1943 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001944 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001945 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001946 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001947 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001948 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001949 return true;
1950 }
1951
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001952 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001953 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001954 // An rvalue of type "pointer to cv D," where D is a class type,
1955 // can be converted to an rvalue of type "pointer to cv B," where
1956 // B is a base class (clause 10) of D. If B is an inaccessible
1957 // (clause 11) or ambiguous (10.2) base class of D, a program that
1958 // necessitates this conversion is ill-formed. The result of the
1959 // conversion is a pointer to the base class sub-object of the
1960 // derived class object. The null pointer value is converted to
1961 // the null pointer value of the destination type.
1962 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001963 // Note that we do not check for ambiguity or inaccessibility
1964 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001965 if (getLangOptions().CPlusPlus &&
1966 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001967 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001968 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001969 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001970 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001971 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001972 ToType, Context);
1973 return true;
1974 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001975
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001976 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1977 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1978 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1979 ToPointeeType,
1980 ToType, Context);
1981 return true;
1982 }
1983
Douglas Gregorc7887512008-12-19 19:13:09 +00001984 return false;
1985}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001986
1987/// \brief Adopt the given qualifiers for the given type.
1988static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1989 Qualifiers TQs = T.getQualifiers();
1990
1991 // Check whether qualifiers already match.
1992 if (TQs == Qs)
1993 return T;
1994
1995 if (Qs.compatiblyIncludes(TQs))
1996 return Context.getQualifiedType(T, Qs);
1997
1998 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1999}
Douglas Gregorc7887512008-12-19 19:13:09 +00002000
2001/// isObjCPointerConversion - Determines whether this is an
2002/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2003/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002004bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002005 QualType& ConvertedType,
2006 bool &IncompatibleObjC) {
2007 if (!getLangOptions().ObjC1)
2008 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002009
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002010 // The set of qualifiers on the type we're converting from.
2011 Qualifiers FromQualifiers = FromType.getQualifiers();
2012
Steve Naroff14108da2009-07-10 23:34:53 +00002013 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002014 const ObjCObjectPointerType* ToObjCPtr =
2015 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002016 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002017 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002018
Steve Naroff14108da2009-07-10 23:34:53 +00002019 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002020 // If the pointee types are the same (ignoring qualifications),
2021 // then this is not a pointer conversion.
2022 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2023 FromObjCPtr->getPointeeType()))
2024 return false;
2025
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002026 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002027 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002028 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002029 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002030 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002031 return true;
2032 }
2033 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002034 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002035 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002036 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002037 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002038 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002039 return true;
2040 }
2041 // Objective C++: We're able to convert from a pointer to an
2042 // interface to a pointer to a different interface.
2043 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002044 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2045 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2046 if (getLangOptions().CPlusPlus && LHS && RHS &&
2047 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2048 FromObjCPtr->getPointeeType()))
2049 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002050 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002051 ToObjCPtr->getPointeeType(),
2052 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002053 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002054 return true;
2055 }
2056
2057 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2058 // Okay: this is some kind of implicit downcast of Objective-C
2059 // interfaces, which is permitted. However, we're going to
2060 // complain about it.
2061 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002062 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002063 ToObjCPtr->getPointeeType(),
2064 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002065 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002066 return true;
2067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068 }
Steve Naroff14108da2009-07-10 23:34:53 +00002069 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002070 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002071 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002072 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002073 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002074 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002075 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002076 // to a block pointer type.
2077 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002078 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002079 return true;
2080 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002081 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002082 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002083 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002084 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002085 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002086 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002087 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002088 return true;
2089 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002090 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002091 return false;
2092
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002093 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002094 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002095 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002096 else if (const BlockPointerType *FromBlockPtr =
2097 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002098 FromPointeeType = FromBlockPtr->getPointeeType();
2099 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002100 return false;
2101
Douglas Gregorc7887512008-12-19 19:13:09 +00002102 // If we have pointers to pointers, recursively check whether this
2103 // is an Objective-C conversion.
2104 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2105 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2106 IncompatibleObjC)) {
2107 // We always complain about this conversion.
2108 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002109 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002110 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002111 return true;
2112 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002113 // Allow conversion of pointee being objective-c pointer to another one;
2114 // as in I* to id.
2115 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2116 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2117 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2118 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002119
Douglas Gregorda80f742010-12-01 21:43:58 +00002120 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002121 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002122 return true;
2123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002124
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002125 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002126 // differences in the argument and result types are in Objective-C
2127 // pointer conversions. If so, we permit the conversion (but
2128 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002129 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002130 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002131 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002132 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002133 if (FromFunctionType && ToFunctionType) {
2134 // If the function types are exactly the same, this isn't an
2135 // Objective-C pointer conversion.
2136 if (Context.getCanonicalType(FromPointeeType)
2137 == Context.getCanonicalType(ToPointeeType))
2138 return false;
2139
2140 // Perform the quick checks that will tell us whether these
2141 // function types are obviously different.
2142 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2143 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2144 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2145 return false;
2146
2147 bool HasObjCConversion = false;
2148 if (Context.getCanonicalType(FromFunctionType->getResultType())
2149 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2150 // Okay, the types match exactly. Nothing to do.
2151 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2152 ToFunctionType->getResultType(),
2153 ConvertedType, IncompatibleObjC)) {
2154 // Okay, we have an Objective-C pointer conversion.
2155 HasObjCConversion = true;
2156 } else {
2157 // Function types are too different. Abort.
2158 return false;
2159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Douglas Gregorc7887512008-12-19 19:13:09 +00002161 // Check argument types.
2162 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2163 ArgIdx != NumArgs; ++ArgIdx) {
2164 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2165 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2166 if (Context.getCanonicalType(FromArgType)
2167 == Context.getCanonicalType(ToArgType)) {
2168 // Okay, the types match exactly. Nothing to do.
2169 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2170 ConvertedType, IncompatibleObjC)) {
2171 // Okay, we have an Objective-C pointer conversion.
2172 HasObjCConversion = true;
2173 } else {
2174 // Argument types are too different. Abort.
2175 return false;
2176 }
2177 }
2178
2179 if (HasObjCConversion) {
2180 // We had an Objective-C conversion. Allow this pointer
2181 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002182 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002183 IncompatibleObjC = true;
2184 return true;
2185 }
2186 }
2187
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002188 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002189}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002190
John McCallf85e1932011-06-15 23:02:42 +00002191/// \brief Determine whether this is an Objective-C writeback conversion,
2192/// used for parameter passing when performing automatic reference counting.
2193///
2194/// \param FromType The type we're converting form.
2195///
2196/// \param ToType The type we're converting to.
2197///
2198/// \param ConvertedType The type that will be produced after applying
2199/// this conversion.
2200bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2201 QualType &ConvertedType) {
2202 if (!getLangOptions().ObjCAutoRefCount ||
2203 Context.hasSameUnqualifiedType(FromType, ToType))
2204 return false;
2205
2206 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2207 QualType ToPointee;
2208 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2209 ToPointee = ToPointer->getPointeeType();
2210 else
2211 return false;
2212
2213 Qualifiers ToQuals = ToPointee.getQualifiers();
2214 if (!ToPointee->isObjCLifetimeType() ||
2215 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002216 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002217 return false;
2218
2219 // Argument must be a pointer to __strong to __weak.
2220 QualType FromPointee;
2221 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2222 FromPointee = FromPointer->getPointeeType();
2223 else
2224 return false;
2225
2226 Qualifiers FromQuals = FromPointee.getQualifiers();
2227 if (!FromPointee->isObjCLifetimeType() ||
2228 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2229 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2230 return false;
2231
2232 // Make sure that we have compatible qualifiers.
2233 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2234 if (!ToQuals.compatiblyIncludes(FromQuals))
2235 return false;
2236
2237 // Remove qualifiers from the pointee type we're converting from; they
2238 // aren't used in the compatibility check belong, and we'll be adding back
2239 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2240 FromPointee = FromPointee.getUnqualifiedType();
2241
2242 // The unqualified form of the pointee types must be compatible.
2243 ToPointee = ToPointee.getUnqualifiedType();
2244 bool IncompatibleObjC;
2245 if (Context.typesAreCompatible(FromPointee, ToPointee))
2246 FromPointee = ToPointee;
2247 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2248 IncompatibleObjC))
2249 return false;
2250
2251 /// \brief Construct the type we're converting to, which is a pointer to
2252 /// __autoreleasing pointee.
2253 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2254 ConvertedType = Context.getPointerType(FromPointee);
2255 return true;
2256}
2257
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002258bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2259 QualType& ConvertedType) {
2260 QualType ToPointeeType;
2261 if (const BlockPointerType *ToBlockPtr =
2262 ToType->getAs<BlockPointerType>())
2263 ToPointeeType = ToBlockPtr->getPointeeType();
2264 else
2265 return false;
2266
2267 QualType FromPointeeType;
2268 if (const BlockPointerType *FromBlockPtr =
2269 FromType->getAs<BlockPointerType>())
2270 FromPointeeType = FromBlockPtr->getPointeeType();
2271 else
2272 return false;
2273 // We have pointer to blocks, check whether the only
2274 // differences in the argument and result types are in Objective-C
2275 // pointer conversions. If so, we permit the conversion.
2276
2277 const FunctionProtoType *FromFunctionType
2278 = FromPointeeType->getAs<FunctionProtoType>();
2279 const FunctionProtoType *ToFunctionType
2280 = ToPointeeType->getAs<FunctionProtoType>();
2281
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002282 if (!FromFunctionType || !ToFunctionType)
2283 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002284
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002285 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002286 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002287
2288 // Perform the quick checks that will tell us whether these
2289 // function types are obviously different.
2290 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2291 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2292 return false;
2293
2294 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2295 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2296 if (FromEInfo != ToEInfo)
2297 return false;
2298
2299 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002300 if (Context.hasSameType(FromFunctionType->getResultType(),
2301 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002302 // Okay, the types match exactly. Nothing to do.
2303 } else {
2304 QualType RHS = FromFunctionType->getResultType();
2305 QualType LHS = ToFunctionType->getResultType();
2306 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2307 !RHS.hasQualifiers() && LHS.hasQualifiers())
2308 LHS = LHS.getUnqualifiedType();
2309
2310 if (Context.hasSameType(RHS,LHS)) {
2311 // OK exact match.
2312 } else if (isObjCPointerConversion(RHS, LHS,
2313 ConvertedType, IncompatibleObjC)) {
2314 if (IncompatibleObjC)
2315 return false;
2316 // Okay, we have an Objective-C pointer conversion.
2317 }
2318 else
2319 return false;
2320 }
2321
2322 // Check argument types.
2323 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2324 ArgIdx != NumArgs; ++ArgIdx) {
2325 IncompatibleObjC = false;
2326 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2327 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2328 if (Context.hasSameType(FromArgType, ToArgType)) {
2329 // Okay, the types match exactly. Nothing to do.
2330 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2331 ConvertedType, IncompatibleObjC)) {
2332 if (IncompatibleObjC)
2333 return false;
2334 // Okay, we have an Objective-C pointer conversion.
2335 } else
2336 // Argument types are too different. Abort.
2337 return false;
2338 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002339 if (LangOpts.ObjCAutoRefCount &&
2340 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2341 ToFunctionType))
2342 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002343
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002344 ConvertedType = ToType;
2345 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002346}
2347
Richard Trieu6efd4c52011-11-23 22:32:32 +00002348enum {
2349 ft_default,
2350 ft_different_class,
2351 ft_parameter_arity,
2352 ft_parameter_mismatch,
2353 ft_return_type,
2354 ft_qualifer_mismatch
2355};
2356
2357/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2358/// function types. Catches different number of parameter, mismatch in
2359/// parameter types, and different return types.
2360void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2361 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002362 // If either type is not valid, include no extra info.
2363 if (FromType.isNull() || ToType.isNull()) {
2364 PDiag << ft_default;
2365 return;
2366 }
2367
Richard Trieu6efd4c52011-11-23 22:32:32 +00002368 // Get the function type from the pointers.
2369 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2370 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2371 *ToMember = ToType->getAs<MemberPointerType>();
2372 if (FromMember->getClass() != ToMember->getClass()) {
2373 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2374 << QualType(FromMember->getClass(), 0);
2375 return;
2376 }
2377 FromType = FromMember->getPointeeType();
2378 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002379 }
2380
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002381 if (FromType->isPointerType())
2382 FromType = FromType->getPointeeType();
2383 if (ToType->isPointerType())
2384 ToType = ToType->getPointeeType();
2385
2386 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002387 FromType = FromType.getNonReferenceType();
2388 ToType = ToType.getNonReferenceType();
2389
Richard Trieu6efd4c52011-11-23 22:32:32 +00002390 // Don't print extra info for non-specialized template functions.
2391 if (FromType->isInstantiationDependentType() &&
2392 !FromType->getAs<TemplateSpecializationType>()) {
2393 PDiag << ft_default;
2394 return;
2395 }
2396
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002397 // No extra info for same types.
2398 if (Context.hasSameType(FromType, ToType)) {
2399 PDiag << ft_default;
2400 return;
2401 }
2402
Richard Trieu6efd4c52011-11-23 22:32:32 +00002403 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2404 *ToFunction = ToType->getAs<FunctionProtoType>();
2405
2406 // Both types need to be function types.
2407 if (!FromFunction || !ToFunction) {
2408 PDiag << ft_default;
2409 return;
2410 }
2411
2412 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2413 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2414 << FromFunction->getNumArgs();
2415 return;
2416 }
2417
2418 // Handle different parameter types.
2419 unsigned ArgPos;
2420 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2421 PDiag << ft_parameter_mismatch << ArgPos + 1
2422 << ToFunction->getArgType(ArgPos)
2423 << FromFunction->getArgType(ArgPos);
2424 return;
2425 }
2426
2427 // Handle different return type.
2428 if (!Context.hasSameType(FromFunction->getResultType(),
2429 ToFunction->getResultType())) {
2430 PDiag << ft_return_type << ToFunction->getResultType()
2431 << FromFunction->getResultType();
2432 return;
2433 }
2434
2435 unsigned FromQuals = FromFunction->getTypeQuals(),
2436 ToQuals = ToFunction->getTypeQuals();
2437 if (FromQuals != ToQuals) {
2438 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2439 return;
2440 }
2441
2442 // Unable to find a difference, so add no extra info.
2443 PDiag << ft_default;
2444}
2445
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002446/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002447/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002448/// they have same number of arguments. This routine assumes that Objective-C
2449/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002450/// If the parameters are different, ArgPos will have the the parameter index
2451/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002452bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002453 const FunctionProtoType *NewType,
2454 unsigned *ArgPos) {
2455 if (!getLangOptions().ObjC1) {
2456 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2457 N = NewType->arg_type_begin(),
2458 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2459 if (!Context.hasSameType(*O, *N)) {
2460 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2461 return false;
2462 }
2463 }
2464 return true;
2465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002466
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002467 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2468 N = NewType->arg_type_begin(),
2469 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2470 QualType ToType = (*O);
2471 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002472 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002473 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2474 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002475 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2476 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2477 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2478 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002479 continue;
2480 }
John McCallc12c5bb2010-05-15 11:32:37 +00002481 else if (const ObjCObjectPointerType *PTTo =
2482 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002483 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002484 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002485 if (Context.hasSameUnqualifiedType(
2486 PTTo->getObjectType()->getBaseType(),
2487 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002488 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002489 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002490 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002491 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002492 }
2493 }
2494 return true;
2495}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002496
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002497/// CheckPointerConversion - Check the pointer conversion from the
2498/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002499/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002500/// conversions for which IsPointerConversion has already returned
2501/// true. It returns true and produces a diagnostic if there was an
2502/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002503bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002504 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002505 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002506 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002507 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002508 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002509
John McCalldaa8e4e2010-11-15 09:13:47 +00002510 Kind = CK_BitCast;
2511
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002512 if (!IsCStyleOrFunctionalCast &&
2513 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2514 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2515 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002516 PDiag(diag::warn_impcast_bool_to_null_pointer)
2517 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002518
John McCall1d9b3b22011-09-09 05:25:32 +00002519 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2520 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002521 QualType FromPointeeType = FromPtrType->getPointeeType(),
2522 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002523
Douglas Gregor5fccd362010-03-03 23:55:11 +00002524 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2525 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002526 // We must have a derived-to-base conversion. Check an
2527 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002528 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2529 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002530 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002531 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002532 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002533
Anders Carlsson61faec12009-09-12 04:46:44 +00002534 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002535 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002536 }
2537 }
John McCall1d9b3b22011-09-09 05:25:32 +00002538 } else if (const ObjCObjectPointerType *ToPtrType =
2539 ToType->getAs<ObjCObjectPointerType>()) {
2540 if (const ObjCObjectPointerType *FromPtrType =
2541 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002542 // Objective-C++ conversions are always okay.
2543 // FIXME: We should have a different class of conversions for the
2544 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002545 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002546 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002547 } else if (FromType->isBlockPointerType()) {
2548 Kind = CK_BlockPointerToObjCPointerCast;
2549 } else {
2550 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002551 }
John McCall1d9b3b22011-09-09 05:25:32 +00002552 } else if (ToType->isBlockPointerType()) {
2553 if (!FromType->isBlockPointerType())
2554 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002555 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002556
2557 // We shouldn't fall into this case unless it's valid for other
2558 // reasons.
2559 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2560 Kind = CK_NullToPointer;
2561
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002562 return false;
2563}
2564
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002565/// IsMemberPointerConversion - Determines whether the conversion of the
2566/// expression From, which has the (possibly adjusted) type FromType, can be
2567/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2568/// If so, returns true and places the converted type (that might differ from
2569/// ToType in its cv-qualifiers at some level) into ConvertedType.
2570bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002571 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002572 bool InOverloadResolution,
2573 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002574 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002575 if (!ToTypePtr)
2576 return false;
2577
2578 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002579 if (From->isNullPointerConstant(Context,
2580 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2581 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002582 ConvertedType = ToType;
2583 return true;
2584 }
2585
2586 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002587 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002588 if (!FromTypePtr)
2589 return false;
2590
2591 // A pointer to member of B can be converted to a pointer to member of D,
2592 // where D is derived from B (C++ 4.11p2).
2593 QualType FromClass(FromTypePtr->getClass(), 0);
2594 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002595
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002596 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2597 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2598 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002599 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2600 ToClass.getTypePtr());
2601 return true;
2602 }
2603
2604 return false;
2605}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002606
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002607/// CheckMemberPointerConversion - Check the member pointer conversion from the
2608/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002609/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002610/// for which IsMemberPointerConversion has already returned true. It returns
2611/// true and produces a diagnostic if there was an error, or returns false
2612/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002613bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002614 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002615 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002616 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002617 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002618 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002619 if (!FromPtrType) {
2620 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002621 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002622 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002623 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002624 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002625 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002626 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002627
Ted Kremenek6217b802009-07-29 21:53:49 +00002628 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002629 assert(ToPtrType && "No member pointer cast has a target type "
2630 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002631
Sebastian Redl21593ac2009-01-28 18:33:18 +00002632 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2633 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002634
Sebastian Redl21593ac2009-01-28 18:33:18 +00002635 // FIXME: What about dependent types?
2636 assert(FromClass->isRecordType() && "Pointer into non-class.");
2637 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002638
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002639 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002640 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002641 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2642 assert(DerivationOkay &&
2643 "Should not have been called if derivation isn't OK.");
2644 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002645
Sebastian Redl21593ac2009-01-28 18:33:18 +00002646 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2647 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002648 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2649 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2650 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2651 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002652 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002653
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002654 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002655 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2656 << FromClass << ToClass << QualType(VBase, 0)
2657 << From->getSourceRange();
2658 return true;
2659 }
2660
John McCall6b2accb2010-02-10 09:31:12 +00002661 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002662 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2663 Paths.front(),
2664 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002665
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002666 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002667 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002668 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002669 return false;
2670}
2671
Douglas Gregor98cd5992008-10-21 23:43:52 +00002672/// IsQualificationConversion - Determines whether the conversion from
2673/// an rvalue of type FromType to ToType is a qualification conversion
2674/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002675///
2676/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2677/// when the qualification conversion involves a change in the Objective-C
2678/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002679bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002680Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002681 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002682 FromType = Context.getCanonicalType(FromType);
2683 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002684 ObjCLifetimeConversion = false;
2685
Douglas Gregor98cd5992008-10-21 23:43:52 +00002686 // If FromType and ToType are the same type, this is not a
2687 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002688 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002689 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002690
Douglas Gregor98cd5992008-10-21 23:43:52 +00002691 // (C++ 4.4p4):
2692 // A conversion can add cv-qualifiers at levels other than the first
2693 // in multi-level pointers, subject to the following rules: [...]
2694 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002695 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002696 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002697 // Within each iteration of the loop, we check the qualifiers to
2698 // determine if this still looks like a qualification
2699 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002700 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002701 // until there are no more pointers or pointers-to-members left to
2702 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002703 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002704
Douglas Gregor621c92a2011-04-25 18:40:17 +00002705 Qualifiers FromQuals = FromType.getQualifiers();
2706 Qualifiers ToQuals = ToType.getQualifiers();
2707
John McCallf85e1932011-06-15 23:02:42 +00002708 // Objective-C ARC:
2709 // Check Objective-C lifetime conversions.
2710 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2711 UnwrappedAnyPointer) {
2712 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2713 ObjCLifetimeConversion = true;
2714 FromQuals.removeObjCLifetime();
2715 ToQuals.removeObjCLifetime();
2716 } else {
2717 // Qualification conversions cannot cast between different
2718 // Objective-C lifetime qualifiers.
2719 return false;
2720 }
2721 }
2722
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002723 // Allow addition/removal of GC attributes but not changing GC attributes.
2724 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2725 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2726 FromQuals.removeObjCGCAttr();
2727 ToQuals.removeObjCGCAttr();
2728 }
2729
Douglas Gregor98cd5992008-10-21 23:43:52 +00002730 // -- for every j > 0, if const is in cv 1,j then const is in cv
2731 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002732 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002733 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Douglas Gregor98cd5992008-10-21 23:43:52 +00002735 // -- if the cv 1,j and cv 2,j are different, then const is in
2736 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002737 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002738 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002739 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Douglas Gregor98cd5992008-10-21 23:43:52 +00002741 // Keep track of whether all prior cv-qualifiers in the "to" type
2742 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002743 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002744 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002745 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002746
2747 // We are left with FromType and ToType being the pointee types
2748 // after unwrapping the original FromType and ToType the same number
2749 // of types. If we unwrapped any pointers, and if FromType and
2750 // ToType have the same unqualified type (since we checked
2751 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002752 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002753}
2754
Sebastian Redl56a04282012-02-11 23:51:08 +00002755static OverloadingResult
2756IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2757 CXXRecordDecl *To,
2758 UserDefinedConversionSequence &User,
2759 OverloadCandidateSet &CandidateSet,
2760 bool AllowExplicit) {
2761 DeclContext::lookup_iterator Con, ConEnd;
2762 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2763 Con != ConEnd; ++Con) {
2764 NamedDecl *D = *Con;
2765 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2766
2767 // Find the constructor (which may be a template).
2768 CXXConstructorDecl *Constructor = 0;
2769 FunctionTemplateDecl *ConstructorTmpl
2770 = dyn_cast<FunctionTemplateDecl>(D);
2771 if (ConstructorTmpl)
2772 Constructor
2773 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2774 else
2775 Constructor = cast<CXXConstructorDecl>(D);
2776
2777 bool Usable = !Constructor->isInvalidDecl() &&
2778 S.isInitListConstructor(Constructor) &&
2779 (AllowExplicit || !Constructor->isExplicit());
2780 if (Usable) {
2781 if (ConstructorTmpl)
2782 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2783 /*ExplicitArgs*/ 0,
2784 &From, 1, CandidateSet,
2785 /*SuppressUserConversions=*/true);
2786 else
2787 S.AddOverloadCandidate(Constructor, FoundDecl,
2788 &From, 1, CandidateSet,
2789 /*SuppressUserConversions=*/true);
2790 }
2791 }
2792
2793 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2794
2795 OverloadCandidateSet::iterator Best;
2796 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2797 case OR_Success: {
2798 // Record the standard conversion we used and the conversion function.
2799 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2800 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2801
2802 QualType ThisType = Constructor->getThisType(S.Context);
2803 // Initializer lists don't have conversions as such.
2804 User.Before.setAsIdentityConversion();
2805 User.HadMultipleCandidates = HadMultipleCandidates;
2806 User.ConversionFunction = Constructor;
2807 User.FoundConversionFunction = Best->FoundDecl;
2808 User.After.setAsIdentityConversion();
2809 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2810 User.After.setAllToTypes(ToType);
2811 return OR_Success;
2812 }
2813
2814 case OR_No_Viable_Function:
2815 return OR_No_Viable_Function;
2816 case OR_Deleted:
2817 return OR_Deleted;
2818 case OR_Ambiguous:
2819 return OR_Ambiguous;
2820 }
2821
2822 llvm_unreachable("Invalid OverloadResult!");
2823}
2824
Douglas Gregor734d9862009-01-30 23:27:23 +00002825/// Determines whether there is a user-defined conversion sequence
2826/// (C++ [over.ics.user]) that converts expression From to the type
2827/// ToType. If such a conversion exists, User will contain the
2828/// user-defined conversion sequence that performs such a conversion
2829/// and this routine will return true. Otherwise, this routine returns
2830/// false and User is unspecified.
2831///
Douglas Gregor734d9862009-01-30 23:27:23 +00002832/// \param AllowExplicit true if the conversion should consider C++0x
2833/// "explicit" conversion functions as well as non-explicit conversion
2834/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002835static OverloadingResult
2836IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002837 UserDefinedConversionSequence &User,
2838 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002839 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002840 // Whether we will only visit constructors.
2841 bool ConstructorsOnly = false;
2842
2843 // If the type we are conversion to is a class type, enumerate its
2844 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002845 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002846 // C++ [over.match.ctor]p1:
2847 // When objects of class type are direct-initialized (8.5), or
2848 // copy-initialized from an expression of the same or a
2849 // derived class type (8.5), overload resolution selects the
2850 // constructor. [...] For copy-initialization, the candidate
2851 // functions are all the converting constructors (12.3.1) of
2852 // that class. The argument list is the expression-list within
2853 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002854 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002855 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002856 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002857 ConstructorsOnly = true;
2858
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002859 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2860 // RequireCompleteType may have returned true due to some invalid decl
2861 // during template instantiation, but ToType may be complete enough now
2862 // to try to recover.
2863 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002864 // We're not going to find any constructors.
2865 } else if (CXXRecordDecl *ToRecordDecl
2866 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002867
2868 Expr **Args = &From;
2869 unsigned NumArgs = 1;
2870 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002871 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002872 // But first, see if there is an init-list-contructor that will work.
2873 OverloadingResult Result = IsInitializerListConstructorConversion(
2874 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2875 if (Result != OR_No_Viable_Function)
2876 return Result;
2877 // Never mind.
2878 CandidateSet.clear();
2879
2880 // If we're list-initializing, we pass the individual elements as
2881 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002882 Args = InitList->getInits();
2883 NumArgs = InitList->getNumInits();
2884 ListInitializing = true;
2885 }
2886
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002887 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002888 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002889 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002890 NamedDecl *D = *Con;
2891 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2892
Douglas Gregordec06662009-08-21 18:42:58 +00002893 // Find the constructor (which may be a template).
2894 CXXConstructorDecl *Constructor = 0;
2895 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002896 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002897 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002898 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002899 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2900 else
John McCall9aa472c2010-03-19 07:35:19 +00002901 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002903 bool Usable = !Constructor->isInvalidDecl();
2904 if (ListInitializing)
2905 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2906 else
2907 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2908 if (Usable) {
Douglas Gregordec06662009-08-21 18:42:58 +00002909 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002910 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2911 /*ExplicitArgs*/ 0,
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002912 Args, NumArgs, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002913 /*SuppressUserConversions=*/
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002914 !ConstructorsOnly &&
2915 !ListInitializing);
Douglas Gregordec06662009-08-21 18:42:58 +00002916 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002917 // Allow one user-defined conversion when user specifies a
2918 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002919 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002920 Args, NumArgs, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002921 /*SuppressUserConversions=*/
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002922 !ConstructorsOnly && !ListInitializing);
Douglas Gregordec06662009-08-21 18:42:58 +00002923 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002924 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002925 }
2926 }
2927
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002928 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002929 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall120d63c2010-08-24 20:38:10 +00002930 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2931 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002932 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002933 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002934 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002935 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002936 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2937 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002938 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002939 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002940 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002941 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002942 DeclAccessPair FoundDecl = I.getPair();
2943 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002944 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2945 if (isa<UsingShadowDecl>(D))
2946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2947
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002948 CXXConversionDecl *Conv;
2949 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002950 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2951 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002952 else
John McCall32daa422010-03-31 01:36:47 +00002953 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002954
2955 if (AllowExplicit || !Conv->isExplicit()) {
2956 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002957 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2958 ActingContext, From, ToType,
2959 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002960 else
John McCall120d63c2010-08-24 20:38:10 +00002961 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2962 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002963 }
2964 }
2965 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002966 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002967
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2969
Douglas Gregor60d62c22008-10-31 16:23:19 +00002970 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002971 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002972 case OR_Success:
2973 // Record the standard conversion we used and the conversion function.
2974 if (CXXConstructorDecl *Constructor
2975 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002976 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00002977
John McCall120d63c2010-08-24 20:38:10 +00002978 // C++ [over.ics.user]p1:
2979 // If the user-defined conversion is specified by a
2980 // constructor (12.3.1), the initial standard conversion
2981 // sequence converts the source type to the type required by
2982 // the argument of the constructor.
2983 //
2984 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002985 if (isa<InitListExpr>(From)) {
2986 // Initializer lists don't have conversions as such.
2987 User.Before.setAsIdentityConversion();
2988 } else {
2989 if (Best->Conversions[0].isEllipsis())
2990 User.EllipsisConversion = true;
2991 else {
2992 User.Before = Best->Conversions[0].Standard;
2993 User.EllipsisConversion = false;
2994 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002995 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002996 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002997 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00002998 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002999 User.After.setAsIdentityConversion();
3000 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3001 User.After.setAllToTypes(ToType);
3002 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003003 }
3004 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003005 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003006 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003007
John McCall120d63c2010-08-24 20:38:10 +00003008 // C++ [over.ics.user]p1:
3009 //
3010 // [...] If the user-defined conversion is specified by a
3011 // conversion function (12.3.2), the initial standard
3012 // conversion sequence converts the source type to the
3013 // implicit object parameter of the conversion function.
3014 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003015 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003016 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003017 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003018 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003019
John McCall120d63c2010-08-24 20:38:10 +00003020 // C++ [over.ics.user]p2:
3021 // The second standard conversion sequence converts the
3022 // result of the user-defined conversion to the target type
3023 // for the sequence. Since an implicit conversion sequence
3024 // is an initialization, the special rules for
3025 // initialization by user-defined conversion apply when
3026 // selecting the best user-defined conversion for a
3027 // user-defined conversion sequence (see 13.3.3 and
3028 // 13.3.3.1).
3029 User.After = Best->FinalConversion;
3030 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003031 }
David Blaikie7530c032012-01-17 06:56:22 +00003032 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003033
John McCall120d63c2010-08-24 20:38:10 +00003034 case OR_No_Viable_Function:
3035 return OR_No_Viable_Function;
3036 case OR_Deleted:
3037 // No conversion here! We're done.
3038 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039
John McCall120d63c2010-08-24 20:38:10 +00003040 case OR_Ambiguous:
3041 return OR_Ambiguous;
3042 }
3043
David Blaikie7530c032012-01-17 06:56:22 +00003044 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003045}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003047bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003048Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003049 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003050 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003051 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003052 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003053 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003054 if (OvResult == OR_Ambiguous)
3055 Diag(From->getSourceRange().getBegin(),
3056 diag::err_typecheck_ambiguous_condition)
3057 << From->getType() << ToType << From->getSourceRange();
3058 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3059 Diag(From->getSourceRange().getBegin(),
3060 diag::err_typecheck_nonviable_condition)
3061 << From->getType() << ToType << From->getSourceRange();
3062 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003063 return false;
John McCall120d63c2010-08-24 20:38:10 +00003064 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003065 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003066}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003067
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003068/// CompareImplicitConversionSequences - Compare two implicit
3069/// conversion sequences to determine whether one is better than the
3070/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003071static ImplicitConversionSequence::CompareKind
3072CompareImplicitConversionSequences(Sema &S,
3073 const ImplicitConversionSequence& ICS1,
3074 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003075{
3076 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3077 // conversion sequences (as defined in 13.3.3.1)
3078 // -- a standard conversion sequence (13.3.3.1.1) is a better
3079 // conversion sequence than a user-defined conversion sequence or
3080 // an ellipsis conversion sequence, and
3081 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3082 // conversion sequence than an ellipsis conversion sequence
3083 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003084 //
John McCall1d318332010-01-12 00:44:57 +00003085 // C++0x [over.best.ics]p10:
3086 // For the purpose of ranking implicit conversion sequences as
3087 // described in 13.3.3.2, the ambiguous conversion sequence is
3088 // treated as a user-defined sequence that is indistinguishable
3089 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003090 if (ICS1.getKindRank() < ICS2.getKindRank())
3091 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003092 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003093 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003094
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003095 // The following checks require both conversion sequences to be of
3096 // the same kind.
3097 if (ICS1.getKind() != ICS2.getKind())
3098 return ImplicitConversionSequence::Indistinguishable;
3099
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003100 ImplicitConversionSequence::CompareKind Result =
3101 ImplicitConversionSequence::Indistinguishable;
3102
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003103 // Two implicit conversion sequences of the same form are
3104 // indistinguishable conversion sequences unless one of the
3105 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003106 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003107 Result = CompareStandardConversionSequences(S,
3108 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003109 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003110 // User-defined conversion sequence U1 is a better conversion
3111 // sequence than another user-defined conversion sequence U2 if
3112 // they contain the same user-defined conversion function or
3113 // constructor and if the second standard conversion sequence of
3114 // U1 is better than the second standard conversion sequence of
3115 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003116 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003117 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003118 Result = CompareStandardConversionSequences(S,
3119 ICS1.UserDefined.After,
3120 ICS2.UserDefined.After);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003121 }
3122
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003123 // List-initialization sequence L1 is a better conversion sequence than
3124 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3125 // for some X and L2 does not.
3126 if (Result == ImplicitConversionSequence::Indistinguishable &&
3127 ICS1.isListInitializationSequence() &&
3128 ICS2.isListInitializationSequence()) {
3129 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
3130 }
3131
3132 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003133}
3134
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003135static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3136 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3137 Qualifiers Quals;
3138 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003139 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003141
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003142 return Context.hasSameUnqualifiedType(T1, T2);
3143}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003144
Douglas Gregorad323a82010-01-27 03:51:04 +00003145// Per 13.3.3.2p3, compare the given standard conversion sequences to
3146// determine if one is a proper subset of the other.
3147static ImplicitConversionSequence::CompareKind
3148compareStandardConversionSubsets(ASTContext &Context,
3149 const StandardConversionSequence& SCS1,
3150 const StandardConversionSequence& SCS2) {
3151 ImplicitConversionSequence::CompareKind Result
3152 = ImplicitConversionSequence::Indistinguishable;
3153
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003154 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003155 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003156 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3157 return ImplicitConversionSequence::Better;
3158 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3159 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003160
Douglas Gregorad323a82010-01-27 03:51:04 +00003161 if (SCS1.Second != SCS2.Second) {
3162 if (SCS1.Second == ICK_Identity)
3163 Result = ImplicitConversionSequence::Better;
3164 else if (SCS2.Second == ICK_Identity)
3165 Result = ImplicitConversionSequence::Worse;
3166 else
3167 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003168 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003169 return ImplicitConversionSequence::Indistinguishable;
3170
3171 if (SCS1.Third == SCS2.Third) {
3172 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3173 : ImplicitConversionSequence::Indistinguishable;
3174 }
3175
3176 if (SCS1.Third == ICK_Identity)
3177 return Result == ImplicitConversionSequence::Worse
3178 ? ImplicitConversionSequence::Indistinguishable
3179 : ImplicitConversionSequence::Better;
3180
3181 if (SCS2.Third == ICK_Identity)
3182 return Result == ImplicitConversionSequence::Better
3183 ? ImplicitConversionSequence::Indistinguishable
3184 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003185
Douglas Gregorad323a82010-01-27 03:51:04 +00003186 return ImplicitConversionSequence::Indistinguishable;
3187}
3188
Douglas Gregor440a4832011-01-26 14:52:12 +00003189/// \brief Determine whether one of the given reference bindings is better
3190/// than the other based on what kind of bindings they are.
3191static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3192 const StandardConversionSequence &SCS2) {
3193 // C++0x [over.ics.rank]p3b4:
3194 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3195 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003196 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003197 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003198 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003199 // reference*.
3200 //
3201 // FIXME: Rvalue references. We're going rogue with the above edits,
3202 // because the semantics in the current C++0x working paper (N3225 at the
3203 // time of this writing) break the standard definition of std::forward
3204 // and std::reference_wrapper when dealing with references to functions.
3205 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003206 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3207 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3208 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003209
Douglas Gregor440a4832011-01-26 14:52:12 +00003210 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3211 SCS2.IsLvalueReference) ||
3212 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3213 !SCS2.IsLvalueReference);
3214}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003216/// CompareStandardConversionSequences - Compare two standard
3217/// conversion sequences to determine whether one is better than the
3218/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003219static ImplicitConversionSequence::CompareKind
3220CompareStandardConversionSequences(Sema &S,
3221 const StandardConversionSequence& SCS1,
3222 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003223{
3224 // Standard conversion sequence S1 is a better conversion sequence
3225 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3226
3227 // -- S1 is a proper subsequence of S2 (comparing the conversion
3228 // sequences in the canonical form defined by 13.3.3.1.1,
3229 // excluding any Lvalue Transformation; the identity conversion
3230 // sequence is considered to be a subsequence of any
3231 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003232 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003233 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003234 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003235
3236 // -- the rank of S1 is better than the rank of S2 (by the rules
3237 // defined below), or, if not that,
3238 ImplicitConversionRank Rank1 = SCS1.getRank();
3239 ImplicitConversionRank Rank2 = SCS2.getRank();
3240 if (Rank1 < Rank2)
3241 return ImplicitConversionSequence::Better;
3242 else if (Rank2 < Rank1)
3243 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003244
Douglas Gregor57373262008-10-22 14:17:15 +00003245 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3246 // are indistinguishable unless one of the following rules
3247 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003248
Douglas Gregor57373262008-10-22 14:17:15 +00003249 // A conversion that is not a conversion of a pointer, or
3250 // pointer to member, to bool is better than another conversion
3251 // that is such a conversion.
3252 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3253 return SCS2.isPointerConversionToBool()
3254 ? ImplicitConversionSequence::Better
3255 : ImplicitConversionSequence::Worse;
3256
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003257 // C++ [over.ics.rank]p4b2:
3258 //
3259 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003260 // conversion of B* to A* is better than conversion of B* to
3261 // void*, and conversion of A* to void* is better than conversion
3262 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003263 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003264 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003265 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003266 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003267 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3268 // Exactly one of the conversion sequences is a conversion to
3269 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003270 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3271 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003272 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3273 // Neither conversion sequence converts to a void pointer; compare
3274 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003275 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003276 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003277 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003278 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3279 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003280 // Both conversion sequences are conversions to void
3281 // pointers. Compare the source types to determine if there's an
3282 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003283 QualType FromType1 = SCS1.getFromType();
3284 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003285
3286 // Adjust the types we're converting from via the array-to-pointer
3287 // conversion, if we need to.
3288 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003289 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003290 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003291 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003292
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003293 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3294 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003295
John McCall120d63c2010-08-24 20:38:10 +00003296 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003297 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003298 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003299 return ImplicitConversionSequence::Worse;
3300
3301 // Objective-C++: If one interface is more specific than the
3302 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003303 const ObjCObjectPointerType* FromObjCPtr1
3304 = FromType1->getAs<ObjCObjectPointerType>();
3305 const ObjCObjectPointerType* FromObjCPtr2
3306 = FromType2->getAs<ObjCObjectPointerType>();
3307 if (FromObjCPtr1 && FromObjCPtr2) {
3308 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3309 FromObjCPtr2);
3310 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3311 FromObjCPtr1);
3312 if (AssignLeft != AssignRight) {
3313 return AssignLeft? ImplicitConversionSequence::Better
3314 : ImplicitConversionSequence::Worse;
3315 }
Douglas Gregor01919692009-12-13 21:37:05 +00003316 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003317 }
Douglas Gregor57373262008-10-22 14:17:15 +00003318
3319 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3320 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003321 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003322 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003323 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003324
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003325 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003326 // Check for a better reference binding based on the kind of bindings.
3327 if (isBetterReferenceBindingKind(SCS1, SCS2))
3328 return ImplicitConversionSequence::Better;
3329 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3330 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003332 // C++ [over.ics.rank]p3b4:
3333 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3334 // which the references refer are the same type except for
3335 // top-level cv-qualifiers, and the type to which the reference
3336 // initialized by S2 refers is more cv-qualified than the type
3337 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003338 QualType T1 = SCS1.getToType(2);
3339 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003340 T1 = S.Context.getCanonicalType(T1);
3341 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003342 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003343 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3344 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003345 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003346 // Objective-C++ ARC: If the references refer to objects with different
3347 // lifetimes, prefer bindings that don't change lifetime.
3348 if (SCS1.ObjCLifetimeConversionBinding !=
3349 SCS2.ObjCLifetimeConversionBinding) {
3350 return SCS1.ObjCLifetimeConversionBinding
3351 ? ImplicitConversionSequence::Worse
3352 : ImplicitConversionSequence::Better;
3353 }
3354
Chandler Carruth6df868e2010-12-12 08:17:55 +00003355 // If the type is an array type, promote the element qualifiers to the
3356 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003357 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003358 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003359 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003360 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003361 if (T2.isMoreQualifiedThan(T1))
3362 return ImplicitConversionSequence::Better;
3363 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003364 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003365 }
3366 }
Douglas Gregor57373262008-10-22 14:17:15 +00003367
Francois Pichet1c98d622011-09-18 21:37:37 +00003368 // In Microsoft mode, prefer an integral conversion to a
3369 // floating-to-integral conversion if the integral conversion
3370 // is between types of the same size.
3371 // For example:
3372 // void f(float);
3373 // void f(int);
3374 // int main {
3375 // long a;
3376 // f(a);
3377 // }
3378 // Here, MSVC will call f(int) instead of generating a compile error
3379 // as clang will do in standard mode.
3380 if (S.getLangOptions().MicrosoftMode &&
3381 SCS1.Second == ICK_Integral_Conversion &&
3382 SCS2.Second == ICK_Floating_Integral &&
3383 S.Context.getTypeSize(SCS1.getFromType()) ==
3384 S.Context.getTypeSize(SCS1.getToType(2)))
3385 return ImplicitConversionSequence::Better;
3386
Douglas Gregor57373262008-10-22 14:17:15 +00003387 return ImplicitConversionSequence::Indistinguishable;
3388}
3389
3390/// CompareQualificationConversions - Compares two standard conversion
3391/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003392/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3393ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003394CompareQualificationConversions(Sema &S,
3395 const StandardConversionSequence& SCS1,
3396 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003397 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003398 // -- S1 and S2 differ only in their qualification conversion and
3399 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3400 // cv-qualification signature of type T1 is a proper subset of
3401 // the cv-qualification signature of type T2, and S1 is not the
3402 // deprecated string literal array-to-pointer conversion (4.2).
3403 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3404 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3405 return ImplicitConversionSequence::Indistinguishable;
3406
3407 // FIXME: the example in the standard doesn't use a qualification
3408 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003409 QualType T1 = SCS1.getToType(2);
3410 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003411 T1 = S.Context.getCanonicalType(T1);
3412 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003413 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003414 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3415 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003416
3417 // If the types are the same, we won't learn anything by unwrapped
3418 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003419 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003420 return ImplicitConversionSequence::Indistinguishable;
3421
Chandler Carruth28e318c2009-12-29 07:16:59 +00003422 // If the type is an array type, promote the element qualifiers to the type
3423 // for comparison.
3424 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003425 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003426 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003427 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003428
Mike Stump1eb44332009-09-09 15:08:12 +00003429 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003430 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003431
3432 // Objective-C++ ARC:
3433 // Prefer qualification conversions not involving a change in lifetime
3434 // to qualification conversions that do not change lifetime.
3435 if (SCS1.QualificationIncludesObjCLifetime !=
3436 SCS2.QualificationIncludesObjCLifetime) {
3437 Result = SCS1.QualificationIncludesObjCLifetime
3438 ? ImplicitConversionSequence::Worse
3439 : ImplicitConversionSequence::Better;
3440 }
3441
John McCall120d63c2010-08-24 20:38:10 +00003442 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003443 // Within each iteration of the loop, we check the qualifiers to
3444 // determine if this still looks like a qualification
3445 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003446 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003447 // until there are no more pointers or pointers-to-members left
3448 // to unwrap. This essentially mimics what
3449 // IsQualificationConversion does, but here we're checking for a
3450 // strict subset of qualifiers.
3451 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3452 // The qualifiers are the same, so this doesn't tell us anything
3453 // about how the sequences rank.
3454 ;
3455 else if (T2.isMoreQualifiedThan(T1)) {
3456 // T1 has fewer qualifiers, so it could be the better sequence.
3457 if (Result == ImplicitConversionSequence::Worse)
3458 // Neither has qualifiers that are a subset of the other's
3459 // qualifiers.
3460 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Douglas Gregor57373262008-10-22 14:17:15 +00003462 Result = ImplicitConversionSequence::Better;
3463 } else if (T1.isMoreQualifiedThan(T2)) {
3464 // T2 has fewer qualifiers, so it could be the better sequence.
3465 if (Result == ImplicitConversionSequence::Better)
3466 // Neither has qualifiers that are a subset of the other's
3467 // qualifiers.
3468 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Douglas Gregor57373262008-10-22 14:17:15 +00003470 Result = ImplicitConversionSequence::Worse;
3471 } else {
3472 // Qualifiers are disjoint.
3473 return ImplicitConversionSequence::Indistinguishable;
3474 }
3475
3476 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003477 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003478 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003479 }
3480
Douglas Gregor57373262008-10-22 14:17:15 +00003481 // Check that the winning standard conversion sequence isn't using
3482 // the deprecated string literal array to pointer conversion.
3483 switch (Result) {
3484 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003485 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003486 Result = ImplicitConversionSequence::Indistinguishable;
3487 break;
3488
3489 case ImplicitConversionSequence::Indistinguishable:
3490 break;
3491
3492 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003493 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003494 Result = ImplicitConversionSequence::Indistinguishable;
3495 break;
3496 }
3497
3498 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003499}
3500
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003501/// CompareDerivedToBaseConversions - Compares two standard conversion
3502/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003503/// various kinds of derived-to-base conversions (C++
3504/// [over.ics.rank]p4b3). As part of these checks, we also look at
3505/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003506ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003507CompareDerivedToBaseConversions(Sema &S,
3508 const StandardConversionSequence& SCS1,
3509 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003510 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003511 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003512 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003513 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003514
3515 // Adjust the types we're converting from via the array-to-pointer
3516 // conversion, if we need to.
3517 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003518 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003519 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003520 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003521
3522 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003523 FromType1 = S.Context.getCanonicalType(FromType1);
3524 ToType1 = S.Context.getCanonicalType(ToType1);
3525 FromType2 = S.Context.getCanonicalType(FromType2);
3526 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003527
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003528 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003529 //
3530 // If class B is derived directly or indirectly from class A and
3531 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003532 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003533 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003534 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003535 SCS2.Second == ICK_Pointer_Conversion &&
3536 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3537 FromType1->isPointerType() && FromType2->isPointerType() &&
3538 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003539 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003540 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003541 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003542 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003543 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003544 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003545 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003546 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003547
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003548 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003549 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003550 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003551 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003552 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003553 return ImplicitConversionSequence::Worse;
3554 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003555
3556 // -- conversion of B* to A* is better than conversion of C* to A*,
3557 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003558 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003559 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003560 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003561 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003562 }
3563 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3564 SCS2.Second == ICK_Pointer_Conversion) {
3565 const ObjCObjectPointerType *FromPtr1
3566 = FromType1->getAs<ObjCObjectPointerType>();
3567 const ObjCObjectPointerType *FromPtr2
3568 = FromType2->getAs<ObjCObjectPointerType>();
3569 const ObjCObjectPointerType *ToPtr1
3570 = ToType1->getAs<ObjCObjectPointerType>();
3571 const ObjCObjectPointerType *ToPtr2
3572 = ToType2->getAs<ObjCObjectPointerType>();
3573
3574 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3575 // Apply the same conversion ranking rules for Objective-C pointer types
3576 // that we do for C++ pointers to class types. However, we employ the
3577 // Objective-C pseudo-subtyping relationship used for assignment of
3578 // Objective-C pointer types.
3579 bool FromAssignLeft
3580 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3581 bool FromAssignRight
3582 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3583 bool ToAssignLeft
3584 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3585 bool ToAssignRight
3586 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3587
3588 // A conversion to an a non-id object pointer type or qualified 'id'
3589 // type is better than a conversion to 'id'.
3590 if (ToPtr1->isObjCIdType() &&
3591 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3592 return ImplicitConversionSequence::Worse;
3593 if (ToPtr2->isObjCIdType() &&
3594 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3595 return ImplicitConversionSequence::Better;
3596
3597 // A conversion to a non-id object pointer type is better than a
3598 // conversion to a qualified 'id' type
3599 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3600 return ImplicitConversionSequence::Worse;
3601 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3602 return ImplicitConversionSequence::Better;
3603
3604 // A conversion to an a non-Class object pointer type or qualified 'Class'
3605 // type is better than a conversion to 'Class'.
3606 if (ToPtr1->isObjCClassType() &&
3607 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3608 return ImplicitConversionSequence::Worse;
3609 if (ToPtr2->isObjCClassType() &&
3610 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3611 return ImplicitConversionSequence::Better;
3612
3613 // A conversion to a non-Class object pointer type is better than a
3614 // conversion to a qualified 'Class' type.
3615 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3616 return ImplicitConversionSequence::Worse;
3617 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3618 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Douglas Gregor395cc372011-01-31 18:51:41 +00003620 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3621 if (S.Context.hasSameType(FromType1, FromType2) &&
3622 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3623 (ToAssignLeft != ToAssignRight))
3624 return ToAssignLeft? ImplicitConversionSequence::Worse
3625 : ImplicitConversionSequence::Better;
3626
3627 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3628 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3629 (FromAssignLeft != FromAssignRight))
3630 return FromAssignLeft? ImplicitConversionSequence::Better
3631 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003632 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003633 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003634
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003635 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003636 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3637 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3638 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003639 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003640 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003641 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003642 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003643 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003644 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003645 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003646 ToType2->getAs<MemberPointerType>();
3647 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3648 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3649 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3650 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3651 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3652 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3653 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3654 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003655 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003656 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003657 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003658 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003659 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003660 return ImplicitConversionSequence::Better;
3661 }
3662 // conversion of B::* to C::* is better than conversion of A::* to C::*
3663 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003664 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003665 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003666 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003667 return ImplicitConversionSequence::Worse;
3668 }
3669 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003671 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003672 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003673 // -- binding of an expression of type C to a reference of type
3674 // B& is better than binding an expression of type C to a
3675 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003676 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3677 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3678 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003679 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003680 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003681 return ImplicitConversionSequence::Worse;
3682 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003683
Douglas Gregor225c41e2008-11-03 19:09:14 +00003684 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003685 // -- binding of an expression of type B to a reference of type
3686 // A& is better than binding an expression of type C to a
3687 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003688 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3689 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3690 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003691 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003692 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003693 return ImplicitConversionSequence::Worse;
3694 }
3695 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003696
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003697 return ImplicitConversionSequence::Indistinguishable;
3698}
3699
Douglas Gregorabe183d2010-04-13 16:31:36 +00003700/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3701/// determine whether they are reference-related,
3702/// reference-compatible, reference-compatible with added
3703/// qualification, or incompatible, for use in C++ initialization by
3704/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3705/// type, and the first type (T1) is the pointee type of the reference
3706/// type being initialized.
3707Sema::ReferenceCompareResult
3708Sema::CompareReferenceRelationship(SourceLocation Loc,
3709 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003710 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003711 bool &ObjCConversion,
3712 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003713 assert(!OrigT1->isReferenceType() &&
3714 "T1 must be the pointee type of the reference type");
3715 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3716
3717 QualType T1 = Context.getCanonicalType(OrigT1);
3718 QualType T2 = Context.getCanonicalType(OrigT2);
3719 Qualifiers T1Quals, T2Quals;
3720 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3721 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3722
3723 // C++ [dcl.init.ref]p4:
3724 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3725 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3726 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003727 DerivedToBase = false;
3728 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003729 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003730 if (UnqualT1 == UnqualT2) {
3731 // Nothing to do.
3732 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003733 IsDerivedFrom(UnqualT2, UnqualT1))
3734 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003735 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3736 UnqualT2->isObjCObjectOrInterfaceType() &&
3737 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3738 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003739 else
3740 return Ref_Incompatible;
3741
3742 // At this point, we know that T1 and T2 are reference-related (at
3743 // least).
3744
3745 // If the type is an array type, promote the element qualifiers to the type
3746 // for comparison.
3747 if (isa<ArrayType>(T1) && T1Quals)
3748 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3749 if (isa<ArrayType>(T2) && T2Quals)
3750 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3751
3752 // C++ [dcl.init.ref]p4:
3753 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3754 // reference-related to T2 and cv1 is the same cv-qualification
3755 // as, or greater cv-qualification than, cv2. For purposes of
3756 // overload resolution, cases for which cv1 is greater
3757 // cv-qualification than cv2 are identified as
3758 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003759 //
3760 // Note that we also require equivalence of Objective-C GC and address-space
3761 // qualifiers when performing these computations, so that e.g., an int in
3762 // address space 1 is not reference-compatible with an int in address
3763 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003764 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3765 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3766 T1Quals.removeObjCLifetime();
3767 T2Quals.removeObjCLifetime();
3768 ObjCLifetimeConversion = true;
3769 }
3770
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003771 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003772 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003773 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003774 return Ref_Compatible_With_Added_Qualification;
3775 else
3776 return Ref_Related;
3777}
3778
Douglas Gregor604eb652010-08-11 02:15:33 +00003779/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003780/// with DeclType. Return true if something definite is found.
3781static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003782FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3783 QualType DeclType, SourceLocation DeclLoc,
3784 Expr *Init, QualType T2, bool AllowRvalues,
3785 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003786 assert(T2->isRecordType() && "Can only find conversions of record types.");
3787 CXXRecordDecl *T2RecordDecl
3788 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3789
3790 OverloadCandidateSet CandidateSet(DeclLoc);
3791 const UnresolvedSetImpl *Conversions
3792 = T2RecordDecl->getVisibleConversionFunctions();
3793 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3794 E = Conversions->end(); I != E; ++I) {
3795 NamedDecl *D = *I;
3796 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3797 if (isa<UsingShadowDecl>(D))
3798 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3799
3800 FunctionTemplateDecl *ConvTemplate
3801 = dyn_cast<FunctionTemplateDecl>(D);
3802 CXXConversionDecl *Conv;
3803 if (ConvTemplate)
3804 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3805 else
3806 Conv = cast<CXXConversionDecl>(D);
3807
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003808 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003809 // explicit conversions, skip it.
3810 if (!AllowExplicit && Conv->isExplicit())
3811 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003812
Douglas Gregor604eb652010-08-11 02:15:33 +00003813 if (AllowRvalues) {
3814 bool DerivedToBase = false;
3815 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003816 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003817
3818 // If we are initializing an rvalue reference, don't permit conversion
3819 // functions that return lvalues.
3820 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3821 const ReferenceType *RefType
3822 = Conv->getConversionType()->getAs<LValueReferenceType>();
3823 if (RefType && !RefType->getPointeeType()->isFunctionType())
3824 continue;
3825 }
3826
Douglas Gregor604eb652010-08-11 02:15:33 +00003827 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003828 S.CompareReferenceRelationship(
3829 DeclLoc,
3830 Conv->getConversionType().getNonReferenceType()
3831 .getUnqualifiedType(),
3832 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003833 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003834 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003835 continue;
3836 } else {
3837 // If the conversion function doesn't return a reference type,
3838 // it can't be considered for this conversion. An rvalue reference
3839 // is only acceptable if its referencee is a function type.
3840
3841 const ReferenceType *RefType =
3842 Conv->getConversionType()->getAs<ReferenceType>();
3843 if (!RefType ||
3844 (!RefType->isLValueReferenceType() &&
3845 !RefType->getPointeeType()->isFunctionType()))
3846 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003847 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003848
Douglas Gregor604eb652010-08-11 02:15:33 +00003849 if (ConvTemplate)
3850 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003851 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003852 else
3853 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003854 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003855 }
3856
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003857 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3858
Sebastian Redl4680bf22010-06-30 18:13:39 +00003859 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003860 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003861 case OR_Success:
3862 // C++ [over.ics.ref]p1:
3863 //
3864 // [...] If the parameter binds directly to the result of
3865 // applying a conversion function to the argument
3866 // expression, the implicit conversion sequence is a
3867 // user-defined conversion sequence (13.3.3.1.2), with the
3868 // second standard conversion sequence either an identity
3869 // conversion or, if the conversion function returns an
3870 // entity of a type that is a derived class of the parameter
3871 // type, a derived-to-base Conversion.
3872 if (!Best->FinalConversion.DirectBinding)
3873 return false;
3874
Chandler Carruth25ca4212011-02-25 19:41:05 +00003875 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003876 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003877 ICS.setUserDefined();
3878 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3879 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003880 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003881 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00003882 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003883 ICS.UserDefined.EllipsisConversion = false;
3884 assert(ICS.UserDefined.After.ReferenceBinding &&
3885 ICS.UserDefined.After.DirectBinding &&
3886 "Expected a direct reference binding!");
3887 return true;
3888
3889 case OR_Ambiguous:
3890 ICS.setAmbiguous();
3891 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3892 Cand != CandidateSet.end(); ++Cand)
3893 if (Cand->Viable)
3894 ICS.Ambiguous.addConversion(Cand->Function);
3895 return true;
3896
3897 case OR_No_Viable_Function:
3898 case OR_Deleted:
3899 // There was no suitable conversion, or we found a deleted
3900 // conversion; continue with other checks.
3901 return false;
3902 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003903
David Blaikie7530c032012-01-17 06:56:22 +00003904 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00003905}
3906
Douglas Gregorabe183d2010-04-13 16:31:36 +00003907/// \brief Compute an implicit conversion sequence for reference
3908/// initialization.
3909static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00003910TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003911 SourceLocation DeclLoc,
3912 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003913 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003914 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3915
3916 // Most paths end in a failed conversion.
3917 ImplicitConversionSequence ICS;
3918 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3919
3920 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3921 QualType T2 = Init->getType();
3922
3923 // If the initializer is the address of an overloaded function, try
3924 // to resolve the overloaded function. If all goes well, T2 is the
3925 // type of the resulting function.
3926 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3927 DeclAccessPair Found;
3928 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3929 false, Found))
3930 T2 = Fn->getType();
3931 }
3932
3933 // Compute some basic properties of the types and the initializer.
3934 bool isRValRef = DeclType->isRValueReferenceType();
3935 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003936 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003937 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003938 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003939 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003940 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003941 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003942
Douglas Gregorabe183d2010-04-13 16:31:36 +00003943
Sebastian Redl4680bf22010-06-30 18:13:39 +00003944 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003945 // A reference to type "cv1 T1" is initialized by an expression
3946 // of type "cv2 T2" as follows:
3947
Sebastian Redl4680bf22010-06-30 18:13:39 +00003948 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003949 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003950 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3951 // reference-compatible with "cv2 T2," or
3952 //
3953 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3954 if (InitCategory.isLValue() &&
3955 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003956 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003957 // When a parameter of reference type binds directly (8.5.3)
3958 // to an argument expression, the implicit conversion sequence
3959 // is the identity conversion, unless the argument expression
3960 // has a type that is a derived class of the parameter type,
3961 // in which case the implicit conversion sequence is a
3962 // derived-to-base Conversion (13.3.3.1).
3963 ICS.setStandard();
3964 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00003965 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3966 : ObjCConversion? ICK_Compatible_Conversion
3967 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003968 ICS.Standard.Third = ICK_Identity;
3969 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3970 ICS.Standard.setToType(0, T2);
3971 ICS.Standard.setToType(1, T1);
3972 ICS.Standard.setToType(2, T1);
3973 ICS.Standard.ReferenceBinding = true;
3974 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003975 ICS.Standard.IsLvalueReference = !isRValRef;
3976 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3977 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003978 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003979 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003980 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003981
Sebastian Redl4680bf22010-06-30 18:13:39 +00003982 // Nothing more to do: the inaccessibility/ambiguity check for
3983 // derived-to-base conversions is suppressed when we're
3984 // computing the implicit conversion sequence (C++
3985 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003986 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003987 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003988
Sebastian Redl4680bf22010-06-30 18:13:39 +00003989 // -- has a class type (i.e., T2 is a class type), where T1 is
3990 // not reference-related to T2, and can be implicitly
3991 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3992 // is reference-compatible with "cv3 T3" 92) (this
3993 // conversion is selected by enumerating the applicable
3994 // conversion functions (13.3.1.6) and choosing the best
3995 // one through overload resolution (13.3)),
3996 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003997 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003998 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003999 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4000 Init, T2, /*AllowRvalues=*/false,
4001 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004002 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004003 }
4004 }
4005
Sebastian Redl4680bf22010-06-30 18:13:39 +00004006 // -- Otherwise, the reference shall be an lvalue reference to a
4007 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004008 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004009 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004010 // We actually handle one oddity of C++ [over.ics.ref] at this
4011 // point, which is that, due to p2 (which short-circuits reference
4012 // binding by only attempting a simple conversion for non-direct
4013 // bindings) and p3's strange wording, we allow a const volatile
4014 // reference to bind to an rvalue. Hence the check for the presence
4015 // of "const" rather than checking for "const" being the only
4016 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004017 // This is also the point where rvalue references and lvalue inits no longer
4018 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004019 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00004020 return ICS;
4021
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004022 // -- If the initializer expression
4023 //
4024 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004025 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004026 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4027 (InitCategory.isXValue() ||
4028 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4029 (InitCategory.isLValue() && T2->isFunctionType()))) {
4030 ICS.setStandard();
4031 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004032 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004033 : ObjCConversion? ICK_Compatible_Conversion
4034 : ICK_Identity;
4035 ICS.Standard.Third = ICK_Identity;
4036 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4037 ICS.Standard.setToType(0, T2);
4038 ICS.Standard.setToType(1, T1);
4039 ICS.Standard.setToType(2, T1);
4040 ICS.Standard.ReferenceBinding = true;
4041 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4042 // binding unless we're binding to a class prvalue.
4043 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4044 // allow the use of rvalue references in C++98/03 for the benefit of
4045 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004046 ICS.Standard.DirectBinding =
4047 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004048 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004049 ICS.Standard.IsLvalueReference = !isRValRef;
4050 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004051 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004052 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004053 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004054 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004055 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004056 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004057
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004058 // -- has a class type (i.e., T2 is a class type), where T1 is not
4059 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004060 // an xvalue, class prvalue, or function lvalue of type
4061 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004062 // "cv3 T3",
4063 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004065 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004066 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004067 // class subobject).
4068 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004069 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004070 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4071 Init, T2, /*AllowRvalues=*/true,
4072 AllowExplicit)) {
4073 // In the second case, if the reference is an rvalue reference
4074 // and the second standard conversion sequence of the
4075 // user-defined conversion sequence includes an lvalue-to-rvalue
4076 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004077 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004078 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4079 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4080
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004081 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004082 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004083
Douglas Gregorabe183d2010-04-13 16:31:36 +00004084 // -- Otherwise, a temporary of type "cv1 T1" is created and
4085 // initialized from the initializer expression using the
4086 // rules for a non-reference copy initialization (8.5). The
4087 // reference is then bound to the temporary. If T1 is
4088 // reference-related to T2, cv1 must be the same
4089 // cv-qualification as, or greater cv-qualification than,
4090 // cv2; otherwise, the program is ill-formed.
4091 if (RefRelationship == Sema::Ref_Related) {
4092 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4093 // we would be reference-compatible or reference-compatible with
4094 // added qualification. But that wasn't the case, so the reference
4095 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004096 //
4097 // Note that we only want to check address spaces and cvr-qualifiers here.
4098 // ObjC GC and lifetime qualifiers aren't important.
4099 Qualifiers T1Quals = T1.getQualifiers();
4100 Qualifiers T2Quals = T2.getQualifiers();
4101 T1Quals.removeObjCGCAttr();
4102 T1Quals.removeObjCLifetime();
4103 T2Quals.removeObjCGCAttr();
4104 T2Quals.removeObjCLifetime();
4105 if (!T1Quals.compatiblyIncludes(T2Quals))
4106 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004107 }
4108
4109 // If at least one of the types is a class type, the types are not
4110 // related, and we aren't allowed any user conversions, the
4111 // reference binding fails. This case is important for breaking
4112 // recursion, since TryImplicitConversion below will attempt to
4113 // create a temporary through the use of a copy constructor.
4114 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4115 (T1->isRecordType() || T2->isRecordType()))
4116 return ICS;
4117
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004118 // If T1 is reference-related to T2 and the reference is an rvalue
4119 // reference, the initializer expression shall not be an lvalue.
4120 if (RefRelationship >= Sema::Ref_Related &&
4121 isRValRef && Init->Classify(S.Context).isLValue())
4122 return ICS;
4123
Douglas Gregorabe183d2010-04-13 16:31:36 +00004124 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004125 // When a parameter of reference type is not bound directly to
4126 // an argument expression, the conversion sequence is the one
4127 // required to convert the argument expression to the
4128 // underlying type of the reference according to
4129 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4130 // to copy-initializing a temporary of the underlying type with
4131 // the argument expression. Any difference in top-level
4132 // cv-qualification is subsumed by the initialization itself
4133 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004134 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4135 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004136 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004137 /*CStyle=*/false,
4138 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004139
4140 // Of course, that's still a reference binding.
4141 if (ICS.isStandard()) {
4142 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004143 ICS.Standard.IsLvalueReference = !isRValRef;
4144 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4145 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004146 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004147 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004148 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004149 // Don't allow rvalue references to bind to lvalues.
4150 if (DeclType->isRValueReferenceType()) {
4151 if (const ReferenceType *RefType
4152 = ICS.UserDefined.ConversionFunction->getResultType()
4153 ->getAs<LValueReferenceType>()) {
4154 if (!RefType->getPointeeType()->isFunctionType()) {
4155 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4156 DeclType);
4157 return ICS;
4158 }
4159 }
4160 }
4161
Douglas Gregorabe183d2010-04-13 16:31:36 +00004162 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004163 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4164 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4165 ICS.UserDefined.After.BindsToRvalue = true;
4166 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4167 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004168 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004169
Douglas Gregorabe183d2010-04-13 16:31:36 +00004170 return ICS;
4171}
4172
Sebastian Redl5405b812011-10-16 18:19:34 +00004173static ImplicitConversionSequence
4174TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4175 bool SuppressUserConversions,
4176 bool InOverloadResolution,
4177 bool AllowObjCWritebackConversion);
4178
4179/// TryListConversion - Try to copy-initialize a value of type ToType from the
4180/// initializer list From.
4181static ImplicitConversionSequence
4182TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4183 bool SuppressUserConversions,
4184 bool InOverloadResolution,
4185 bool AllowObjCWritebackConversion) {
4186 // C++11 [over.ics.list]p1:
4187 // When an argument is an initializer list, it is not an expression and
4188 // special rules apply for converting it to a parameter type.
4189
4190 ImplicitConversionSequence Result;
4191 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004192 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004193
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004194 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004195 // initialized from init lists.
4196 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4197 return Result;
4198
Sebastian Redl5405b812011-10-16 18:19:34 +00004199 // C++11 [over.ics.list]p2:
4200 // If the parameter type is std::initializer_list<X> or "array of X" and
4201 // all the elements can be implicitly converted to X, the implicit
4202 // conversion sequence is the worst conversion necessary to convert an
4203 // element of the list to X.
Sebastian Redlfe592282012-01-17 22:49:48 +00004204 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004205 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004206 X = S.Context.getBaseElementType(ToType);
4207 else
4208 (void)S.isStdInitializerList(ToType, &X);
4209 if (!X.isNull()) {
4210 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4211 Expr *Init = From->getInit(i);
4212 ImplicitConversionSequence ICS =
4213 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4214 InOverloadResolution,
4215 AllowObjCWritebackConversion);
4216 // If a single element isn't convertible, fail.
4217 if (ICS.isBad()) {
4218 Result = ICS;
4219 break;
4220 }
4221 // Otherwise, look for the worst conversion.
4222 if (Result.isBad() ||
4223 CompareImplicitConversionSequences(S, ICS, Result) ==
4224 ImplicitConversionSequence::Worse)
4225 Result = ICS;
4226 }
4227 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004228 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004229 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004230
4231 // C++11 [over.ics.list]p3:
4232 // Otherwise, if the parameter is a non-aggregate class X and overload
4233 // resolution chooses a single best constructor [...] the implicit
4234 // conversion sequence is a user-defined conversion sequence. If multiple
4235 // constructors are viable but none is better than the others, the
4236 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004237 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4238 // This function can deal with initializer lists.
4239 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4240 /*AllowExplicit=*/false,
4241 InOverloadResolution, /*CStyle=*/false,
4242 AllowObjCWritebackConversion);
4243 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004244 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004245 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004246
4247 // C++11 [over.ics.list]p4:
4248 // Otherwise, if the parameter has an aggregate type which can be
4249 // initialized from the initializer list [...] the implicit conversion
4250 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004251 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004252 // Type is an aggregate, argument is an init list. At this point it comes
4253 // down to checking whether the initialization works.
4254 // FIXME: Find out whether this parameter is consumed or not.
4255 InitializedEntity Entity =
4256 InitializedEntity::InitializeParameter(S.Context, ToType,
4257 /*Consumed=*/false);
4258 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4259 Result.setUserDefined();
4260 Result.UserDefined.Before.setAsIdentityConversion();
4261 // Initializer lists don't have a type.
4262 Result.UserDefined.Before.setFromType(QualType());
4263 Result.UserDefined.Before.setAllToTypes(QualType());
4264
4265 Result.UserDefined.After.setAsIdentityConversion();
4266 Result.UserDefined.After.setFromType(ToType);
4267 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004268 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004269 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004270 return Result;
4271 }
4272
4273 // C++11 [over.ics.list]p5:
4274 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004275 if (ToType->isReferenceType()) {
4276 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4277 // mention initializer lists in any way. So we go by what list-
4278 // initialization would do and try to extrapolate from that.
4279
4280 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4281
4282 // If the initializer list has a single element that is reference-related
4283 // to the parameter type, we initialize the reference from that.
4284 if (From->getNumInits() == 1) {
4285 Expr *Init = From->getInit(0);
4286
4287 QualType T2 = Init->getType();
4288
4289 // If the initializer is the address of an overloaded function, try
4290 // to resolve the overloaded function. If all goes well, T2 is the
4291 // type of the resulting function.
4292 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4293 DeclAccessPair Found;
4294 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4295 Init, ToType, false, Found))
4296 T2 = Fn->getType();
4297 }
4298
4299 // Compute some basic properties of the types and the initializer.
4300 bool dummy1 = false;
4301 bool dummy2 = false;
4302 bool dummy3 = false;
4303 Sema::ReferenceCompareResult RefRelationship
4304 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4305 dummy2, dummy3);
4306
4307 if (RefRelationship >= Sema::Ref_Related)
4308 return TryReferenceInit(S, Init, ToType,
4309 /*FIXME:*/From->getLocStart(),
4310 SuppressUserConversions,
4311 /*AllowExplicit=*/false);
4312 }
4313
4314 // Otherwise, we bind the reference to a temporary created from the
4315 // initializer list.
4316 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4317 InOverloadResolution,
4318 AllowObjCWritebackConversion);
4319 if (Result.isFailure())
4320 return Result;
4321 assert(!Result.isEllipsis() &&
4322 "Sub-initialization cannot result in ellipsis conversion.");
4323
4324 // Can we even bind to a temporary?
4325 if (ToType->isRValueReferenceType() ||
4326 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4327 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4328 Result.UserDefined.After;
4329 SCS.ReferenceBinding = true;
4330 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4331 SCS.BindsToRvalue = true;
4332 SCS.BindsToFunctionLvalue = false;
4333 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4334 SCS.ObjCLifetimeConversionBinding = false;
4335 } else
4336 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4337 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004338 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004339 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004340
4341 // C++11 [over.ics.list]p6:
4342 // Otherwise, if the parameter type is not a class:
4343 if (!ToType->isRecordType()) {
4344 // - if the initializer list has one element, the implicit conversion
4345 // sequence is the one required to convert the element to the
4346 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004347 unsigned NumInits = From->getNumInits();
4348 if (NumInits == 1)
4349 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4350 SuppressUserConversions,
4351 InOverloadResolution,
4352 AllowObjCWritebackConversion);
4353 // - if the initializer list has no elements, the implicit conversion
4354 // sequence is the identity conversion.
4355 else if (NumInits == 0) {
4356 Result.setStandard();
4357 Result.Standard.setAsIdentityConversion();
4358 }
4359 return Result;
4360 }
4361
4362 // C++11 [over.ics.list]p7:
4363 // In all cases other than those enumerated above, no conversion is possible
4364 return Result;
4365}
4366
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004367/// TryCopyInitialization - Try to copy-initialize a value of type
4368/// ToType from the expression From. Return the implicit conversion
4369/// sequence required to pass this argument, which may be a bad
4370/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004371/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004372/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004373static ImplicitConversionSequence
4374TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004375 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004376 bool InOverloadResolution,
4377 bool AllowObjCWritebackConversion) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004378 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4379 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4380 InOverloadResolution,AllowObjCWritebackConversion);
4381
Douglas Gregorabe183d2010-04-13 16:31:36 +00004382 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004383 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004384 /*FIXME:*/From->getLocStart(),
4385 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004386 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004387
John McCall120d63c2010-08-24 20:38:10 +00004388 return TryImplicitConversion(S, From, ToType,
4389 SuppressUserConversions,
4390 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004391 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004392 /*CStyle=*/false,
4393 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004394}
4395
Anna Zaksf3546ee2011-07-28 19:46:48 +00004396static bool TryCopyInitialization(const CanQualType FromQTy,
4397 const CanQualType ToQTy,
4398 Sema &S,
4399 SourceLocation Loc,
4400 ExprValueKind FromVK) {
4401 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4402 ImplicitConversionSequence ICS =
4403 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4404
4405 return !ICS.isBad();
4406}
4407
Douglas Gregor96176b32008-11-18 23:14:02 +00004408/// TryObjectArgumentInitialization - Try to initialize the object
4409/// parameter of the given member function (@c Method) from the
4410/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004411static ImplicitConversionSequence
4412TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004413 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004414 CXXMethodDecl *Method,
4415 CXXRecordDecl *ActingContext) {
4416 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004417 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4418 // const volatile object.
4419 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4420 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004421 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004422
4423 // Set up the conversion sequence as a "bad" conversion, to allow us
4424 // to exit early.
4425 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004426
4427 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004428 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004429 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004430 FromType = PT->getPointeeType();
4431
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004432 // When we had a pointer, it's implicitly dereferenced, so we
4433 // better have an lvalue.
4434 assert(FromClassification.isLValue());
4435 }
4436
Anders Carlssona552f7c2009-05-01 18:34:30 +00004437 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004438
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004439 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004440 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004441 // parameter is
4442 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004443 // - "lvalue reference to cv X" for functions declared without a
4444 // ref-qualifier or with the & ref-qualifier
4445 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004446 // ref-qualifier
4447 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004448 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004449 // cv-qualification on the member function declaration.
4450 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004452 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004453 // (C++ [over.match.funcs]p5). We perform a simplified version of
4454 // reference binding here, that allows class rvalues to bind to
4455 // non-constant references.
4456
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004457 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004458 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004459 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004460 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004461 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004462 ICS.setBad(BadConversionSequence::bad_qualifiers,
4463 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004464 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004465 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004466
4467 // Check that we have either the same type or a derived type. It
4468 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004469 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004470 ImplicitConversionKind SecondKind;
4471 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4472 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004473 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004474 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004475 else {
John McCallb1bdc622010-02-25 01:37:24 +00004476 ICS.setBad(BadConversionSequence::unrelated_class,
4477 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004478 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004479 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004480
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004481 // Check the ref-qualifier.
4482 switch (Method->getRefQualifier()) {
4483 case RQ_None:
4484 // Do nothing; we don't care about lvalueness or rvalueness.
4485 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004486
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004487 case RQ_LValue:
4488 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4489 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004490 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004491 ImplicitParamType);
4492 return ICS;
4493 }
4494 break;
4495
4496 case RQ_RValue:
4497 if (!FromClassification.isRValue()) {
4498 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004500 ImplicitParamType);
4501 return ICS;
4502 }
4503 break;
4504 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004505
Douglas Gregor96176b32008-11-18 23:14:02 +00004506 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004507 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004508 ICS.Standard.setAsIdentityConversion();
4509 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004510 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004511 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004512 ICS.Standard.ReferenceBinding = true;
4513 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004514 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004515 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004516 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4517 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4518 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004519 return ICS;
4520}
4521
4522/// PerformObjectArgumentInitialization - Perform initialization of
4523/// the implicit object parameter for the given Method with the given
4524/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004525ExprResult
4526Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004527 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004528 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004529 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004530 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004531 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004532 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004534 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004535 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004536 FromRecordType = PT->getPointeeType();
4537 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004538 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004539 } else {
4540 FromRecordType = From->getType();
4541 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004542 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004543 }
4544
John McCall701c89e2009-12-03 04:06:58 +00004545 // Note that we always use the true parent context when performing
4546 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004547 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004548 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4549 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004550 if (ICS.isBad()) {
4551 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4552 Qualifiers FromQs = FromRecordType.getQualifiers();
4553 Qualifiers ToQs = DestType.getQualifiers();
4554 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4555 if (CVR) {
4556 Diag(From->getSourceRange().getBegin(),
4557 diag::err_member_function_call_bad_cvr)
4558 << Method->getDeclName() << FromRecordType << (CVR - 1)
4559 << From->getSourceRange();
4560 Diag(Method->getLocation(), diag::note_previous_decl)
4561 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004562 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004563 }
4564 }
4565
Douglas Gregor96176b32008-11-18 23:14:02 +00004566 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004567 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004568 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004569 }
Mike Stump1eb44332009-09-09 15:08:12 +00004570
John Wiegley429bb272011-04-08 18:41:53 +00004571 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4572 ExprResult FromRes =
4573 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4574 if (FromRes.isInvalid())
4575 return ExprError();
4576 From = FromRes.take();
4577 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004578
Douglas Gregor5fccd362010-03-03 23:55:11 +00004579 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004580 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004581 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004582 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004583}
4584
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004585/// TryContextuallyConvertToBool - Attempt to contextually convert the
4586/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004587static ImplicitConversionSequence
4588TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004589 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004590 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004591 // FIXME: Are these flags correct?
4592 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004593 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004594 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004595 /*CStyle=*/false,
4596 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004597}
4598
4599/// PerformContextuallyConvertToBool - Perform a contextual conversion
4600/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004601ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004602 if (checkPlaceholderForOverload(*this, From))
4603 return ExprError();
4604
John McCall120d63c2010-08-24 20:38:10 +00004605 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004606 if (!ICS.isBad())
4607 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004608
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004609 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00004610 return Diag(From->getSourceRange().getBegin(),
4611 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004612 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004613 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004614}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004615
Richard Smith8ef7b202012-01-18 23:55:52 +00004616/// Check that the specified conversion is permitted in a converted constant
4617/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4618/// is acceptable.
4619static bool CheckConvertedConstantConversions(Sema &S,
4620 StandardConversionSequence &SCS) {
4621 // Since we know that the target type is an integral or unscoped enumeration
4622 // type, most conversion kinds are impossible. All possible First and Third
4623 // conversions are fine.
4624 switch (SCS.Second) {
4625 case ICK_Identity:
4626 case ICK_Integral_Promotion:
4627 case ICK_Integral_Conversion:
4628 return true;
4629
4630 case ICK_Boolean_Conversion:
4631 // Conversion from an integral or unscoped enumeration type to bool is
4632 // classified as ICK_Boolean_Conversion, but it's also an integral
4633 // conversion, so it's permitted in a converted constant expression.
4634 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4635 SCS.getToType(2)->isBooleanType();
4636
4637 case ICK_Floating_Integral:
4638 case ICK_Complex_Real:
4639 return false;
4640
4641 case ICK_Lvalue_To_Rvalue:
4642 case ICK_Array_To_Pointer:
4643 case ICK_Function_To_Pointer:
4644 case ICK_NoReturn_Adjustment:
4645 case ICK_Qualification:
4646 case ICK_Compatible_Conversion:
4647 case ICK_Vector_Conversion:
4648 case ICK_Vector_Splat:
4649 case ICK_Derived_To_Base:
4650 case ICK_Pointer_Conversion:
4651 case ICK_Pointer_Member:
4652 case ICK_Block_Pointer_Conversion:
4653 case ICK_Writeback_Conversion:
4654 case ICK_Floating_Promotion:
4655 case ICK_Complex_Promotion:
4656 case ICK_Complex_Conversion:
4657 case ICK_Floating_Conversion:
4658 case ICK_TransparentUnionConversion:
4659 llvm_unreachable("unexpected second conversion kind");
4660
4661 case ICK_Num_Conversion_Kinds:
4662 break;
4663 }
4664
4665 llvm_unreachable("unknown conversion kind");
4666}
4667
4668/// CheckConvertedConstantExpression - Check that the expression From is a
4669/// converted constant expression of type T, perform the conversion and produce
4670/// the converted expression, per C++11 [expr.const]p3.
4671ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4672 llvm::APSInt &Value,
4673 CCEKind CCE) {
4674 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4675 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4676
4677 if (checkPlaceholderForOverload(*this, From))
4678 return ExprError();
4679
4680 // C++11 [expr.const]p3 with proposed wording fixes:
4681 // A converted constant expression of type T is a core constant expression,
4682 // implicitly converted to a prvalue of type T, where the converted
4683 // expression is a literal constant expression and the implicit conversion
4684 // sequence contains only user-defined conversions, lvalue-to-rvalue
4685 // conversions, integral promotions, and integral conversions other than
4686 // narrowing conversions.
4687 ImplicitConversionSequence ICS =
4688 TryImplicitConversion(From, T,
4689 /*SuppressUserConversions=*/false,
4690 /*AllowExplicit=*/false,
4691 /*InOverloadResolution=*/false,
4692 /*CStyle=*/false,
4693 /*AllowObjcWritebackConversion=*/false);
4694 StandardConversionSequence *SCS = 0;
4695 switch (ICS.getKind()) {
4696 case ImplicitConversionSequence::StandardConversion:
4697 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4698 return Diag(From->getSourceRange().getBegin(),
4699 diag::err_typecheck_converted_constant_expression_disallowed)
4700 << From->getType() << From->getSourceRange() << T;
4701 SCS = &ICS.Standard;
4702 break;
4703 case ImplicitConversionSequence::UserDefinedConversion:
4704 // We are converting from class type to an integral or enumeration type, so
4705 // the Before sequence must be trivial.
4706 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4707 return Diag(From->getSourceRange().getBegin(),
4708 diag::err_typecheck_converted_constant_expression_disallowed)
4709 << From->getType() << From->getSourceRange() << T;
4710 SCS = &ICS.UserDefined.After;
4711 break;
4712 case ImplicitConversionSequence::AmbiguousConversion:
4713 case ImplicitConversionSequence::BadConversion:
4714 if (!DiagnoseMultipleUserDefinedConversion(From, T))
4715 return Diag(From->getSourceRange().getBegin(),
4716 diag::err_typecheck_converted_constant_expression)
4717 << From->getType() << From->getSourceRange() << T;
4718 return ExprError();
4719
4720 case ImplicitConversionSequence::EllipsisConversion:
4721 llvm_unreachable("ellipsis conversion in converted constant expression");
4722 }
4723
4724 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4725 if (Result.isInvalid())
4726 return Result;
4727
4728 // Check for a narrowing implicit conversion.
4729 APValue PreNarrowingValue;
Richard Smithf72fccf2012-01-30 22:27:01 +00004730 bool Diagnosed = false;
Richard Smith8ef7b202012-01-18 23:55:52 +00004731 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue)) {
4732 case NK_Variable_Narrowing:
4733 // Implicit conversion to a narrower type, and the value is not a constant
4734 // expression. We'll diagnose this in a moment.
4735 case NK_Not_Narrowing:
4736 break;
4737
4738 case NK_Constant_Narrowing:
4739 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4740 << CCE << /*Constant*/1
4741 << PreNarrowingValue.getAsString(Context, QualType()) << T;
Richard Smithf72fccf2012-01-30 22:27:01 +00004742 Diagnosed = true;
Richard Smith8ef7b202012-01-18 23:55:52 +00004743 break;
4744
4745 case NK_Type_Narrowing:
4746 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4747 << CCE << /*Constant*/0 << From->getType() << T;
Richard Smithf72fccf2012-01-30 22:27:01 +00004748 Diagnosed = true;
Richard Smith8ef7b202012-01-18 23:55:52 +00004749 break;
4750 }
4751
4752 // Check the expression is a constant expression.
4753 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4754 Expr::EvalResult Eval;
4755 Eval.Diag = &Notes;
4756
4757 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4758 // The expression can't be folded, so we can't keep it at this position in
4759 // the AST.
4760 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004761 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004762 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004763
4764 if (Notes.empty()) {
4765 // It's a constant expression.
4766 return Result;
4767 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004768 }
4769
Richard Smithf72fccf2012-01-30 22:27:01 +00004770 // Only issue one narrowing diagnostic.
4771 if (Diagnosed)
4772 return Result;
4773
Richard Smith8ef7b202012-01-18 23:55:52 +00004774 // It's not a constant expression. Produce an appropriate diagnostic.
4775 if (Notes.size() == 1 &&
4776 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4777 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4778 else {
4779 Diag(From->getSourceRange().getBegin(), diag::err_expr_not_cce)
4780 << CCE << From->getSourceRange();
4781 for (unsigned I = 0; I < Notes.size(); ++I)
4782 Diag(Notes[I].first, Notes[I].second);
4783 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004784 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004785}
4786
John McCall0bcc9bc2011-09-09 06:11:02 +00004787/// dropPointerConversions - If the given standard conversion sequence
4788/// involves any pointer conversions, remove them. This may change
4789/// the result type of the conversion sequence.
4790static void dropPointerConversion(StandardConversionSequence &SCS) {
4791 if (SCS.Second == ICK_Pointer_Conversion) {
4792 SCS.Second = ICK_Identity;
4793 SCS.Third = ICK_Identity;
4794 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4795 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004796}
John McCall120d63c2010-08-24 20:38:10 +00004797
John McCall0bcc9bc2011-09-09 06:11:02 +00004798/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4799/// convert the expression From to an Objective-C pointer type.
4800static ImplicitConversionSequence
4801TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4802 // Do an implicit conversion to 'id'.
4803 QualType Ty = S.Context.getObjCIdType();
4804 ImplicitConversionSequence ICS
4805 = TryImplicitConversion(S, From, Ty,
4806 // FIXME: Are these flags correct?
4807 /*SuppressUserConversions=*/false,
4808 /*AllowExplicit=*/true,
4809 /*InOverloadResolution=*/false,
4810 /*CStyle=*/false,
4811 /*AllowObjCWritebackConversion=*/false);
4812
4813 // Strip off any final conversions to 'id'.
4814 switch (ICS.getKind()) {
4815 case ImplicitConversionSequence::BadConversion:
4816 case ImplicitConversionSequence::AmbiguousConversion:
4817 case ImplicitConversionSequence::EllipsisConversion:
4818 break;
4819
4820 case ImplicitConversionSequence::UserDefinedConversion:
4821 dropPointerConversion(ICS.UserDefined.After);
4822 break;
4823
4824 case ImplicitConversionSequence::StandardConversion:
4825 dropPointerConversion(ICS.Standard);
4826 break;
4827 }
4828
4829 return ICS;
4830}
4831
4832/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4833/// conversion of the expression From to an Objective-C pointer type.
4834ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004835 if (checkPlaceholderForOverload(*this, From))
4836 return ExprError();
4837
John McCallc12c5bb2010-05-15 11:32:37 +00004838 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004839 ImplicitConversionSequence ICS =
4840 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004841 if (!ICS.isBad())
4842 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004843 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004844}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004845
Richard Smithf39aec12012-02-04 07:07:42 +00004846/// Determine whether the provided type is an integral type, or an enumeration
4847/// type of a permitted flavor.
4848static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4849 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4850 : T->isIntegralOrUnscopedEnumerationType();
4851}
4852
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004853/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00004854/// enumeration type.
4855///
4856/// This routine will attempt to convert an expression of class type to an
4857/// integral or enumeration type, if that class type only has a single
4858/// conversion to an integral or enumeration type.
4859///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004860/// \param Loc The source location of the construct that requires the
4861/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004862///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004863/// \param FromE The expression we're converting from.
4864///
4865/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4866/// have integral or enumeration type.
4867///
4868/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4869/// incomplete class type.
4870///
4871/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4872/// explicit conversion function (because no implicit conversion functions
4873/// were available). This is a recovery mode.
4874///
4875/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4876/// showing which conversion was picked.
4877///
4878/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4879/// conversion function that could convert to integral or enumeration type.
4880///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004881/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004882/// usable conversion function.
4883///
4884/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4885/// function, which may be an extension in this case.
4886///
Richard Smithf39aec12012-02-04 07:07:42 +00004887/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4888/// enumerations should be considered.
4889///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004890/// \returns The expression, converted to an integral or enumeration type if
4891/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004892ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004893Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00004894 const PartialDiagnostic &NotIntDiag,
4895 const PartialDiagnostic &IncompleteDiag,
4896 const PartialDiagnostic &ExplicitConvDiag,
4897 const PartialDiagnostic &ExplicitConvNote,
4898 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004899 const PartialDiagnostic &AmbigNote,
Richard Smithf39aec12012-02-04 07:07:42 +00004900 const PartialDiagnostic &ConvDiag,
4901 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004902 // We can't perform any more checking for type-dependent expressions.
4903 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00004904 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004905
Eli Friedmanceccab92012-01-26 00:26:18 +00004906 // Process placeholders immediately.
4907 if (From->hasPlaceholderType()) {
4908 ExprResult result = CheckPlaceholderExpr(From);
4909 if (result.isInvalid()) return result;
4910 From = result.take();
4911 }
4912
Douglas Gregorc30614b2010-06-29 23:17:37 +00004913 // If the expression already has integral or enumeration type, we're golden.
4914 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00004915 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00004916 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004917
4918 // FIXME: Check for missing '()' if T is a function type?
4919
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004920 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorc30614b2010-06-29 23:17:37 +00004921 // expression of integral or enumeration type.
4922 const RecordType *RecordTy = T->getAs<RecordType>();
4923 if (!RecordTy || !getLangOptions().CPlusPlus) {
Richard Smith282e7e62012-02-04 09:53:13 +00004924 if (NotIntDiag.getDiagID())
4925 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00004926 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004927 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004928
Douglas Gregorc30614b2010-06-29 23:17:37 +00004929 // We must have a complete class type.
4930 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00004931 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004932
Douglas Gregorc30614b2010-06-29 23:17:37 +00004933 // Look for a conversion to an integral or enumeration type.
4934 UnresolvedSet<4> ViableConversions;
4935 UnresolvedSet<4> ExplicitConversions;
4936 const UnresolvedSetImpl *Conversions
4937 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004938
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004939 bool HadMultipleCandidates = (Conversions->size() > 1);
4940
Douglas Gregorc30614b2010-06-29 23:17:37 +00004941 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004942 E = Conversions->end();
4943 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00004944 ++I) {
4945 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00004946 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
4947 if (isIntegralOrEnumerationType(
4948 Conversion->getConversionType().getNonReferenceType(),
4949 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004950 if (Conversion->isExplicit())
4951 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4952 else
4953 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4954 }
Richard Smithf39aec12012-02-04 07:07:42 +00004955 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00004956 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004957
Douglas Gregorc30614b2010-06-29 23:17:37 +00004958 switch (ViableConversions.size()) {
4959 case 0:
Richard Smith282e7e62012-02-04 09:53:13 +00004960 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004961 DeclAccessPair Found = ExplicitConversions[0];
4962 CXXConversionDecl *Conversion
4963 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004964
Douglas Gregorc30614b2010-06-29 23:17:37 +00004965 // The user probably meant to invoke the given explicit
4966 // conversion; use it.
4967 QualType ConvTy
4968 = Conversion->getConversionType().getNonReferenceType();
4969 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00004970 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004971
Douglas Gregorc30614b2010-06-29 23:17:37 +00004972 Diag(Loc, ExplicitConvDiag)
4973 << T << ConvTy
4974 << FixItHint::CreateInsertion(From->getLocStart(),
4975 "static_cast<" + TypeStr + ">(")
4976 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4977 ")");
4978 Diag(Conversion->getLocation(), ExplicitConvNote)
4979 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004980
4981 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00004982 // explicit conversion function.
4983 if (isSFINAEContext())
4984 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004985
Douglas Gregorc30614b2010-06-29 23:17:37 +00004986 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004987 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4988 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004989 if (Result.isInvalid())
4990 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00004991 // Record usage of conversion in an implicit cast.
4992 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4993 CK_UserDefinedConversion,
4994 Result.get(), 0,
4995 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00004996 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004997
Douglas Gregorc30614b2010-06-29 23:17:37 +00004998 // We'll complain below about a non-integral condition type.
4999 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005000
Douglas Gregorc30614b2010-06-29 23:17:37 +00005001 case 1: {
5002 // Apply this conversion.
5003 DeclAccessPair Found = ViableConversions[0];
5004 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005005
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005006 CXXConversionDecl *Conversion
5007 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5008 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005009 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005010 if (ConvDiag.getDiagID()) {
5011 if (isSFINAEContext())
5012 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005013
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005014 Diag(Loc, ConvDiag)
5015 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005017
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005018 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5019 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005020 if (Result.isInvalid())
5021 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005022 // Record usage of conversion in an implicit cast.
5023 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5024 CK_UserDefinedConversion,
5025 Result.get(), 0,
5026 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005027 break;
5028 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005029
Douglas Gregorc30614b2010-06-29 23:17:37 +00005030 default:
Richard Smith282e7e62012-02-04 09:53:13 +00005031 if (!AmbigDiag.getDiagID())
5032 return Owned(From);
5033
Douglas Gregorc30614b2010-06-29 23:17:37 +00005034 Diag(Loc, AmbigDiag)
5035 << T << From->getSourceRange();
5036 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5037 CXXConversionDecl *Conv
5038 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5039 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5040 Diag(Conv->getLocation(), AmbigNote)
5041 << ConvTy->isEnumeralType() << ConvTy;
5042 }
John McCall9ae2f072010-08-23 23:25:46 +00005043 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005044 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005045
Richard Smith282e7e62012-02-04 09:53:13 +00005046 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5047 NotIntDiag.getDiagID())
5048 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005049
Eli Friedmanceccab92012-01-26 00:26:18 +00005050 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005051}
5052
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005053/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005054/// candidate functions, using the given function call arguments. If
5055/// @p SuppressUserConversions, then don't allow user-defined
5056/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005057///
5058/// \para PartialOverloading true if we are performing "partial" overloading
5059/// based on an incomplete set of function arguments. This feature is used by
5060/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005061void
5062Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005063 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005064 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005065 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005066 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005067 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00005068 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005069 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005070 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005071 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005072 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005073
Douglas Gregor88a35142008-12-22 05:46:06 +00005074 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005075 if (!isa<CXXConstructorDecl>(Method)) {
5076 // If we get here, it's because we're calling a member function
5077 // that is named without a member access expression (e.g.,
5078 // "this->f") that was either written explicitly or created
5079 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005080 // function, e.g., X::f(). We use an empty type for the implied
5081 // object argument (C++ [over.call.func]p3), and the acting context
5082 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005083 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005084 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005085 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005086 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005087 return;
5088 }
5089 // We treat a constructor like a non-member function, since its object
5090 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005091 }
5092
Douglas Gregorfd476482009-11-13 23:59:09 +00005093 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005094 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005095
Douglas Gregor7edfb692009-11-23 12:27:39 +00005096 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005097 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005098
Douglas Gregor66724ea2009-11-14 01:20:54 +00005099 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5100 // C++ [class.copy]p3:
5101 // A member function template is never instantiated to perform the copy
5102 // of a class object to an object of its class type.
5103 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005104 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005105 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005106 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5107 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005108 return;
5109 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005110
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005111 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005112 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005113 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005114 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005115 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005116 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005117 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005118 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005119
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005120 unsigned NumArgsInProto = Proto->getNumArgs();
5121
5122 // (C++ 13.3.2p2): A candidate function having fewer than m
5123 // parameters is viable only if it has an ellipsis in its parameter
5124 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005125 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005126 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005127 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005128 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005129 return;
5130 }
5131
5132 // (C++ 13.3.2p2): A candidate function having more than m parameters
5133 // is viable only if the (m+1)st parameter has a default argument
5134 // (8.3.6). For the purposes of overload resolution, the
5135 // parameter list is truncated on the right, so that there are
5136 // exactly m parameters.
5137 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005138 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005139 // Not enough arguments.
5140 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005141 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005142 return;
5143 }
5144
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005145 // (CUDA B.1): Check for invalid calls between targets.
5146 if (getLangOptions().CUDA)
5147 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5148 if (CheckCUDATarget(Caller, Function)) {
5149 Candidate.Viable = false;
5150 Candidate.FailureKind = ovl_fail_bad_target;
5151 return;
5152 }
5153
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005154 // Determine the implicit conversion sequences for each of the
5155 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005156 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5157 if (ArgIdx < NumArgsInProto) {
5158 // (C++ 13.3.2p3): for F to be a viable function, there shall
5159 // exist for each argument an implicit conversion sequence
5160 // (13.3.3.1) that converts that argument to the corresponding
5161 // parameter of F.
5162 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005163 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005164 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005165 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005166 /*InOverloadResolution=*/true,
5167 /*AllowObjCWritebackConversion=*/
5168 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005169 if (Candidate.Conversions[ArgIdx].isBad()) {
5170 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005171 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005172 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005173 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005174 } else {
5175 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5176 // argument for which there is no corresponding parameter is
5177 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005178 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005179 }
5180 }
5181}
5182
Douglas Gregor063daf62009-03-13 18:40:31 +00005183/// \brief Add all of the function declarations in the given function set to
5184/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005185void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005186 Expr **Args, unsigned NumArgs,
5187 OverloadCandidateSet& CandidateSet,
5188 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00005189 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005190 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5191 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005192 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005193 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005194 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005195 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005196 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00005197 CandidateSet, SuppressUserConversions);
5198 else
John McCall9aa472c2010-03-19 07:35:19 +00005199 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005200 SuppressUserConversions);
5201 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005202 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005203 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5204 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005205 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005206 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00005207 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005208 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005209 Args[0]->Classify(Context),
5210 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00005211 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00005212 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005213 else
John McCall9aa472c2010-03-19 07:35:19 +00005214 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00005215 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00005216 Args, NumArgs, CandidateSet,
5217 SuppressUserConversions);
5218 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005219 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005220}
5221
John McCall314be4e2009-11-17 07:50:12 +00005222/// AddMethodCandidate - Adds a named decl (which is some kind of
5223/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005224void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005225 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005226 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005227 Expr **Args, unsigned NumArgs,
5228 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005229 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005230 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005231 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005232
5233 if (isa<UsingShadowDecl>(Decl))
5234 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005235
John McCall314be4e2009-11-17 07:50:12 +00005236 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5237 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5238 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005239 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5240 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005241 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00005242 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005243 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005244 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005245 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005246 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005247 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005248 }
5249}
5250
Douglas Gregor96176b32008-11-18 23:14:02 +00005251/// AddMethodCandidate - Adds the given C++ member function to the set
5252/// of candidate functions, using the given function call arguments
5253/// and the object argument (@c Object). For example, in a call
5254/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5255/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5256/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005257/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005258void
John McCall9aa472c2010-03-19 07:35:19 +00005259Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005260 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005261 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00005262 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00005263 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005264 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005265 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005266 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005267 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005268 assert(!isa<CXXConstructorDecl>(Method) &&
5269 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005270
Douglas Gregor3f396022009-09-28 04:47:19 +00005271 if (!CandidateSet.isNewCandidate(Method))
5272 return;
5273
Douglas Gregor7edfb692009-11-23 12:27:39 +00005274 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005275 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005276
Douglas Gregor96176b32008-11-18 23:14:02 +00005277 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005278 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005279 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005280 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005281 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005282 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005283 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00005284
5285 unsigned NumArgsInProto = Proto->getNumArgs();
5286
5287 // (C++ 13.3.2p2): A candidate function having fewer than m
5288 // parameters is viable only if it has an ellipsis in its parameter
5289 // list (8.3.5).
5290 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5291 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005292 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005293 return;
5294 }
5295
5296 // (C++ 13.3.2p2): A candidate function having more than m parameters
5297 // is viable only if the (m+1)st parameter has a default argument
5298 // (8.3.6). For the purposes of overload resolution, the
5299 // parameter list is truncated on the right, so that there are
5300 // exactly m parameters.
5301 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5302 if (NumArgs < MinRequiredArgs) {
5303 // Not enough arguments.
5304 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005305 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005306 return;
5307 }
5308
5309 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005310
John McCall701c89e2009-12-03 04:06:58 +00005311 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005312 // The implicit object argument is ignored.
5313 Candidate.IgnoreObjectArgument = true;
5314 else {
5315 // Determine the implicit conversion sequence for the object
5316 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005317 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005318 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5319 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005320 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005321 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005322 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005323 return;
5324 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005325 }
5326
5327 // Determine the implicit conversion sequences for each of the
5328 // arguments.
5329 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5330 if (ArgIdx < NumArgsInProto) {
5331 // (C++ 13.3.2p3): for F to be a viable function, there shall
5332 // exist for each argument an implicit conversion sequence
5333 // (13.3.3.1) that converts that argument to the corresponding
5334 // parameter of F.
5335 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005336 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005337 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005338 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005339 /*InOverloadResolution=*/true,
5340 /*AllowObjCWritebackConversion=*/
5341 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005342 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005343 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005344 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005345 break;
5346 }
5347 } else {
5348 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5349 // argument for which there is no corresponding parameter is
5350 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005351 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005352 }
5353 }
5354}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005355
Douglas Gregor6b906862009-08-21 00:16:32 +00005356/// \brief Add a C++ member function template as a candidate to the candidate
5357/// set, using template argument deduction to produce an appropriate member
5358/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005359void
Douglas Gregor6b906862009-08-21 00:16:32 +00005360Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005361 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005362 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005363 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005364 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005365 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00005366 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00005367 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005368 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005369 if (!CandidateSet.isNewCandidate(MethodTmpl))
5370 return;
5371
Douglas Gregor6b906862009-08-21 00:16:32 +00005372 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005373 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005374 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005375 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005376 // candidate functions in the usual way.113) A given name can refer to one
5377 // or more function templates and also to a set of overloaded non-template
5378 // functions. In such a case, the candidate functions generated from each
5379 // function template are combined with the set of non-template candidate
5380 // functions.
John McCall5769d612010-02-08 23:07:23 +00005381 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005382 FunctionDecl *Specialization = 0;
5383 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00005384 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00005385 Args, NumArgs, Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005386 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005387 Candidate.FoundDecl = FoundDecl;
5388 Candidate.Function = MethodTmpl->getTemplatedDecl();
5389 Candidate.Viable = false;
5390 Candidate.FailureKind = ovl_fail_bad_deduction;
5391 Candidate.IsSurrogate = false;
5392 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005393 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005394 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005395 Info);
5396 return;
5397 }
Mike Stump1eb44332009-09-09 15:08:12 +00005398
Douglas Gregor6b906862009-08-21 00:16:32 +00005399 // Add the function template specialization produced by template argument
5400 // deduction as a candidate.
5401 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005402 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005403 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005404 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005405 ActingContext, ObjectType, ObjectClassification,
5406 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005407}
5408
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005409/// \brief Add a C++ function template specialization as a candidate
5410/// in the candidate set, using template argument deduction to produce
5411/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005412void
Douglas Gregore53060f2009-06-25 22:08:12 +00005413Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005414 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005415 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00005416 Expr **Args, unsigned NumArgs,
5417 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005418 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005419 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5420 return;
5421
Douglas Gregore53060f2009-06-25 22:08:12 +00005422 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005423 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005424 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005425 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005426 // candidate functions in the usual way.113) A given name can refer to one
5427 // or more function templates and also to a set of overloaded non-template
5428 // functions. In such a case, the candidate functions generated from each
5429 // function template are combined with the set of non-template candidate
5430 // functions.
John McCall5769d612010-02-08 23:07:23 +00005431 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005432 FunctionDecl *Specialization = 0;
5433 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00005434 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005435 Args, NumArgs, Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005436 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005437 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005438 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5439 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005440 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005441 Candidate.IsSurrogate = false;
5442 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005443 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005444 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005445 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005446 return;
5447 }
Mike Stump1eb44332009-09-09 15:08:12 +00005448
Douglas Gregore53060f2009-06-25 22:08:12 +00005449 // Add the function template specialization produced by template argument
5450 // deduction as a candidate.
5451 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005452 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005453 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005454}
Mike Stump1eb44332009-09-09 15:08:12 +00005455
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005456/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005457/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005458/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005459/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005460/// (which may or may not be the same type as the type that the
5461/// conversion function produces).
5462void
5463Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005464 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005465 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005466 Expr *From, QualType ToType,
5467 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005468 assert(!Conversion->getDescribedFunctionTemplate() &&
5469 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005470 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005471 if (!CandidateSet.isNewCandidate(Conversion))
5472 return;
5473
Douglas Gregor7edfb692009-11-23 12:27:39 +00005474 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005475 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005476
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005477 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005478 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005479 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005480 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005481 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005482 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005483 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005484 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005485 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005486 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005487 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005488
Douglas Gregorbca39322010-08-19 15:37:02 +00005489 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005490 // For conversion functions, the function is considered to be a member of
5491 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005492 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005493 //
5494 // Determine the implicit conversion sequence for the implicit
5495 // object parameter.
5496 QualType ImplicitParamType = From->getType();
5497 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5498 ImplicitParamType = FromPtrType->getPointeeType();
5499 CXXRecordDecl *ConversionContext
5500 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005501
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005502 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005503 = TryObjectArgumentInitialization(*this, From->getType(),
5504 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005505 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005506
John McCall1d318332010-01-12 00:44:57 +00005507 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005508 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005509 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005510 return;
5511 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005512
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005513 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005514 // derived to base as such conversions are given Conversion Rank. They only
5515 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5516 QualType FromCanon
5517 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5518 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5519 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5520 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005521 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005522 return;
5523 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005524
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005525 // To determine what the conversion from the result of calling the
5526 // conversion function to the type we're eventually trying to
5527 // convert to (ToType), we need to synthesize a call to the
5528 // conversion function and attempt copy initialization from it. This
5529 // makes sure that we get the right semantics with respect to
5530 // lvalues/rvalues and the type. Fortunately, we can allocate this
5531 // call on the stack and we don't need its arguments to be
5532 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00005533 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005534 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005535 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5536 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005537 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005538 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005539
Richard Smith87c1f1f2011-07-13 22:53:21 +00005540 QualType ConversionType = Conversion->getConversionType();
5541 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005542 Candidate.Viable = false;
5543 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5544 return;
5545 }
5546
Richard Smith87c1f1f2011-07-13 22:53:21 +00005547 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005548
Mike Stump1eb44332009-09-09 15:08:12 +00005549 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005550 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5551 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005552 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005553 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005554 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005555 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005556 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005557 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005558 /*InOverloadResolution=*/false,
5559 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005560
John McCall1d318332010-01-12 00:44:57 +00005561 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005562 case ImplicitConversionSequence::StandardConversion:
5563 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005564
Douglas Gregorc520c842010-04-12 23:42:09 +00005565 // C++ [over.ics.user]p3:
5566 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005567 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005568 // shall have exact match rank.
5569 if (Conversion->getPrimaryTemplate() &&
5570 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5571 Candidate.Viable = false;
5572 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5573 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005574
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005575 // C++0x [dcl.init.ref]p5:
5576 // In the second case, if the reference is an rvalue reference and
5577 // the second standard conversion sequence of the user-defined
5578 // conversion sequence includes an lvalue-to-rvalue conversion, the
5579 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005580 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005581 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5582 Candidate.Viable = false;
5583 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5584 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005585 break;
5586
5587 case ImplicitConversionSequence::BadConversion:
5588 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005589 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005590 break;
5591
5592 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005593 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005594 "Can only end up with a standard conversion sequence or failure");
5595 }
5596}
5597
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005598/// \brief Adds a conversion function template specialization
5599/// candidate to the overload set, using template argument deduction
5600/// to deduce the template arguments of the conversion function
5601/// template from the type that we are converting to (C++
5602/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005603void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005604Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005605 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005606 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005607 Expr *From, QualType ToType,
5608 OverloadCandidateSet &CandidateSet) {
5609 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5610 "Only conversion function templates permitted here");
5611
Douglas Gregor3f396022009-09-28 04:47:19 +00005612 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5613 return;
5614
John McCall5769d612010-02-08 23:07:23 +00005615 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005616 CXXConversionDecl *Specialization = 0;
5617 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005618 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005619 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005620 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005621 Candidate.FoundDecl = FoundDecl;
5622 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5623 Candidate.Viable = false;
5624 Candidate.FailureKind = ovl_fail_bad_deduction;
5625 Candidate.IsSurrogate = false;
5626 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005627 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005628 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005629 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005630 return;
5631 }
Mike Stump1eb44332009-09-09 15:08:12 +00005632
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005633 // Add the conversion function template specialization produced by
5634 // template argument deduction as a candidate.
5635 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005636 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005637 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005638}
5639
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005640/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5641/// converts the given @c Object to a function pointer via the
5642/// conversion function @c Conversion, and then attempts to call it
5643/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5644/// the type of function that we'll eventually be calling.
5645void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005646 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005647 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005648 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005649 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00005650 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005651 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005652 if (!CandidateSet.isNewCandidate(Conversion))
5653 return;
5654
Douglas Gregor7edfb692009-11-23 12:27:39 +00005655 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005656 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005657
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005658 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005659 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005660 Candidate.Function = 0;
5661 Candidate.Surrogate = Conversion;
5662 Candidate.Viable = true;
5663 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005664 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005665 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005666
5667 // Determine the implicit conversion sequence for the implicit
5668 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005669 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005670 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005671 Object->Classify(Context),
5672 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005673 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005674 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005675 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005676 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005677 return;
5678 }
5679
5680 // The first conversion is actually a user-defined conversion whose
5681 // first conversion is ObjectInit's standard conversion (which is
5682 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005683 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005684 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005685 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005686 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005687 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005688 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005689 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005690 = Candidate.Conversions[0].UserDefined.Before;
5691 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5692
Mike Stump1eb44332009-09-09 15:08:12 +00005693 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005694 unsigned NumArgsInProto = Proto->getNumArgs();
5695
5696 // (C++ 13.3.2p2): A candidate function having fewer than m
5697 // parameters is viable only if it has an ellipsis in its parameter
5698 // list (8.3.5).
5699 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5700 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005701 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005702 return;
5703 }
5704
5705 // Function types don't have any default arguments, so just check if
5706 // we have enough arguments.
5707 if (NumArgs < NumArgsInProto) {
5708 // Not enough arguments.
5709 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005710 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005711 return;
5712 }
5713
5714 // Determine the implicit conversion sequences for each of the
5715 // arguments.
5716 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5717 if (ArgIdx < NumArgsInProto) {
5718 // (C++ 13.3.2p3): for F to be a viable function, there shall
5719 // exist for each argument an implicit conversion sequence
5720 // (13.3.3.1) that converts that argument to the corresponding
5721 // parameter of F.
5722 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005723 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005724 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005725 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005726 /*InOverloadResolution=*/false,
5727 /*AllowObjCWritebackConversion=*/
5728 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005729 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005730 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005731 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005732 break;
5733 }
5734 } else {
5735 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5736 // argument for which there is no corresponding parameter is
5737 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005738 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005739 }
5740 }
5741}
5742
Douglas Gregor063daf62009-03-13 18:40:31 +00005743/// \brief Add overload candidates for overloaded operators that are
5744/// member functions.
5745///
5746/// Add the overloaded operator candidates that are member functions
5747/// for the operator Op that was used in an operator expression such
5748/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5749/// CandidateSet will store the added overload candidates. (C++
5750/// [over.match.oper]).
5751void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5752 SourceLocation OpLoc,
5753 Expr **Args, unsigned NumArgs,
5754 OverloadCandidateSet& CandidateSet,
5755 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005756 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5757
5758 // C++ [over.match.oper]p3:
5759 // For a unary operator @ with an operand of a type whose
5760 // cv-unqualified version is T1, and for a binary operator @ with
5761 // a left operand of a type whose cv-unqualified version is T1 and
5762 // a right operand of a type whose cv-unqualified version is T2,
5763 // three sets of candidate functions, designated member
5764 // candidates, non-member candidates and built-in candidates, are
5765 // constructed as follows:
5766 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005767
5768 // -- If T1 is a class type, the set of member candidates is the
5769 // result of the qualified lookup of T1::operator@
5770 // (13.3.1.1.1); otherwise, the set of member candidates is
5771 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005772 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005773 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005774 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005775 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005776
John McCalla24dc2e2009-11-17 02:14:36 +00005777 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5778 LookupQualifiedName(Operators, T1Rec->getDecl());
5779 Operators.suppressDiagnostics();
5780
Mike Stump1eb44332009-09-09 15:08:12 +00005781 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005782 OperEnd = Operators.end();
5783 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005784 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005785 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005786 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005787 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005788 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005789 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005790}
5791
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005792/// AddBuiltinCandidate - Add a candidate for a built-in
5793/// operator. ResultTy and ParamTys are the result and parameter types
5794/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005795/// arguments being passed to the candidate. IsAssignmentOperator
5796/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005797/// operator. NumContextualBoolArguments is the number of arguments
5798/// (at the beginning of the argument list) that will be contextually
5799/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005800void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005801 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005802 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005803 bool IsAssignmentOperator,
5804 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005805 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005806 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005807
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005808 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005809 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005810 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005811 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005812 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005813 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005814 Candidate.BuiltinTypes.ResultTy = ResultTy;
5815 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5816 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5817
5818 // Determine the implicit conversion sequences for each of the
5819 // arguments.
5820 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005821 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005822 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005823 // C++ [over.match.oper]p4:
5824 // For the built-in assignment operators, conversions of the
5825 // left operand are restricted as follows:
5826 // -- no temporaries are introduced to hold the left operand, and
5827 // -- no user-defined conversions are applied to the left
5828 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005829 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005830 //
5831 // We block these conversions by turning off user-defined
5832 // conversions, since that is the only way that initialization of
5833 // a reference to a non-class type can occur from something that
5834 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005835 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005836 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005837 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005838 Candidate.Conversions[ArgIdx]
5839 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005840 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005841 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005842 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005843 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005844 /*InOverloadResolution=*/false,
5845 /*AllowObjCWritebackConversion=*/
5846 getLangOptions().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005847 }
John McCall1d318332010-01-12 00:44:57 +00005848 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005849 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005850 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005851 break;
5852 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005853 }
5854}
5855
5856/// BuiltinCandidateTypeSet - A set of types that will be used for the
5857/// candidate operator functions for built-in operators (C++
5858/// [over.built]). The types are separated into pointer types and
5859/// enumeration types.
5860class BuiltinCandidateTypeSet {
5861 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005862 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005863
5864 /// PointerTypes - The set of pointer types that will be used in the
5865 /// built-in candidates.
5866 TypeSet PointerTypes;
5867
Sebastian Redl78eb8742009-04-19 21:53:20 +00005868 /// MemberPointerTypes - The set of member pointer types that will be
5869 /// used in the built-in candidates.
5870 TypeSet MemberPointerTypes;
5871
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005872 /// EnumerationTypes - The set of enumeration types that will be
5873 /// used in the built-in candidates.
5874 TypeSet EnumerationTypes;
5875
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005876 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00005877 /// candidates.
5878 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00005879
5880 /// \brief A flag indicating non-record types are viable candidates
5881 bool HasNonRecordTypes;
5882
5883 /// \brief A flag indicating whether either arithmetic or enumeration types
5884 /// were present in the candidate set.
5885 bool HasArithmeticOrEnumeralTypes;
5886
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005887 /// \brief A flag indicating whether the nullptr type was present in the
5888 /// candidate set.
5889 bool HasNullPtrType;
5890
Douglas Gregor5842ba92009-08-24 15:23:48 +00005891 /// Sema - The semantic analysis instance where we are building the
5892 /// candidate type set.
5893 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00005894
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005895 /// Context - The AST context in which we will build the type sets.
5896 ASTContext &Context;
5897
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005898 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5899 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00005900 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005901
5902public:
5903 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005904 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005905
Mike Stump1eb44332009-09-09 15:08:12 +00005906 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00005907 : HasNonRecordTypes(false),
5908 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005909 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00005910 SemaRef(SemaRef),
5911 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005912
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005913 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005914 SourceLocation Loc,
5915 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005916 bool AllowExplicitConversions,
5917 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005918
5919 /// pointer_begin - First pointer type found;
5920 iterator pointer_begin() { return PointerTypes.begin(); }
5921
Sebastian Redl78eb8742009-04-19 21:53:20 +00005922 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005923 iterator pointer_end() { return PointerTypes.end(); }
5924
Sebastian Redl78eb8742009-04-19 21:53:20 +00005925 /// member_pointer_begin - First member pointer type found;
5926 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5927
5928 /// member_pointer_end - Past the last member pointer type found;
5929 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5930
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005931 /// enumeration_begin - First enumeration type found;
5932 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5933
Sebastian Redl78eb8742009-04-19 21:53:20 +00005934 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005935 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005936
Douglas Gregor26bcf672010-05-19 03:21:00 +00005937 iterator vector_begin() { return VectorTypes.begin(); }
5938 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00005939
5940 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5941 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005942 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005943};
5944
Sebastian Redl78eb8742009-04-19 21:53:20 +00005945/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005946/// the set of pointer types along with any more-qualified variants of
5947/// that type. For example, if @p Ty is "int const *", this routine
5948/// will add "int const *", "int const volatile *", "int const
5949/// restrict *", and "int const volatile restrict *" to the set of
5950/// pointer types. Returns true if the add of @p Ty itself succeeded,
5951/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005952///
5953/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005954bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00005955BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5956 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00005957
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005958 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005959 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005960 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005961
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005962 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00005963 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005964 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005965 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005966 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005967 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005968 buildObjCPtr = true;
5969 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005970 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005971 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005972 }
5973 else
5974 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005975
Sebastian Redla9efada2009-11-18 20:39:26 +00005976 // Don't add qualified variants of arrays. For one, they're not allowed
5977 // (the qualifier would sink to the element type), and for another, the
5978 // only overload situation where it matters is subscript or pointer +- int,
5979 // and those shouldn't have qualifier variants anyway.
5980 if (PointeeTy->isArrayType())
5981 return true;
John McCall0953e762009-09-24 19:53:00 +00005982 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00005983 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00005984 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005985 bool hasVolatile = VisibleQuals.hasVolatile();
5986 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005987
John McCall0953e762009-09-24 19:53:00 +00005988 // Iterate through all strict supersets of BaseCVR.
5989 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5990 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005991 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5992 // in the types.
5993 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5994 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00005995 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005996 if (!buildObjCPtr)
5997 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5998 else
5999 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006000 }
6001
6002 return true;
6003}
6004
Sebastian Redl78eb8742009-04-19 21:53:20 +00006005/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6006/// to the set of pointer types along with any more-qualified variants of
6007/// that type. For example, if @p Ty is "int const *", this routine
6008/// will add "int const *", "int const volatile *", "int const
6009/// restrict *", and "int const volatile restrict *" to the set of
6010/// pointer types. Returns true if the add of @p Ty itself succeeded,
6011/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006012///
6013/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006014bool
6015BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6016 QualType Ty) {
6017 // Insert this type.
6018 if (!MemberPointerTypes.insert(Ty))
6019 return false;
6020
John McCall0953e762009-09-24 19:53:00 +00006021 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6022 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006023
John McCall0953e762009-09-24 19:53:00 +00006024 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006025 // Don't add qualified variants of arrays. For one, they're not allowed
6026 // (the qualifier would sink to the element type), and for another, the
6027 // only overload situation where it matters is subscript or pointer +- int,
6028 // and those shouldn't have qualifier variants anyway.
6029 if (PointeeTy->isArrayType())
6030 return true;
John McCall0953e762009-09-24 19:53:00 +00006031 const Type *ClassTy = PointerTy->getClass();
6032
6033 // Iterate through all strict supersets of the pointee type's CVR
6034 // qualifiers.
6035 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6036 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6037 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006038
John McCall0953e762009-09-24 19:53:00 +00006039 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006040 MemberPointerTypes.insert(
6041 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006042 }
6043
6044 return true;
6045}
6046
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006047/// AddTypesConvertedFrom - Add each of the types to which the type @p
6048/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006049/// primarily interested in pointer types and enumeration types. We also
6050/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006051/// AllowUserConversions is true if we should look at the conversion
6052/// functions of a class type, and AllowExplicitConversions if we
6053/// should also include the explicit conversion functions of a class
6054/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006055void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006056BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006057 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006058 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006059 bool AllowExplicitConversions,
6060 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006061 // Only deal with canonical types.
6062 Ty = Context.getCanonicalType(Ty);
6063
6064 // Look through reference types; they aren't part of the type of an
6065 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006066 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006067 Ty = RefTy->getPointeeType();
6068
John McCall3b657512011-01-19 10:06:00 +00006069 // If we're dealing with an array type, decay to the pointer.
6070 if (Ty->isArrayType())
6071 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6072
6073 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006074 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006075
Chandler Carruth6a577462010-12-13 01:44:01 +00006076 // Flag if we ever add a non-record type.
6077 const RecordType *TyRec = Ty->getAs<RecordType>();
6078 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6079
Chandler Carruth6a577462010-12-13 01:44:01 +00006080 // Flag if we encounter an arithmetic type.
6081 HasArithmeticOrEnumeralTypes =
6082 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6083
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006084 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6085 PointerTypes.insert(Ty);
6086 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006087 // Insert our type, and its more-qualified variants, into the set
6088 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006089 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006090 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006091 } else if (Ty->isMemberPointerType()) {
6092 // Member pointers are far easier, since the pointee can't be converted.
6093 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6094 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006095 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006096 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006097 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006098 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006099 // We treat vector types as arithmetic types in many contexts as an
6100 // extension.
6101 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006102 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006103 } else if (Ty->isNullPtrType()) {
6104 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006105 } else if (AllowUserConversions && TyRec) {
6106 // No conversion functions in incomplete types.
6107 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6108 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006109
Chandler Carruth6a577462010-12-13 01:44:01 +00006110 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6111 const UnresolvedSetImpl *Conversions
6112 = ClassDecl->getVisibleConversionFunctions();
6113 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6114 E = Conversions->end(); I != E; ++I) {
6115 NamedDecl *D = I.getDecl();
6116 if (isa<UsingShadowDecl>(D))
6117 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006118
Chandler Carruth6a577462010-12-13 01:44:01 +00006119 // Skip conversion function templates; they don't tell us anything
6120 // about which builtin types we can convert to.
6121 if (isa<FunctionTemplateDecl>(D))
6122 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006123
Chandler Carruth6a577462010-12-13 01:44:01 +00006124 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6125 if (AllowExplicitConversions || !Conv->isExplicit()) {
6126 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6127 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006128 }
6129 }
6130 }
6131}
6132
Douglas Gregor19b7b152009-08-24 13:43:27 +00006133/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6134/// the volatile- and non-volatile-qualified assignment operators for the
6135/// given type to the candidate set.
6136static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6137 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006138 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006139 unsigned NumArgs,
6140 OverloadCandidateSet &CandidateSet) {
6141 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006142
Douglas Gregor19b7b152009-08-24 13:43:27 +00006143 // T& operator=(T&, T)
6144 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6145 ParamTypes[1] = T;
6146 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6147 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006148
Douglas Gregor19b7b152009-08-24 13:43:27 +00006149 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6150 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006151 ParamTypes[0]
6152 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006153 ParamTypes[1] = T;
6154 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006155 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006156 }
6157}
Mike Stump1eb44332009-09-09 15:08:12 +00006158
Sebastian Redl9994a342009-10-25 17:03:50 +00006159/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6160/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006161static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6162 Qualifiers VRQuals;
6163 const RecordType *TyRec;
6164 if (const MemberPointerType *RHSMPType =
6165 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006166 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006167 else
6168 TyRec = ArgExpr->getType()->getAs<RecordType>();
6169 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006170 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006171 VRQuals.addVolatile();
6172 VRQuals.addRestrict();
6173 return VRQuals;
6174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006175
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006176 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006177 if (!ClassDecl->hasDefinition())
6178 return VRQuals;
6179
John McCalleec51cf2010-01-20 00:46:10 +00006180 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006181 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006182
John McCalleec51cf2010-01-20 00:46:10 +00006183 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006184 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006185 NamedDecl *D = I.getDecl();
6186 if (isa<UsingShadowDecl>(D))
6187 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6188 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006189 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6190 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6191 CanTy = ResTypeRef->getPointeeType();
6192 // Need to go down the pointer/mempointer chain and add qualifiers
6193 // as see them.
6194 bool done = false;
6195 while (!done) {
6196 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6197 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006198 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006199 CanTy->getAs<MemberPointerType>())
6200 CanTy = ResTypeMPtr->getPointeeType();
6201 else
6202 done = true;
6203 if (CanTy.isVolatileQualified())
6204 VRQuals.addVolatile();
6205 if (CanTy.isRestrictQualified())
6206 VRQuals.addRestrict();
6207 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6208 return VRQuals;
6209 }
6210 }
6211 }
6212 return VRQuals;
6213}
John McCall00071ec2010-11-13 05:51:15 +00006214
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006215namespace {
John McCall00071ec2010-11-13 05:51:15 +00006216
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006217/// \brief Helper class to manage the addition of builtin operator overload
6218/// candidates. It provides shared state and utility methods used throughout
6219/// the process, as well as a helper method to add each group of builtin
6220/// operator overloads from the standard to a candidate set.
6221class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006222 // Common instance state available to all overload candidate addition methods.
6223 Sema &S;
6224 Expr **Args;
6225 unsigned NumArgs;
6226 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006227 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006228 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006229 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006230
Chandler Carruth6d695582010-12-12 10:35:00 +00006231 // Define some constants used to index and iterate over the arithemetic types
6232 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006233 // The "promoted arithmetic types" are the arithmetic
6234 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006235 static const unsigned FirstIntegralType = 3;
6236 static const unsigned LastIntegralType = 18;
6237 static const unsigned FirstPromotedIntegralType = 3,
6238 LastPromotedIntegralType = 9;
6239 static const unsigned FirstPromotedArithmeticType = 0,
6240 LastPromotedArithmeticType = 9;
6241 static const unsigned NumArithmeticTypes = 18;
6242
Chandler Carruth6d695582010-12-12 10:35:00 +00006243 /// \brief Get the canonical type for a given arithmetic type index.
6244 CanQualType getArithmeticType(unsigned index) {
6245 assert(index < NumArithmeticTypes);
6246 static CanQualType ASTContext::* const
6247 ArithmeticTypes[NumArithmeticTypes] = {
6248 // Start of promoted types.
6249 &ASTContext::FloatTy,
6250 &ASTContext::DoubleTy,
6251 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006252
Chandler Carruth6d695582010-12-12 10:35:00 +00006253 // Start of integral types.
6254 &ASTContext::IntTy,
6255 &ASTContext::LongTy,
6256 &ASTContext::LongLongTy,
6257 &ASTContext::UnsignedIntTy,
6258 &ASTContext::UnsignedLongTy,
6259 &ASTContext::UnsignedLongLongTy,
6260 // End of promoted types.
6261
6262 &ASTContext::BoolTy,
6263 &ASTContext::CharTy,
6264 &ASTContext::WCharTy,
6265 &ASTContext::Char16Ty,
6266 &ASTContext::Char32Ty,
6267 &ASTContext::SignedCharTy,
6268 &ASTContext::ShortTy,
6269 &ASTContext::UnsignedCharTy,
6270 &ASTContext::UnsignedShortTy,
6271 // End of integral types.
6272 // FIXME: What about complex?
6273 };
6274 return S.Context.*ArithmeticTypes[index];
6275 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006276
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006277 /// \brief Gets the canonical type resulting from the usual arithemetic
6278 /// converions for the given arithmetic types.
6279 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6280 // Accelerator table for performing the usual arithmetic conversions.
6281 // The rules are basically:
6282 // - if either is floating-point, use the wider floating-point
6283 // - if same signedness, use the higher rank
6284 // - if same size, use unsigned of the higher rank
6285 // - use the larger type
6286 // These rules, together with the axiom that higher ranks are
6287 // never smaller, are sufficient to precompute all of these results
6288 // *except* when dealing with signed types of higher rank.
6289 // (we could precompute SLL x UI for all known platforms, but it's
6290 // better not to make any assumptions).
6291 enum PromotedType {
6292 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6293 };
6294 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6295 [LastPromotedArithmeticType] = {
6296 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6297 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6298 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6299 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6300 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6301 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6302 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6303 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6304 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6305 };
6306
6307 assert(L < LastPromotedArithmeticType);
6308 assert(R < LastPromotedArithmeticType);
6309 int Idx = ConversionsTable[L][R];
6310
6311 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006312 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006313
6314 // Slow path: we need to compare widths.
6315 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006316 CanQualType LT = getArithmeticType(L),
6317 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006318 unsigned LW = S.Context.getIntWidth(LT),
6319 RW = S.Context.getIntWidth(RT);
6320
6321 // If they're different widths, use the signed type.
6322 if (LW > RW) return LT;
6323 else if (LW < RW) return RT;
6324
6325 // Otherwise, use the unsigned type of the signed type's rank.
6326 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6327 assert(L == SLL || R == SLL);
6328 return S.Context.UnsignedLongLongTy;
6329 }
6330
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006331 /// \brief Helper method to factor out the common pattern of adding overloads
6332 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006333 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6334 bool HasVolatile) {
6335 QualType ParamTypes[2] = {
6336 S.Context.getLValueReferenceType(CandidateTy),
6337 S.Context.IntTy
6338 };
6339
6340 // Non-volatile version.
6341 if (NumArgs == 1)
6342 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6343 else
6344 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6345
6346 // Use a heuristic to reduce number of builtin candidates in the set:
6347 // add volatile version only if there are conversions to a volatile type.
6348 if (HasVolatile) {
6349 ParamTypes[0] =
6350 S.Context.getLValueReferenceType(
6351 S.Context.getVolatileType(CandidateTy));
6352 if (NumArgs == 1)
6353 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6354 else
6355 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6356 }
6357 }
6358
6359public:
6360 BuiltinOperatorOverloadBuilder(
6361 Sema &S, Expr **Args, unsigned NumArgs,
6362 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006363 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006364 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006365 OverloadCandidateSet &CandidateSet)
6366 : S(S), Args(Args), NumArgs(NumArgs),
6367 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006368 HasArithmeticOrEnumeralCandidateType(
6369 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006370 CandidateTypes(CandidateTypes),
6371 CandidateSet(CandidateSet) {
6372 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006373 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006374 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006375 assert(getArithmeticType(LastPromotedIntegralType - 1)
6376 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006377 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006378 assert(getArithmeticType(FirstPromotedArithmeticType)
6379 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006380 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006381 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6382 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006383 "Invalid last promoted arithmetic type");
6384 }
6385
6386 // C++ [over.built]p3:
6387 //
6388 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6389 // is either volatile or empty, there exist candidate operator
6390 // functions of the form
6391 //
6392 // VQ T& operator++(VQ T&);
6393 // T operator++(VQ T&, int);
6394 //
6395 // C++ [over.built]p4:
6396 //
6397 // For every pair (T, VQ), where T is an arithmetic type other
6398 // than bool, and VQ is either volatile or empty, there exist
6399 // candidate operator functions of the form
6400 //
6401 // VQ T& operator--(VQ T&);
6402 // T operator--(VQ T&, int);
6403 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006404 if (!HasArithmeticOrEnumeralCandidateType)
6405 return;
6406
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006407 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6408 Arith < NumArithmeticTypes; ++Arith) {
6409 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006410 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006411 VisibleTypeConversionsQuals.hasVolatile());
6412 }
6413 }
6414
6415 // C++ [over.built]p5:
6416 //
6417 // For every pair (T, VQ), where T is a cv-qualified or
6418 // cv-unqualified object type, and VQ is either volatile or
6419 // empty, there exist candidate operator functions of the form
6420 //
6421 // T*VQ& operator++(T*VQ&);
6422 // T*VQ& operator--(T*VQ&);
6423 // T* operator++(T*VQ&, int);
6424 // T* operator--(T*VQ&, int);
6425 void addPlusPlusMinusMinusPointerOverloads() {
6426 for (BuiltinCandidateTypeSet::iterator
6427 Ptr = CandidateTypes[0].pointer_begin(),
6428 PtrEnd = CandidateTypes[0].pointer_end();
6429 Ptr != PtrEnd; ++Ptr) {
6430 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006431 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006432 continue;
6433
6434 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6435 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6436 VisibleTypeConversionsQuals.hasVolatile()));
6437 }
6438 }
6439
6440 // C++ [over.built]p6:
6441 // For every cv-qualified or cv-unqualified object type T, there
6442 // exist candidate operator functions of the form
6443 //
6444 // T& operator*(T*);
6445 //
6446 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006447 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006448 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006449 // T& operator*(T*);
6450 void addUnaryStarPointerOverloads() {
6451 for (BuiltinCandidateTypeSet::iterator
6452 Ptr = CandidateTypes[0].pointer_begin(),
6453 PtrEnd = CandidateTypes[0].pointer_end();
6454 Ptr != PtrEnd; ++Ptr) {
6455 QualType ParamTy = *Ptr;
6456 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006457 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6458 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006459
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006460 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6461 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6462 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006463
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006464 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6465 &ParamTy, Args, 1, CandidateSet);
6466 }
6467 }
6468
6469 // C++ [over.built]p9:
6470 // For every promoted arithmetic type T, there exist candidate
6471 // operator functions of the form
6472 //
6473 // T operator+(T);
6474 // T operator-(T);
6475 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006476 if (!HasArithmeticOrEnumeralCandidateType)
6477 return;
6478
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006479 for (unsigned Arith = FirstPromotedArithmeticType;
6480 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006481 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006482 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6483 }
6484
6485 // Extension: We also add these operators for vector types.
6486 for (BuiltinCandidateTypeSet::iterator
6487 Vec = CandidateTypes[0].vector_begin(),
6488 VecEnd = CandidateTypes[0].vector_end();
6489 Vec != VecEnd; ++Vec) {
6490 QualType VecTy = *Vec;
6491 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6492 }
6493 }
6494
6495 // C++ [over.built]p8:
6496 // For every type T, there exist candidate operator functions of
6497 // the form
6498 //
6499 // T* operator+(T*);
6500 void addUnaryPlusPointerOverloads() {
6501 for (BuiltinCandidateTypeSet::iterator
6502 Ptr = CandidateTypes[0].pointer_begin(),
6503 PtrEnd = CandidateTypes[0].pointer_end();
6504 Ptr != PtrEnd; ++Ptr) {
6505 QualType ParamTy = *Ptr;
6506 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6507 }
6508 }
6509
6510 // C++ [over.built]p10:
6511 // For every promoted integral type T, there exist candidate
6512 // operator functions of the form
6513 //
6514 // T operator~(T);
6515 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006516 if (!HasArithmeticOrEnumeralCandidateType)
6517 return;
6518
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006519 for (unsigned Int = FirstPromotedIntegralType;
6520 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006521 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006522 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6523 }
6524
6525 // Extension: We also add this operator for vector types.
6526 for (BuiltinCandidateTypeSet::iterator
6527 Vec = CandidateTypes[0].vector_begin(),
6528 VecEnd = CandidateTypes[0].vector_end();
6529 Vec != VecEnd; ++Vec) {
6530 QualType VecTy = *Vec;
6531 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6532 }
6533 }
6534
6535 // C++ [over.match.oper]p16:
6536 // For every pointer to member type T, there exist candidate operator
6537 // functions of the form
6538 //
6539 // bool operator==(T,T);
6540 // bool operator!=(T,T);
6541 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6542 /// Set of (canonical) types that we've already handled.
6543 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6544
6545 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6546 for (BuiltinCandidateTypeSet::iterator
6547 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6548 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6549 MemPtr != MemPtrEnd;
6550 ++MemPtr) {
6551 // Don't add the same builtin candidate twice.
6552 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6553 continue;
6554
6555 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6556 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6557 CandidateSet);
6558 }
6559 }
6560 }
6561
6562 // C++ [over.built]p15:
6563 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006564 // For every T, where T is an enumeration type, a pointer type, or
6565 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006566 //
6567 // bool operator<(T, T);
6568 // bool operator>(T, T);
6569 // bool operator<=(T, T);
6570 // bool operator>=(T, T);
6571 // bool operator==(T, T);
6572 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006573 void addRelationalPointerOrEnumeralOverloads() {
6574 // C++ [over.built]p1:
6575 // If there is a user-written candidate with the same name and parameter
6576 // types as a built-in candidate operator function, the built-in operator
6577 // function is hidden and is not included in the set of candidate
6578 // functions.
6579 //
6580 // The text is actually in a note, but if we don't implement it then we end
6581 // up with ambiguities when the user provides an overloaded operator for
6582 // an enumeration type. Note that only enumeration types have this problem,
6583 // so we track which enumeration types we've seen operators for. Also, the
6584 // only other overloaded operator with enumeration argumenst, operator=,
6585 // cannot be overloaded for enumeration types, so this is the only place
6586 // where we must suppress candidates like this.
6587 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6588 UserDefinedBinaryOperators;
6589
6590 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6591 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6592 CandidateTypes[ArgIdx].enumeration_end()) {
6593 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6594 CEnd = CandidateSet.end();
6595 C != CEnd; ++C) {
6596 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6597 continue;
6598
6599 QualType FirstParamType =
6600 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6601 QualType SecondParamType =
6602 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6603
6604 // Skip if either parameter isn't of enumeral type.
6605 if (!FirstParamType->isEnumeralType() ||
6606 !SecondParamType->isEnumeralType())
6607 continue;
6608
6609 // Add this operator to the set of known user-defined operators.
6610 UserDefinedBinaryOperators.insert(
6611 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6612 S.Context.getCanonicalType(SecondParamType)));
6613 }
6614 }
6615 }
6616
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006617 /// Set of (canonical) types that we've already handled.
6618 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6619
6620 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6621 for (BuiltinCandidateTypeSet::iterator
6622 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6623 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6624 Ptr != PtrEnd; ++Ptr) {
6625 // Don't add the same builtin candidate twice.
6626 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6627 continue;
6628
6629 QualType ParamTypes[2] = { *Ptr, *Ptr };
6630 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6631 CandidateSet);
6632 }
6633 for (BuiltinCandidateTypeSet::iterator
6634 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6635 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6636 Enum != EnumEnd; ++Enum) {
6637 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6638
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006639 // Don't add the same builtin candidate twice, or if a user defined
6640 // candidate exists.
6641 if (!AddedTypes.insert(CanonType) ||
6642 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6643 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006644 continue;
6645
6646 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006647 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6648 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006649 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006650
6651 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6652 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6653 if (AddedTypes.insert(NullPtrTy) &&
6654 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6655 NullPtrTy))) {
6656 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6657 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6658 CandidateSet);
6659 }
6660 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006661 }
6662 }
6663
6664 // C++ [over.built]p13:
6665 //
6666 // For every cv-qualified or cv-unqualified object type T
6667 // there exist candidate operator functions of the form
6668 //
6669 // T* operator+(T*, ptrdiff_t);
6670 // T& operator[](T*, ptrdiff_t); [BELOW]
6671 // T* operator-(T*, ptrdiff_t);
6672 // T* operator+(ptrdiff_t, T*);
6673 // T& operator[](ptrdiff_t, T*); [BELOW]
6674 //
6675 // C++ [over.built]p14:
6676 //
6677 // For every T, where T is a pointer to object type, there
6678 // exist candidate operator functions of the form
6679 //
6680 // ptrdiff_t operator-(T, T);
6681 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6682 /// Set of (canonical) types that we've already handled.
6683 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6684
6685 for (int Arg = 0; Arg < 2; ++Arg) {
6686 QualType AsymetricParamTypes[2] = {
6687 S.Context.getPointerDiffType(),
6688 S.Context.getPointerDiffType(),
6689 };
6690 for (BuiltinCandidateTypeSet::iterator
6691 Ptr = CandidateTypes[Arg].pointer_begin(),
6692 PtrEnd = CandidateTypes[Arg].pointer_end();
6693 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006694 QualType PointeeTy = (*Ptr)->getPointeeType();
6695 if (!PointeeTy->isObjectType())
6696 continue;
6697
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006698 AsymetricParamTypes[Arg] = *Ptr;
6699 if (Arg == 0 || Op == OO_Plus) {
6700 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6701 // T* operator+(ptrdiff_t, T*);
6702 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6703 CandidateSet);
6704 }
6705 if (Op == OO_Minus) {
6706 // ptrdiff_t operator-(T, T);
6707 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6708 continue;
6709
6710 QualType ParamTypes[2] = { *Ptr, *Ptr };
6711 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6712 Args, 2, CandidateSet);
6713 }
6714 }
6715 }
6716 }
6717
6718 // C++ [over.built]p12:
6719 //
6720 // For every pair of promoted arithmetic types L and R, there
6721 // exist candidate operator functions of the form
6722 //
6723 // LR operator*(L, R);
6724 // LR operator/(L, R);
6725 // LR operator+(L, R);
6726 // LR operator-(L, R);
6727 // bool operator<(L, R);
6728 // bool operator>(L, R);
6729 // bool operator<=(L, R);
6730 // bool operator>=(L, R);
6731 // bool operator==(L, R);
6732 // bool operator!=(L, R);
6733 //
6734 // where LR is the result of the usual arithmetic conversions
6735 // between types L and R.
6736 //
6737 // C++ [over.built]p24:
6738 //
6739 // For every pair of promoted arithmetic types L and R, there exist
6740 // candidate operator functions of the form
6741 //
6742 // LR operator?(bool, L, R);
6743 //
6744 // where LR is the result of the usual arithmetic conversions
6745 // between types L and R.
6746 // Our candidates ignore the first parameter.
6747 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006748 if (!HasArithmeticOrEnumeralCandidateType)
6749 return;
6750
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006751 for (unsigned Left = FirstPromotedArithmeticType;
6752 Left < LastPromotedArithmeticType; ++Left) {
6753 for (unsigned Right = FirstPromotedArithmeticType;
6754 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006755 QualType LandR[2] = { getArithmeticType(Left),
6756 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006757 QualType Result =
6758 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006759 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006760 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6761 }
6762 }
6763
6764 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6765 // conditional operator for vector types.
6766 for (BuiltinCandidateTypeSet::iterator
6767 Vec1 = CandidateTypes[0].vector_begin(),
6768 Vec1End = CandidateTypes[0].vector_end();
6769 Vec1 != Vec1End; ++Vec1) {
6770 for (BuiltinCandidateTypeSet::iterator
6771 Vec2 = CandidateTypes[1].vector_begin(),
6772 Vec2End = CandidateTypes[1].vector_end();
6773 Vec2 != Vec2End; ++Vec2) {
6774 QualType LandR[2] = { *Vec1, *Vec2 };
6775 QualType Result = S.Context.BoolTy;
6776 if (!isComparison) {
6777 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6778 Result = *Vec1;
6779 else
6780 Result = *Vec2;
6781 }
6782
6783 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6784 }
6785 }
6786 }
6787
6788 // C++ [over.built]p17:
6789 //
6790 // For every pair of promoted integral types L and R, there
6791 // exist candidate operator functions of the form
6792 //
6793 // LR operator%(L, R);
6794 // LR operator&(L, R);
6795 // LR operator^(L, R);
6796 // LR operator|(L, R);
6797 // L operator<<(L, R);
6798 // L operator>>(L, R);
6799 //
6800 // where LR is the result of the usual arithmetic conversions
6801 // between types L and R.
6802 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006803 if (!HasArithmeticOrEnumeralCandidateType)
6804 return;
6805
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006806 for (unsigned Left = FirstPromotedIntegralType;
6807 Left < LastPromotedIntegralType; ++Left) {
6808 for (unsigned Right = FirstPromotedIntegralType;
6809 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006810 QualType LandR[2] = { getArithmeticType(Left),
6811 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006812 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6813 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006814 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006815 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6816 }
6817 }
6818 }
6819
6820 // C++ [over.built]p20:
6821 //
6822 // For every pair (T, VQ), where T is an enumeration or
6823 // pointer to member type and VQ is either volatile or
6824 // empty, there exist candidate operator functions of the form
6825 //
6826 // VQ T& operator=(VQ T&, T);
6827 void addAssignmentMemberPointerOrEnumeralOverloads() {
6828 /// Set of (canonical) types that we've already handled.
6829 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6830
6831 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6832 for (BuiltinCandidateTypeSet::iterator
6833 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6834 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6835 Enum != EnumEnd; ++Enum) {
6836 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6837 continue;
6838
6839 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6840 CandidateSet);
6841 }
6842
6843 for (BuiltinCandidateTypeSet::iterator
6844 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6845 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6846 MemPtr != MemPtrEnd; ++MemPtr) {
6847 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6848 continue;
6849
6850 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6851 CandidateSet);
6852 }
6853 }
6854 }
6855
6856 // C++ [over.built]p19:
6857 //
6858 // For every pair (T, VQ), where T is any type and VQ is either
6859 // volatile or empty, there exist candidate operator functions
6860 // of the form
6861 //
6862 // T*VQ& operator=(T*VQ&, T*);
6863 //
6864 // C++ [over.built]p21:
6865 //
6866 // For every pair (T, VQ), where T is a cv-qualified or
6867 // cv-unqualified object type and VQ is either volatile or
6868 // empty, there exist candidate operator functions of the form
6869 //
6870 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6871 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6872 void addAssignmentPointerOverloads(bool isEqualOp) {
6873 /// Set of (canonical) types that we've already handled.
6874 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6875
6876 for (BuiltinCandidateTypeSet::iterator
6877 Ptr = CandidateTypes[0].pointer_begin(),
6878 PtrEnd = CandidateTypes[0].pointer_end();
6879 Ptr != PtrEnd; ++Ptr) {
6880 // If this is operator=, keep track of the builtin candidates we added.
6881 if (isEqualOp)
6882 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006883 else if (!(*Ptr)->getPointeeType()->isObjectType())
6884 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006885
6886 // non-volatile version
6887 QualType ParamTypes[2] = {
6888 S.Context.getLValueReferenceType(*Ptr),
6889 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6890 };
6891 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6892 /*IsAssigmentOperator=*/ isEqualOp);
6893
6894 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6895 VisibleTypeConversionsQuals.hasVolatile()) {
6896 // volatile version
6897 ParamTypes[0] =
6898 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6900 /*IsAssigmentOperator=*/isEqualOp);
6901 }
6902 }
6903
6904 if (isEqualOp) {
6905 for (BuiltinCandidateTypeSet::iterator
6906 Ptr = CandidateTypes[1].pointer_begin(),
6907 PtrEnd = CandidateTypes[1].pointer_end();
6908 Ptr != PtrEnd; ++Ptr) {
6909 // Make sure we don't add the same candidate twice.
6910 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6911 continue;
6912
Chandler Carruth6df868e2010-12-12 08:17:55 +00006913 QualType ParamTypes[2] = {
6914 S.Context.getLValueReferenceType(*Ptr),
6915 *Ptr,
6916 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006917
6918 // non-volatile version
6919 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6920 /*IsAssigmentOperator=*/true);
6921
6922 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6923 VisibleTypeConversionsQuals.hasVolatile()) {
6924 // volatile version
6925 ParamTypes[0] =
6926 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00006927 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6928 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006929 }
6930 }
6931 }
6932 }
6933
6934 // C++ [over.built]p18:
6935 //
6936 // For every triple (L, VQ, R), where L is an arithmetic type,
6937 // VQ is either volatile or empty, and R is a promoted
6938 // arithmetic type, there exist candidate operator functions of
6939 // the form
6940 //
6941 // VQ L& operator=(VQ L&, R);
6942 // VQ L& operator*=(VQ L&, R);
6943 // VQ L& operator/=(VQ L&, R);
6944 // VQ L& operator+=(VQ L&, R);
6945 // VQ L& operator-=(VQ L&, R);
6946 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006947 if (!HasArithmeticOrEnumeralCandidateType)
6948 return;
6949
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006950 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6951 for (unsigned Right = FirstPromotedArithmeticType;
6952 Right < LastPromotedArithmeticType; ++Right) {
6953 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006954 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006955
6956 // Add this built-in operator as a candidate (VQ is empty).
6957 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006958 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006959 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6960 /*IsAssigmentOperator=*/isEqualOp);
6961
6962 // Add this built-in operator as a candidate (VQ is 'volatile').
6963 if (VisibleTypeConversionsQuals.hasVolatile()) {
6964 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006965 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006966 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006967 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6968 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006969 /*IsAssigmentOperator=*/isEqualOp);
6970 }
6971 }
6972 }
6973
6974 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6975 for (BuiltinCandidateTypeSet::iterator
6976 Vec1 = CandidateTypes[0].vector_begin(),
6977 Vec1End = CandidateTypes[0].vector_end();
6978 Vec1 != Vec1End; ++Vec1) {
6979 for (BuiltinCandidateTypeSet::iterator
6980 Vec2 = CandidateTypes[1].vector_begin(),
6981 Vec2End = CandidateTypes[1].vector_end();
6982 Vec2 != Vec2End; ++Vec2) {
6983 QualType ParamTypes[2];
6984 ParamTypes[1] = *Vec2;
6985 // Add this built-in operator as a candidate (VQ is empty).
6986 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6987 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6988 /*IsAssigmentOperator=*/isEqualOp);
6989
6990 // Add this built-in operator as a candidate (VQ is 'volatile').
6991 if (VisibleTypeConversionsQuals.hasVolatile()) {
6992 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6993 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006994 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6995 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006996 /*IsAssigmentOperator=*/isEqualOp);
6997 }
6998 }
6999 }
7000 }
7001
7002 // C++ [over.built]p22:
7003 //
7004 // For every triple (L, VQ, R), where L is an integral type, VQ
7005 // is either volatile or empty, and R is a promoted integral
7006 // type, there exist candidate operator functions of the form
7007 //
7008 // VQ L& operator%=(VQ L&, R);
7009 // VQ L& operator<<=(VQ L&, R);
7010 // VQ L& operator>>=(VQ L&, R);
7011 // VQ L& operator&=(VQ L&, R);
7012 // VQ L& operator^=(VQ L&, R);
7013 // VQ L& operator|=(VQ L&, R);
7014 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007015 if (!HasArithmeticOrEnumeralCandidateType)
7016 return;
7017
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007018 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7019 for (unsigned Right = FirstPromotedIntegralType;
7020 Right < LastPromotedIntegralType; ++Right) {
7021 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007022 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007023
7024 // Add this built-in operator as a candidate (VQ is empty).
7025 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007026 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007027 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7028 if (VisibleTypeConversionsQuals.hasVolatile()) {
7029 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007030 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007031 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7032 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7033 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7034 CandidateSet);
7035 }
7036 }
7037 }
7038 }
7039
7040 // C++ [over.operator]p23:
7041 //
7042 // There also exist candidate operator functions of the form
7043 //
7044 // bool operator!(bool);
7045 // bool operator&&(bool, bool);
7046 // bool operator||(bool, bool);
7047 void addExclaimOverload() {
7048 QualType ParamTy = S.Context.BoolTy;
7049 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7050 /*IsAssignmentOperator=*/false,
7051 /*NumContextualBoolArguments=*/1);
7052 }
7053 void addAmpAmpOrPipePipeOverload() {
7054 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7055 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7056 /*IsAssignmentOperator=*/false,
7057 /*NumContextualBoolArguments=*/2);
7058 }
7059
7060 // C++ [over.built]p13:
7061 //
7062 // For every cv-qualified or cv-unqualified object type T there
7063 // exist candidate operator functions of the form
7064 //
7065 // T* operator+(T*, ptrdiff_t); [ABOVE]
7066 // T& operator[](T*, ptrdiff_t);
7067 // T* operator-(T*, ptrdiff_t); [ABOVE]
7068 // T* operator+(ptrdiff_t, T*); [ABOVE]
7069 // T& operator[](ptrdiff_t, T*);
7070 void addSubscriptOverloads() {
7071 for (BuiltinCandidateTypeSet::iterator
7072 Ptr = CandidateTypes[0].pointer_begin(),
7073 PtrEnd = CandidateTypes[0].pointer_end();
7074 Ptr != PtrEnd; ++Ptr) {
7075 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7076 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007077 if (!PointeeType->isObjectType())
7078 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007079
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007080 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7081
7082 // T& operator[](T*, ptrdiff_t)
7083 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7084 }
7085
7086 for (BuiltinCandidateTypeSet::iterator
7087 Ptr = CandidateTypes[1].pointer_begin(),
7088 PtrEnd = CandidateTypes[1].pointer_end();
7089 Ptr != PtrEnd; ++Ptr) {
7090 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7091 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007092 if (!PointeeType->isObjectType())
7093 continue;
7094
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007095 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7096
7097 // T& operator[](ptrdiff_t, T*)
7098 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7099 }
7100 }
7101
7102 // C++ [over.built]p11:
7103 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7104 // C1 is the same type as C2 or is a derived class of C2, T is an object
7105 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7106 // there exist candidate operator functions of the form
7107 //
7108 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7109 //
7110 // where CV12 is the union of CV1 and CV2.
7111 void addArrowStarOverloads() {
7112 for (BuiltinCandidateTypeSet::iterator
7113 Ptr = CandidateTypes[0].pointer_begin(),
7114 PtrEnd = CandidateTypes[0].pointer_end();
7115 Ptr != PtrEnd; ++Ptr) {
7116 QualType C1Ty = (*Ptr);
7117 QualType C1;
7118 QualifierCollector Q1;
7119 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7120 if (!isa<RecordType>(C1))
7121 continue;
7122 // heuristic to reduce number of builtin candidates in the set.
7123 // Add volatile/restrict version only if there are conversions to a
7124 // volatile/restrict type.
7125 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7126 continue;
7127 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7128 continue;
7129 for (BuiltinCandidateTypeSet::iterator
7130 MemPtr = CandidateTypes[1].member_pointer_begin(),
7131 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7132 MemPtr != MemPtrEnd; ++MemPtr) {
7133 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7134 QualType C2 = QualType(mptr->getClass(), 0);
7135 C2 = C2.getUnqualifiedType();
7136 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7137 break;
7138 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7139 // build CV12 T&
7140 QualType T = mptr->getPointeeType();
7141 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7142 T.isVolatileQualified())
7143 continue;
7144 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7145 T.isRestrictQualified())
7146 continue;
7147 T = Q1.apply(S.Context, T);
7148 QualType ResultTy = S.Context.getLValueReferenceType(T);
7149 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7150 }
7151 }
7152 }
7153
7154 // Note that we don't consider the first argument, since it has been
7155 // contextually converted to bool long ago. The candidates below are
7156 // therefore added as binary.
7157 //
7158 // C++ [over.built]p25:
7159 // For every type T, where T is a pointer, pointer-to-member, or scoped
7160 // enumeration type, there exist candidate operator functions of the form
7161 //
7162 // T operator?(bool, T, T);
7163 //
7164 void addConditionalOperatorOverloads() {
7165 /// Set of (canonical) types that we've already handled.
7166 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7167
7168 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7169 for (BuiltinCandidateTypeSet::iterator
7170 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7171 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7172 Ptr != PtrEnd; ++Ptr) {
7173 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7174 continue;
7175
7176 QualType ParamTypes[2] = { *Ptr, *Ptr };
7177 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7178 }
7179
7180 for (BuiltinCandidateTypeSet::iterator
7181 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7182 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7183 MemPtr != MemPtrEnd; ++MemPtr) {
7184 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7185 continue;
7186
7187 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7188 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7189 }
7190
7191 if (S.getLangOptions().CPlusPlus0x) {
7192 for (BuiltinCandidateTypeSet::iterator
7193 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7194 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7195 Enum != EnumEnd; ++Enum) {
7196 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7197 continue;
7198
7199 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7200 continue;
7201
7202 QualType ParamTypes[2] = { *Enum, *Enum };
7203 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7204 }
7205 }
7206 }
7207 }
7208};
7209
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007210} // end anonymous namespace
7211
7212/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7213/// operator overloads to the candidate set (C++ [over.built]), based
7214/// on the operator @p Op and the arguments given. For example, if the
7215/// operator is a binary '+', this routine might add "int
7216/// operator+(int, int)" to cover integer addition.
7217void
7218Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7219 SourceLocation OpLoc,
7220 Expr **Args, unsigned NumArgs,
7221 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007222 // Find all of the types that the arguments can convert to, but only
7223 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007224 // that make use of these types. Also record whether we encounter non-record
7225 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007226 Qualifiers VisibleTypeConversionsQuals;
7227 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007228 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7229 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007230
7231 bool HasNonRecordCandidateType = false;
7232 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007233 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007234 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7235 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7236 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7237 OpLoc,
7238 true,
7239 (Op == OO_Exclaim ||
7240 Op == OO_AmpAmp ||
7241 Op == OO_PipePipe),
7242 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007243 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7244 CandidateTypes[ArgIdx].hasNonRecordTypes();
7245 HasArithmeticOrEnumeralCandidateType =
7246 HasArithmeticOrEnumeralCandidateType ||
7247 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007248 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007249
Chandler Carruth6a577462010-12-13 01:44:01 +00007250 // Exit early when no non-record types have been added to the candidate set
7251 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007252 //
7253 // We can't exit early for !, ||, or &&, since there we have always have
7254 // 'bool' overloads.
7255 if (!HasNonRecordCandidateType &&
7256 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007257 return;
7258
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007259 // Setup an object to manage the common state for building overloads.
7260 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7261 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007262 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007263 CandidateTypes, CandidateSet);
7264
7265 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007266 switch (Op) {
7267 case OO_None:
7268 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007269 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007270
Chandler Carruthabb71842010-12-12 08:51:33 +00007271 case OO_New:
7272 case OO_Delete:
7273 case OO_Array_New:
7274 case OO_Array_Delete:
7275 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007276 llvm_unreachable(
7277 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007278
7279 case OO_Comma:
7280 case OO_Arrow:
7281 // C++ [over.match.oper]p3:
7282 // -- For the operator ',', the unary operator '&', or the
7283 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007284 break;
7285
7286 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007287 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007288 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007289 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007290
7291 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007292 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007293 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007294 } else {
7295 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7296 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7297 }
Douglas Gregor74253732008-11-19 15:42:04 +00007298 break;
7299
Chandler Carruthabb71842010-12-12 08:51:33 +00007300 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007301 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007302 OpBuilder.addUnaryStarPointerOverloads();
7303 else
7304 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7305 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007306
Chandler Carruthabb71842010-12-12 08:51:33 +00007307 case OO_Slash:
7308 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007309 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007310
7311 case OO_PlusPlus:
7312 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007313 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7314 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007315 break;
7316
Douglas Gregor19b7b152009-08-24 13:43:27 +00007317 case OO_EqualEqual:
7318 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007319 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007320 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007321
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007322 case OO_Less:
7323 case OO_Greater:
7324 case OO_LessEqual:
7325 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007326 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007327 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7328 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007329
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007330 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007331 case OO_Caret:
7332 case OO_Pipe:
7333 case OO_LessLess:
7334 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007335 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007336 break;
7337
Chandler Carruthabb71842010-12-12 08:51:33 +00007338 case OO_Amp: // '&' is either unary or binary
7339 if (NumArgs == 1)
7340 // C++ [over.match.oper]p3:
7341 // -- For the operator ',', the unary operator '&', or the
7342 // operator '->', the built-in candidates set is empty.
7343 break;
7344
7345 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7346 break;
7347
7348 case OO_Tilde:
7349 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7350 break;
7351
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007352 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007353 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007354 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007355
7356 case OO_PlusEqual:
7357 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007358 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007359 // Fall through.
7360
7361 case OO_StarEqual:
7362 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007363 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007364 break;
7365
7366 case OO_PercentEqual:
7367 case OO_LessLessEqual:
7368 case OO_GreaterGreaterEqual:
7369 case OO_AmpEqual:
7370 case OO_CaretEqual:
7371 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007372 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007373 break;
7374
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007375 case OO_Exclaim:
7376 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007377 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007378
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007379 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007380 case OO_PipePipe:
7381 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007382 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007383
7384 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007385 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007386 break;
7387
7388 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007389 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007390 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007391
7392 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007393 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007394 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7395 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007396 }
7397}
7398
Douglas Gregorfa047642009-02-04 00:32:51 +00007399/// \brief Add function candidates found via argument-dependent lookup
7400/// to the set of overloading candidates.
7401///
7402/// This routine performs argument-dependent name lookup based on the
7403/// given function name (which may also be an operator name) and adds
7404/// all of the overload candidates found by ADL to the overload
7405/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007406void
Douglas Gregorfa047642009-02-04 00:32:51 +00007407Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00007408 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00007409 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00007410 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007411 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007412 bool PartialOverloading,
7413 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007414 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007415
John McCalla113e722010-01-26 06:04:06 +00007416 // FIXME: This approach for uniquing ADL results (and removing
7417 // redundant candidates from the set) relies on pointer-equality,
7418 // which means we need to key off the canonical decl. However,
7419 // always going back to the canonical decl might not get us the
7420 // right set of default arguments. What default arguments are
7421 // we supposed to consider on ADL candidates, anyway?
7422
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007423 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00007424 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
7425 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007426
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007427 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007428 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7429 CandEnd = CandidateSet.end();
7430 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007431 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007432 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007433 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007434 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007435 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007436
7437 // For each of the ADL candidates we found, add it to the overload
7438 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007439 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007440 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007441 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007442 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007443 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007444
John McCall9aa472c2010-03-19 07:35:19 +00007445 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00007446 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007447 } else
John McCall6e266892010-01-26 03:27:55 +00007448 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007449 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00007450 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007451 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007452}
7453
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007454/// isBetterOverloadCandidate - Determines whether the first overload
7455/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007456bool
John McCall120d63c2010-08-24 20:38:10 +00007457isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007458 const OverloadCandidate &Cand1,
7459 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007460 SourceLocation Loc,
7461 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007462 // Define viable functions to be better candidates than non-viable
7463 // functions.
7464 if (!Cand2.Viable)
7465 return Cand1.Viable;
7466 else if (!Cand1.Viable)
7467 return false;
7468
Douglas Gregor88a35142008-12-22 05:46:06 +00007469 // C++ [over.match.best]p1:
7470 //
7471 // -- if F is a static member function, ICS1(F) is defined such
7472 // that ICS1(F) is neither better nor worse than ICS1(G) for
7473 // any function G, and, symmetrically, ICS1(G) is neither
7474 // better nor worse than ICS1(F).
7475 unsigned StartArg = 0;
7476 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7477 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007478
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007479 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007480 // A viable function F1 is defined to be a better function than another
7481 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007482 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007483 unsigned NumArgs = Cand1.NumConversions;
7484 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007485 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007486 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007487 switch (CompareImplicitConversionSequences(S,
7488 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007489 Cand2.Conversions[ArgIdx])) {
7490 case ImplicitConversionSequence::Better:
7491 // Cand1 has a better conversion sequence.
7492 HasBetterConversion = true;
7493 break;
7494
7495 case ImplicitConversionSequence::Worse:
7496 // Cand1 can't be better than Cand2.
7497 return false;
7498
7499 case ImplicitConversionSequence::Indistinguishable:
7500 // Do nothing.
7501 break;
7502 }
7503 }
7504
Mike Stump1eb44332009-09-09 15:08:12 +00007505 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007506 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007507 if (HasBetterConversion)
7508 return true;
7509
Mike Stump1eb44332009-09-09 15:08:12 +00007510 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007511 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007512 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007513 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7514 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007515
7516 // -- F1 and F2 are function template specializations, and the function
7517 // template for F1 is more specialized than the template for F2
7518 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007519 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007520 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007521 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007522 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007523 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7524 Cand2.Function->getPrimaryTemplate(),
7525 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007526 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007527 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007528 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007529 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007530 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007531
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007532 // -- the context is an initialization by user-defined conversion
7533 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7534 // from the return type of F1 to the destination type (i.e.,
7535 // the type of the entity being initialized) is a better
7536 // conversion sequence than the standard conversion sequence
7537 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007538 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007539 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007540 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00007541 switch (CompareStandardConversionSequences(S,
7542 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007543 Cand2.FinalConversion)) {
7544 case ImplicitConversionSequence::Better:
7545 // Cand1 has a better conversion sequence.
7546 return true;
7547
7548 case ImplicitConversionSequence::Worse:
7549 // Cand1 can't be better than Cand2.
7550 return false;
7551
7552 case ImplicitConversionSequence::Indistinguishable:
7553 // Do nothing
7554 break;
7555 }
7556 }
7557
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007558 return false;
7559}
7560
Mike Stump1eb44332009-09-09 15:08:12 +00007561/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007562/// within an overload candidate set.
7563///
7564/// \param CandidateSet the set of candidate functions.
7565///
7566/// \param Loc the location of the function name (or operator symbol) for
7567/// which overload resolution occurs.
7568///
Mike Stump1eb44332009-09-09 15:08:12 +00007569/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007570/// function, Best points to the candidate function found.
7571///
7572/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007573OverloadingResult
7574OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007575 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007576 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007577 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007578 Best = end();
7579 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7580 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007581 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007582 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007583 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007584 }
7585
7586 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007587 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007588 return OR_No_Viable_Function;
7589
7590 // Make sure that this function is better than every other viable
7591 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007592 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007593 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007594 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007595 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007596 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007597 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007598 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007599 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007600 }
Mike Stump1eb44332009-09-09 15:08:12 +00007601
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007602 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007603 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007604 (Best->Function->isDeleted() ||
7605 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007606 return OR_Deleted;
7607
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007608 return OR_Success;
7609}
7610
John McCall3c80f572010-01-12 02:15:36 +00007611namespace {
7612
7613enum OverloadCandidateKind {
7614 oc_function,
7615 oc_method,
7616 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007617 oc_function_template,
7618 oc_method_template,
7619 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007620 oc_implicit_default_constructor,
7621 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007622 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007623 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007624 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007625 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007626};
7627
John McCall220ccbf2010-01-13 00:25:19 +00007628OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7629 FunctionDecl *Fn,
7630 std::string &Description) {
7631 bool isTemplate = false;
7632
7633 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7634 isTemplate = true;
7635 Description = S.getTemplateArgumentBindingsText(
7636 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7637 }
John McCallb1622a12010-01-06 09:43:14 +00007638
7639 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007640 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007641 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007642
Sebastian Redlf677ea32011-02-05 19:23:19 +00007643 if (Ctor->getInheritedConstructor())
7644 return oc_implicit_inherited_constructor;
7645
Sean Hunt82713172011-05-25 23:16:36 +00007646 if (Ctor->isDefaultConstructor())
7647 return oc_implicit_default_constructor;
7648
7649 if (Ctor->isMoveConstructor())
7650 return oc_implicit_move_constructor;
7651
7652 assert(Ctor->isCopyConstructor() &&
7653 "unexpected sort of implicit constructor");
7654 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007655 }
7656
7657 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7658 // This actually gets spelled 'candidate function' for now, but
7659 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007660 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007661 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007662
Sean Hunt82713172011-05-25 23:16:36 +00007663 if (Meth->isMoveAssignmentOperator())
7664 return oc_implicit_move_assignment;
7665
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007666 if (Meth->isCopyAssignmentOperator())
7667 return oc_implicit_copy_assignment;
7668
7669 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7670 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007671 }
7672
John McCall220ccbf2010-01-13 00:25:19 +00007673 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007674}
7675
Sebastian Redlf677ea32011-02-05 19:23:19 +00007676void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7677 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7678 if (!Ctor) return;
7679
7680 Ctor = Ctor->getInheritedConstructor();
7681 if (!Ctor) return;
7682
7683 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7684}
7685
John McCall3c80f572010-01-12 02:15:36 +00007686} // end anonymous namespace
7687
7688// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007689void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007690 std::string FnDesc;
7691 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007692 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7693 << (unsigned) K << FnDesc;
7694 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7695 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007696 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007697}
7698
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007699//Notes the location of all overload candidates designated through
7700// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007701void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007702 assert(OverloadedExpr->getType() == Context.OverloadTy);
7703
7704 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7705 OverloadExpr *OvlExpr = Ovl.Expression;
7706
7707 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7708 IEnd = OvlExpr->decls_end();
7709 I != IEnd; ++I) {
7710 if (FunctionTemplateDecl *FunTmpl =
7711 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007712 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007713 } else if (FunctionDecl *Fun
7714 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007715 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007716 }
7717 }
7718}
7719
John McCall1d318332010-01-12 00:44:57 +00007720/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7721/// "lead" diagnostic; it will be given two arguments, the source and
7722/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007723void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7724 Sema &S,
7725 SourceLocation CaretLoc,
7726 const PartialDiagnostic &PDiag) const {
7727 S.Diag(CaretLoc, PDiag)
7728 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007729 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007730 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7731 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007732 }
John McCall81201622010-01-08 04:41:39 +00007733}
7734
John McCall1d318332010-01-12 00:44:57 +00007735namespace {
7736
John McCalladbb8f82010-01-13 09:16:55 +00007737void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7738 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7739 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007740 assert(Cand->Function && "for now, candidate must be a function");
7741 FunctionDecl *Fn = Cand->Function;
7742
7743 // There's a conversion slot for the object argument if this is a
7744 // non-constructor method. Note that 'I' corresponds the
7745 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007746 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007747 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007748 if (I == 0)
7749 isObjectArgument = true;
7750 else
7751 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007752 }
7753
John McCall220ccbf2010-01-13 00:25:19 +00007754 std::string FnDesc;
7755 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7756
John McCalladbb8f82010-01-13 09:16:55 +00007757 Expr *FromExpr = Conv.Bad.FromExpr;
7758 QualType FromTy = Conv.Bad.getFromType();
7759 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007760
John McCall5920dbb2010-02-02 02:42:52 +00007761 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007762 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007763 Expr *E = FromExpr->IgnoreParens();
7764 if (isa<UnaryOperator>(E))
7765 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007766 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007767
7768 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7769 << (unsigned) FnKind << FnDesc
7770 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7771 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007772 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007773 return;
7774 }
7775
John McCall258b2032010-01-23 08:10:49 +00007776 // Do some hand-waving analysis to see if the non-viability is due
7777 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007778 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7779 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7780 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7781 CToTy = RT->getPointeeType();
7782 else {
7783 // TODO: detect and diagnose the full richness of const mismatches.
7784 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7785 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7786 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7787 }
7788
7789 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7790 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7791 // It is dumb that we have to do this here.
7792 while (isa<ArrayType>(CFromTy))
7793 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7794 while (isa<ArrayType>(CToTy))
7795 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7796
7797 Qualifiers FromQs = CFromTy.getQualifiers();
7798 Qualifiers ToQs = CToTy.getQualifiers();
7799
7800 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7801 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7802 << (unsigned) FnKind << FnDesc
7803 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7804 << FromTy
7805 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7806 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007807 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007808 return;
7809 }
7810
John McCallf85e1932011-06-15 23:02:42 +00007811 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007812 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007813 << (unsigned) FnKind << FnDesc
7814 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7815 << FromTy
7816 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7817 << (unsigned) isObjectArgument << I+1;
7818 MaybeEmitInheritedConstructorNote(S, Fn);
7819 return;
7820 }
7821
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007822 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7823 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7824 << (unsigned) FnKind << FnDesc
7825 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7826 << FromTy
7827 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7828 << (unsigned) isObjectArgument << I+1;
7829 MaybeEmitInheritedConstructorNote(S, Fn);
7830 return;
7831 }
7832
John McCall651f3ee2010-01-14 03:28:57 +00007833 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7834 assert(CVR && "unexpected qualifiers mismatch");
7835
7836 if (isObjectArgument) {
7837 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7838 << (unsigned) FnKind << FnDesc
7839 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7840 << FromTy << (CVR - 1);
7841 } else {
7842 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7843 << (unsigned) FnKind << FnDesc
7844 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7845 << FromTy << (CVR - 1) << I+1;
7846 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007847 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007848 return;
7849 }
7850
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007851 // Special diagnostic for failure to convert an initializer list, since
7852 // telling the user that it has type void is not useful.
7853 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7854 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7855 << (unsigned) FnKind << FnDesc
7856 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7857 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7858 MaybeEmitInheritedConstructorNote(S, Fn);
7859 return;
7860 }
7861
John McCall258b2032010-01-23 08:10:49 +00007862 // Diagnose references or pointers to incomplete types differently,
7863 // since it's far from impossible that the incompleteness triggered
7864 // the failure.
7865 QualType TempFromTy = FromTy.getNonReferenceType();
7866 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7867 TempFromTy = PTy->getPointeeType();
7868 if (TempFromTy->isIncompleteType()) {
7869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7870 << (unsigned) FnKind << FnDesc
7871 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7872 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007873 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00007874 return;
7875 }
7876
Douglas Gregor85789812010-06-30 23:01:39 +00007877 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007878 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00007879 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7880 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7881 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7882 FromPtrTy->getPointeeType()) &&
7883 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7884 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007885 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00007886 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007887 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00007888 }
7889 } else if (const ObjCObjectPointerType *FromPtrTy
7890 = FromTy->getAs<ObjCObjectPointerType>()) {
7891 if (const ObjCObjectPointerType *ToPtrTy
7892 = ToTy->getAs<ObjCObjectPointerType>())
7893 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7894 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7895 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7896 FromPtrTy->getPointeeType()) &&
7897 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007898 BaseToDerivedConversion = 2;
7899 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7900 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7901 !FromTy->isIncompleteType() &&
7902 !ToRefTy->getPointeeType()->isIncompleteType() &&
7903 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7904 BaseToDerivedConversion = 3;
7905 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007906
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007907 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007908 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007909 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00007910 << (unsigned) FnKind << FnDesc
7911 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007912 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007913 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007914 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00007915 return;
7916 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007917
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00007918 if (isa<ObjCObjectPointerType>(CFromTy) &&
7919 isa<PointerType>(CToTy)) {
7920 Qualifiers FromQs = CFromTy.getQualifiers();
7921 Qualifiers ToQs = CToTy.getQualifiers();
7922 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7923 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7924 << (unsigned) FnKind << FnDesc
7925 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7926 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7927 MaybeEmitInheritedConstructorNote(S, Fn);
7928 return;
7929 }
7930 }
7931
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007932 // Emit the generic diagnostic and, optionally, add the hints to it.
7933 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7934 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00007935 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007936 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7937 << (unsigned) (Cand->Fix.Kind);
7938
7939 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00007940 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
7941 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007942 FDiag << *HI;
7943 S.Diag(Fn->getLocation(), FDiag);
7944
Sebastian Redlf677ea32011-02-05 19:23:19 +00007945 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00007946}
7947
7948void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7949 unsigned NumFormalArgs) {
7950 // TODO: treat calls to a missing default constructor as a special case
7951
7952 FunctionDecl *Fn = Cand->Function;
7953 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7954
7955 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007956
Douglas Gregor439d3c32011-05-05 00:13:13 +00007957 // With invalid overloaded operators, it's possible that we think we
7958 // have an arity mismatch when it fact it looks like we have the
7959 // right number of arguments, because only overloaded operators have
7960 // the weird behavior of overloading member and non-member functions.
7961 // Just don't report anything.
7962 if (Fn->isInvalidDecl() &&
7963 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7964 return;
7965
John McCalladbb8f82010-01-13 09:16:55 +00007966 // at least / at most / exactly
7967 unsigned mode, modeCount;
7968 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00007969 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7970 (Cand->FailureKind == ovl_fail_bad_deduction &&
7971 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007972 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00007973 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00007974 mode = 0; // "at least"
7975 else
7976 mode = 2; // "exactly"
7977 modeCount = MinParams;
7978 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00007979 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7980 (Cand->FailureKind == ovl_fail_bad_deduction &&
7981 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00007982 if (MinParams != FnTy->getNumArgs())
7983 mode = 1; // "at most"
7984 else
7985 mode = 2; // "exactly"
7986 modeCount = FnTy->getNumArgs();
7987 }
7988
7989 std::string Description;
7990 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7991
7992 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007993 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00007994 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007995 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007996}
7997
John McCall342fec42010-02-01 18:53:26 +00007998/// Diagnose a failed template-argument deduction.
7999void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8000 Expr **Args, unsigned NumArgs) {
8001 FunctionDecl *Fn = Cand->Function; // pattern
8002
Douglas Gregora9333192010-05-08 17:41:32 +00008003 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008004 NamedDecl *ParamD;
8005 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8006 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8007 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008008 switch (Cand->DeductionFailure.Result) {
8009 case Sema::TDK_Success:
8010 llvm_unreachable("TDK_success while diagnosing bad deduction");
8011
8012 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008013 assert(ParamD && "no parameter found for incomplete deduction result");
8014 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8015 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008016 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008017 return;
8018 }
8019
John McCall57e97782010-08-05 09:05:08 +00008020 case Sema::TDK_Underqualified: {
8021 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8022 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8023
8024 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8025
8026 // Param will have been canonicalized, but it should just be a
8027 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008028 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008029 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008030 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008031 assert(S.Context.hasSameType(Param, NonCanonParam));
8032
8033 // Arg has also been canonicalized, but there's nothing we can do
8034 // about that. It also doesn't matter as much, because it won't
8035 // have any template parameters in it (because deduction isn't
8036 // done on dependent types).
8037 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8038
8039 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8040 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008041 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008042 return;
8043 }
8044
8045 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008046 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008047 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008048 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008049 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008050 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008051 which = 1;
8052 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008053 which = 2;
8054 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008055
Douglas Gregora9333192010-05-08 17:41:32 +00008056 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008057 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008058 << *Cand->DeductionFailure.getFirstArg()
8059 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008060 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008061 return;
8062 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008063
Douglas Gregorf1a84452010-05-08 19:15:54 +00008064 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008065 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008066 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008067 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008068 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8069 << ParamD->getDeclName();
8070 else {
8071 int index = 0;
8072 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8073 index = TTP->getIndex();
8074 else if (NonTypeTemplateParmDecl *NTTP
8075 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8076 index = NTTP->getIndex();
8077 else
8078 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008079 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008080 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8081 << (index + 1);
8082 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008083 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008084 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008085
Douglas Gregora18592e2010-05-08 18:13:28 +00008086 case Sema::TDK_TooManyArguments:
8087 case Sema::TDK_TooFewArguments:
8088 DiagnoseArityMismatch(S, Cand, NumArgs);
8089 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008090
8091 case Sema::TDK_InstantiationDepth:
8092 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008093 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008094 return;
8095
8096 case Sema::TDK_SubstitutionFailure: {
8097 std::string ArgString;
8098 if (TemplateArgumentList *Args
8099 = Cand->DeductionFailure.getTemplateArgumentList())
8100 ArgString = S.getTemplateArgumentBindingsText(
8101 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8102 *Args);
8103 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8104 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008105 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008106 return;
8107 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008108
John McCall342fec42010-02-01 18:53:26 +00008109 // TODO: diagnose these individually, then kill off
8110 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008111 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008112 case Sema::TDK_FailedOverloadResolution:
8113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008114 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008115 return;
8116 }
8117}
8118
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008119/// CUDA: diagnose an invalid call across targets.
8120void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8121 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8122 FunctionDecl *Callee = Cand->Function;
8123
8124 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8125 CalleeTarget = S.IdentifyCUDATarget(Callee);
8126
8127 std::string FnDesc;
8128 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8129
8130 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8131 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8132}
8133
John McCall342fec42010-02-01 18:53:26 +00008134/// Generates a 'note' diagnostic for an overload candidate. We've
8135/// already generated a primary error at the call site.
8136///
8137/// It really does need to be a single diagnostic with its caret
8138/// pointed at the candidate declaration. Yes, this creates some
8139/// major challenges of technical writing. Yes, this makes pointing
8140/// out problems with specific arguments quite awkward. It's still
8141/// better than generating twenty screens of text for every failed
8142/// overload.
8143///
8144/// It would be great to be able to express per-candidate problems
8145/// more richly for those diagnostic clients that cared, but we'd
8146/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008147void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8148 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008149 FunctionDecl *Fn = Cand->Function;
8150
John McCall81201622010-01-08 04:41:39 +00008151 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008152 if (Cand->Viable && (Fn->isDeleted() ||
8153 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008154 std::string FnDesc;
8155 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008156
8157 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00008158 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008159 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008160 return;
John McCall81201622010-01-08 04:41:39 +00008161 }
8162
John McCall220ccbf2010-01-13 00:25:19 +00008163 // We don't really have anything else to say about viable candidates.
8164 if (Cand->Viable) {
8165 S.NoteOverloadCandidate(Fn);
8166 return;
8167 }
John McCall1d318332010-01-12 00:44:57 +00008168
John McCalladbb8f82010-01-13 09:16:55 +00008169 switch (Cand->FailureKind) {
8170 case ovl_fail_too_many_arguments:
8171 case ovl_fail_too_few_arguments:
8172 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008173
John McCalladbb8f82010-01-13 09:16:55 +00008174 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00008175 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
8176
John McCall717e8912010-01-23 05:17:32 +00008177 case ovl_fail_trivial_conversion:
8178 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008179 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008180 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008181
John McCallb1bdc622010-02-25 01:37:24 +00008182 case ovl_fail_bad_conversion: {
8183 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008184 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008185 if (Cand->Conversions[I].isBad())
8186 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008187
John McCalladbb8f82010-01-13 09:16:55 +00008188 // FIXME: this currently happens when we're called from SemaInit
8189 // when user-conversion overload fails. Figure out how to handle
8190 // those conditions and diagnose them well.
8191 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008192 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008193
8194 case ovl_fail_bad_target:
8195 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008196 }
John McCalla1d7d622010-01-08 00:58:21 +00008197}
8198
8199void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8200 // Desugar the type of the surrogate down to a function type,
8201 // retaining as many typedefs as possible while still showing
8202 // the function type (and, therefore, its parameter types).
8203 QualType FnType = Cand->Surrogate->getConversionType();
8204 bool isLValueReference = false;
8205 bool isRValueReference = false;
8206 bool isPointer = false;
8207 if (const LValueReferenceType *FnTypeRef =
8208 FnType->getAs<LValueReferenceType>()) {
8209 FnType = FnTypeRef->getPointeeType();
8210 isLValueReference = true;
8211 } else if (const RValueReferenceType *FnTypeRef =
8212 FnType->getAs<RValueReferenceType>()) {
8213 FnType = FnTypeRef->getPointeeType();
8214 isRValueReference = true;
8215 }
8216 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8217 FnType = FnTypePtr->getPointeeType();
8218 isPointer = true;
8219 }
8220 // Desugar down to a function type.
8221 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8222 // Reconstruct the pointer/reference as appropriate.
8223 if (isPointer) FnType = S.Context.getPointerType(FnType);
8224 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8225 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8226
8227 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8228 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008229 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008230}
8231
8232void NoteBuiltinOperatorCandidate(Sema &S,
8233 const char *Opc,
8234 SourceLocation OpLoc,
8235 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008236 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008237 std::string TypeStr("operator");
8238 TypeStr += Opc;
8239 TypeStr += "(";
8240 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008241 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008242 TypeStr += ")";
8243 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8244 } else {
8245 TypeStr += ", ";
8246 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8247 TypeStr += ")";
8248 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8249 }
8250}
8251
8252void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8253 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008254 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008255 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8256 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008257 if (ICS.isBad()) break; // all meaningless after first invalid
8258 if (!ICS.isAmbiguous()) continue;
8259
John McCall120d63c2010-08-24 20:38:10 +00008260 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008261 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008262 }
8263}
8264
John McCall1b77e732010-01-15 23:32:50 +00008265SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8266 if (Cand->Function)
8267 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008268 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008269 return Cand->Surrogate->getLocation();
8270 return SourceLocation();
8271}
8272
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008273static unsigned
8274RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008275 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008276 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008277 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008278
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008279 case Sema::TDK_Incomplete:
8280 return 1;
8281
8282 case Sema::TDK_Underqualified:
8283 case Sema::TDK_Inconsistent:
8284 return 2;
8285
8286 case Sema::TDK_SubstitutionFailure:
8287 case Sema::TDK_NonDeducedMismatch:
8288 return 3;
8289
8290 case Sema::TDK_InstantiationDepth:
8291 case Sema::TDK_FailedOverloadResolution:
8292 return 4;
8293
8294 case Sema::TDK_InvalidExplicitArguments:
8295 return 5;
8296
8297 case Sema::TDK_TooManyArguments:
8298 case Sema::TDK_TooFewArguments:
8299 return 6;
8300 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008301 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008302}
8303
John McCallbf65c0b2010-01-12 00:48:53 +00008304struct CompareOverloadCandidatesForDisplay {
8305 Sema &S;
8306 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008307
8308 bool operator()(const OverloadCandidate *L,
8309 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008310 // Fast-path this check.
8311 if (L == R) return false;
8312
John McCall81201622010-01-08 04:41:39 +00008313 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008314 if (L->Viable) {
8315 if (!R->Viable) return true;
8316
8317 // TODO: introduce a tri-valued comparison for overload
8318 // candidates. Would be more worthwhile if we had a sort
8319 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008320 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8321 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008322 } else if (R->Viable)
8323 return false;
John McCall81201622010-01-08 04:41:39 +00008324
John McCall1b77e732010-01-15 23:32:50 +00008325 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008326
John McCall1b77e732010-01-15 23:32:50 +00008327 // Criteria by which we can sort non-viable candidates:
8328 if (!L->Viable) {
8329 // 1. Arity mismatches come after other candidates.
8330 if (L->FailureKind == ovl_fail_too_many_arguments ||
8331 L->FailureKind == ovl_fail_too_few_arguments)
8332 return false;
8333 if (R->FailureKind == ovl_fail_too_many_arguments ||
8334 R->FailureKind == ovl_fail_too_few_arguments)
8335 return true;
John McCall81201622010-01-08 04:41:39 +00008336
John McCall717e8912010-01-23 05:17:32 +00008337 // 2. Bad conversions come first and are ordered by the number
8338 // of bad conversions and quality of good conversions.
8339 if (L->FailureKind == ovl_fail_bad_conversion) {
8340 if (R->FailureKind != ovl_fail_bad_conversion)
8341 return true;
8342
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008343 // The conversion that can be fixed with a smaller number of changes,
8344 // comes first.
8345 unsigned numLFixes = L->Fix.NumConversionsFixed;
8346 unsigned numRFixes = R->Fix.NumConversionsFixed;
8347 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8348 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008349 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008350 if (numLFixes < numRFixes)
8351 return true;
8352 else
8353 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008354 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008355
John McCall717e8912010-01-23 05:17:32 +00008356 // If there's any ordering between the defined conversions...
8357 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008358 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008359
8360 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008361 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008362 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008363 switch (CompareImplicitConversionSequences(S,
8364 L->Conversions[I],
8365 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008366 case ImplicitConversionSequence::Better:
8367 leftBetter++;
8368 break;
8369
8370 case ImplicitConversionSequence::Worse:
8371 leftBetter--;
8372 break;
8373
8374 case ImplicitConversionSequence::Indistinguishable:
8375 break;
8376 }
8377 }
8378 if (leftBetter > 0) return true;
8379 if (leftBetter < 0) return false;
8380
8381 } else if (R->FailureKind == ovl_fail_bad_conversion)
8382 return false;
8383
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008384 if (L->FailureKind == ovl_fail_bad_deduction) {
8385 if (R->FailureKind != ovl_fail_bad_deduction)
8386 return true;
8387
8388 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8389 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008390 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008391 } else if (R->FailureKind == ovl_fail_bad_deduction)
8392 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008393
John McCall1b77e732010-01-15 23:32:50 +00008394 // TODO: others?
8395 }
8396
8397 // Sort everything else by location.
8398 SourceLocation LLoc = GetLocationForCandidate(L);
8399 SourceLocation RLoc = GetLocationForCandidate(R);
8400
8401 // Put candidates without locations (e.g. builtins) at the end.
8402 if (LLoc.isInvalid()) return false;
8403 if (RLoc.isInvalid()) return true;
8404
8405 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008406 }
8407};
8408
John McCall717e8912010-01-23 05:17:32 +00008409/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008410/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008411void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8412 Expr **Args, unsigned NumArgs) {
8413 assert(!Cand->Viable);
8414
8415 // Don't do anything on failures other than bad conversion.
8416 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8417
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008418 // We only want the FixIts if all the arguments can be corrected.
8419 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008420 // Use a implicit copy initialization to check conversion fixes.
8421 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008422
John McCall717e8912010-01-23 05:17:32 +00008423 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008424 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008425 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008426 while (true) {
8427 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8428 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008429 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008430 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008431 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008432 }
John McCall717e8912010-01-23 05:17:32 +00008433 }
8434
8435 if (ConvIdx == ConvCount)
8436 return;
8437
John McCallb1bdc622010-02-25 01:37:24 +00008438 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8439 "remaining conversion is initialized?");
8440
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008441 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008442 // operation somehow.
8443 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008444
8445 const FunctionProtoType* Proto;
8446 unsigned ArgIdx = ConvIdx;
8447
8448 if (Cand->IsSurrogate) {
8449 QualType ConvType
8450 = Cand->Surrogate->getConversionType().getNonReferenceType();
8451 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8452 ConvType = ConvPtrType->getPointeeType();
8453 Proto = ConvType->getAs<FunctionProtoType>();
8454 ArgIdx--;
8455 } else if (Cand->Function) {
8456 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8457 if (isa<CXXMethodDecl>(Cand->Function) &&
8458 !isa<CXXConstructorDecl>(Cand->Function))
8459 ArgIdx--;
8460 } else {
8461 // Builtin binary operator with a bad first conversion.
8462 assert(ConvCount <= 3);
8463 for (; ConvIdx != ConvCount; ++ConvIdx)
8464 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008465 = TryCopyInitialization(S, Args[ConvIdx],
8466 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008467 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008468 /*InOverloadResolution*/ true,
8469 /*AllowObjCWritebackConversion=*/
8470 S.getLangOptions().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008471 return;
8472 }
8473
8474 // Fill in the rest of the conversions.
8475 unsigned NumArgsInProto = Proto->getNumArgs();
8476 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008477 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008478 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008479 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008480 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008481 /*InOverloadResolution=*/true,
8482 /*AllowObjCWritebackConversion=*/
8483 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008484 // Store the FixIt in the candidate if it exists.
8485 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008486 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008487 }
John McCall717e8912010-01-23 05:17:32 +00008488 else
8489 Cand->Conversions[ConvIdx].setEllipsis();
8490 }
8491}
8492
John McCalla1d7d622010-01-08 00:58:21 +00008493} // end anonymous namespace
8494
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008495/// PrintOverloadCandidates - When overload resolution fails, prints
8496/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008497/// set.
John McCall120d63c2010-08-24 20:38:10 +00008498void OverloadCandidateSet::NoteCandidates(Sema &S,
8499 OverloadCandidateDisplayKind OCD,
8500 Expr **Args, unsigned NumArgs,
8501 const char *Opc,
8502 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008503 // Sort the candidates by viability and position. Sorting directly would
8504 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008505 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008506 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8507 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008508 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008509 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008510 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00008511 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008512 if (Cand->Function || Cand->IsSurrogate)
8513 Cands.push_back(Cand);
8514 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8515 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008516 }
8517 }
8518
John McCallbf65c0b2010-01-12 00:48:53 +00008519 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008520 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008521
John McCall1d318332010-01-12 00:44:57 +00008522 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008523
Chris Lattner5f9e2722011-07-23 10:55:15 +00008524 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008525 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8526 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008527 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008528 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8529 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008530
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008531 // Set an arbitrary limit on the number of candidate functions we'll spam
8532 // the user with. FIXME: This limit should depend on details of the
8533 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008534 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008535 break;
8536 }
8537 ++CandsShown;
8538
John McCalla1d7d622010-01-08 00:58:21 +00008539 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00008540 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00008541 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008542 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008543 else {
8544 assert(Cand->Viable &&
8545 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008546 // Generally we only see ambiguities including viable builtin
8547 // operators if overload resolution got screwed up by an
8548 // ambiguous user-defined conversion.
8549 //
8550 // FIXME: It's quite possible for different conversions to see
8551 // different ambiguities, though.
8552 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008553 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008554 ReportedAmbiguousConversions = true;
8555 }
John McCalla1d7d622010-01-08 00:58:21 +00008556
John McCall1d318332010-01-12 00:44:57 +00008557 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008558 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008559 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008560 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008561
8562 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008563 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008564}
8565
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008566// [PossiblyAFunctionType] --> [Return]
8567// NonFunctionType --> NonFunctionType
8568// R (A) --> R(A)
8569// R (*)(A) --> R (A)
8570// R (&)(A) --> R (A)
8571// R (S::*)(A) --> R (A)
8572QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8573 QualType Ret = PossiblyAFunctionType;
8574 if (const PointerType *ToTypePtr =
8575 PossiblyAFunctionType->getAs<PointerType>())
8576 Ret = ToTypePtr->getPointeeType();
8577 else if (const ReferenceType *ToTypeRef =
8578 PossiblyAFunctionType->getAs<ReferenceType>())
8579 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008580 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008581 PossiblyAFunctionType->getAs<MemberPointerType>())
8582 Ret = MemTypePtr->getPointeeType();
8583 Ret =
8584 Context.getCanonicalType(Ret).getUnqualifiedType();
8585 return Ret;
8586}
Douglas Gregor904eed32008-11-10 20:40:00 +00008587
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008588// A helper class to help with address of function resolution
8589// - allows us to avoid passing around all those ugly parameters
8590class AddressOfFunctionResolver
8591{
8592 Sema& S;
8593 Expr* SourceExpr;
8594 const QualType& TargetType;
8595 QualType TargetFunctionType; // Extracted function type from target type
8596
8597 bool Complain;
8598 //DeclAccessPair& ResultFunctionAccessPair;
8599 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008600
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008601 bool TargetTypeIsNonStaticMemberFunction;
8602 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008603
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008604 OverloadExpr::FindResult OvlExprInfo;
8605 OverloadExpr *OvlExpr;
8606 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008607 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008608
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008609public:
8610 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8611 const QualType& TargetType, bool Complain)
8612 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8613 Complain(Complain), Context(S.getASTContext()),
8614 TargetTypeIsNonStaticMemberFunction(
8615 !!TargetType->getAs<MemberPointerType>()),
8616 FoundNonTemplateFunction(false),
8617 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8618 OvlExpr(OvlExprInfo.Expression)
8619 {
8620 ExtractUnqualifiedFunctionTypeFromTargetType();
8621
8622 if (!TargetFunctionType->isFunctionType()) {
8623 if (OvlExpr->hasExplicitTemplateArgs()) {
8624 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008625 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008626 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008627
8628 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8629 if (!Method->isStatic()) {
8630 // If the target type is a non-function type and the function
8631 // found is a non-static member function, pretend as if that was
8632 // the target, it's the only possible type to end up with.
8633 TargetTypeIsNonStaticMemberFunction = true;
8634
8635 // And skip adding the function if its not in the proper form.
8636 // We'll diagnose this due to an empty set of functions.
8637 if (!OvlExprInfo.HasFormOfMemberPointer)
8638 return;
8639 }
8640 }
8641
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008642 Matches.push_back(std::make_pair(dap,Fn));
8643 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008644 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008645 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008646 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008647
8648 if (OvlExpr->hasExplicitTemplateArgs())
8649 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008650
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008651 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8652 // C++ [over.over]p4:
8653 // If more than one function is selected, [...]
8654 if (Matches.size() > 1) {
8655 if (FoundNonTemplateFunction)
8656 EliminateAllTemplateMatches();
8657 else
8658 EliminateAllExceptMostSpecializedTemplate();
8659 }
8660 }
8661 }
8662
8663private:
8664 bool isTargetTypeAFunction() const {
8665 return TargetFunctionType->isFunctionType();
8666 }
8667
8668 // [ToType] [Return]
8669
8670 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8671 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8672 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8673 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8674 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8675 }
8676
8677 // return true if any matching specializations were found
8678 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8679 const DeclAccessPair& CurAccessFunPair) {
8680 if (CXXMethodDecl *Method
8681 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8682 // Skip non-static function templates when converting to pointer, and
8683 // static when converting to member pointer.
8684 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8685 return false;
8686 }
8687 else if (TargetTypeIsNonStaticMemberFunction)
8688 return false;
8689
8690 // C++ [over.over]p2:
8691 // If the name is a function template, template argument deduction is
8692 // done (14.8.2.2), and if the argument deduction succeeds, the
8693 // resulting template argument list is used to generate a single
8694 // function template specialization, which is added to the set of
8695 // overloaded functions considered.
8696 FunctionDecl *Specialization = 0;
8697 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8698 if (Sema::TemplateDeductionResult Result
8699 = S.DeduceTemplateArguments(FunctionTemplate,
8700 &OvlExplicitTemplateArgs,
8701 TargetFunctionType, Specialization,
8702 Info)) {
8703 // FIXME: make a note of the failed deduction for diagnostics.
8704 (void)Result;
8705 return false;
8706 }
8707
8708 // Template argument deduction ensures that we have an exact match.
8709 // This function template specicalization works.
8710 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8711 assert(TargetFunctionType
8712 == Context.getCanonicalType(Specialization->getType()));
8713 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8714 return true;
8715 }
8716
8717 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8718 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008720 // Skip non-static functions when converting to pointer, and static
8721 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008722 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8723 return false;
8724 }
8725 else if (TargetTypeIsNonStaticMemberFunction)
8726 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008727
Chandler Carruthbd647292009-12-29 06:17:27 +00008728 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008729 if (S.getLangOptions().CUDA)
8730 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8731 if (S.CheckCUDATarget(Caller, FunDecl))
8732 return false;
8733
Douglas Gregor43c79c22009-12-09 00:47:37 +00008734 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008735 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8736 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008737 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8738 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008739 Matches.push_back(std::make_pair(CurAccessFunPair,
8740 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008741 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008742 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008743 }
Mike Stump1eb44332009-09-09 15:08:12 +00008744 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008745
8746 return false;
8747 }
8748
8749 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8750 bool Ret = false;
8751
8752 // If the overload expression doesn't have the form of a pointer to
8753 // member, don't try to convert it to a pointer-to-member type.
8754 if (IsInvalidFormOfPointerToMemberFunction())
8755 return false;
8756
8757 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8758 E = OvlExpr->decls_end();
8759 I != E; ++I) {
8760 // Look through any using declarations to find the underlying function.
8761 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8762
8763 // C++ [over.over]p3:
8764 // Non-member functions and static member functions match
8765 // targets of type "pointer-to-function" or "reference-to-function."
8766 // Nonstatic member functions match targets of
8767 // type "pointer-to-member-function."
8768 // Note that according to DR 247, the containing class does not matter.
8769 if (FunctionTemplateDecl *FunctionTemplate
8770 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8771 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8772 Ret = true;
8773 }
8774 // If we have explicit template arguments supplied, skip non-templates.
8775 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8776 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8777 Ret = true;
8778 }
8779 assert(Ret || Matches.empty());
8780 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008781 }
8782
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008783 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008784 // [...] and any given function template specialization F1 is
8785 // eliminated if the set contains a second function template
8786 // specialization whose function template is more specialized
8787 // than the function template of F1 according to the partial
8788 // ordering rules of 14.5.5.2.
8789
8790 // The algorithm specified above is quadratic. We instead use a
8791 // two-pass algorithm (similar to the one used to identify the
8792 // best viable function in an overload set) that identifies the
8793 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008794
8795 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8796 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8797 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008798
John McCallc373d482010-01-27 01:50:18 +00008799 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008800 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8801 TPOC_Other, 0, SourceExpr->getLocStart(),
8802 S.PDiag(),
8803 S.PDiag(diag::err_addr_ovl_ambiguous)
8804 << Matches[0].second->getDeclName(),
8805 S.PDiag(diag::note_ovl_candidate)
8806 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00008807 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008808
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008809 if (Result != MatchesCopy.end()) {
8810 // Make it the first and only element
8811 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8812 Matches[0].second = cast<FunctionDecl>(*Result);
8813 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008814 }
8815 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008816
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008817 void EliminateAllTemplateMatches() {
8818 // [...] any function template specializations in the set are
8819 // eliminated if the set also contains a non-template function, [...]
8820 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8821 if (Matches[I].second->getPrimaryTemplate() == 0)
8822 ++I;
8823 else {
8824 Matches[I] = Matches[--N];
8825 Matches.set_size(N);
8826 }
8827 }
8828 }
8829
8830public:
8831 void ComplainNoMatchesFound() const {
8832 assert(Matches.empty());
8833 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8834 << OvlExpr->getName() << TargetFunctionType
8835 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008836 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008837 }
8838
8839 bool IsInvalidFormOfPointerToMemberFunction() const {
8840 return TargetTypeIsNonStaticMemberFunction &&
8841 !OvlExprInfo.HasFormOfMemberPointer;
8842 }
8843
8844 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8845 // TODO: Should we condition this on whether any functions might
8846 // have matched, or is it more appropriate to do that in callers?
8847 // TODO: a fixit wouldn't hurt.
8848 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8849 << TargetType << OvlExpr->getSourceRange();
8850 }
8851
8852 void ComplainOfInvalidConversion() const {
8853 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8854 << OvlExpr->getName() << TargetType;
8855 }
8856
8857 void ComplainMultipleMatchesFound() const {
8858 assert(Matches.size() > 1);
8859 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8860 << OvlExpr->getName()
8861 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008862 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008863 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008864
8865 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8866
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008867 int getNumMatches() const { return Matches.size(); }
8868
8869 FunctionDecl* getMatchingFunctionDecl() const {
8870 if (Matches.size() != 1) return 0;
8871 return Matches[0].second;
8872 }
8873
8874 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8875 if (Matches.size() != 1) return 0;
8876 return &Matches[0].first;
8877 }
8878};
8879
8880/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8881/// an overloaded function (C++ [over.over]), where @p From is an
8882/// expression with overloaded function type and @p ToType is the type
8883/// we're trying to resolve to. For example:
8884///
8885/// @code
8886/// int f(double);
8887/// int f(int);
8888///
8889/// int (*pfd)(double) = f; // selects f(double)
8890/// @endcode
8891///
8892/// This routine returns the resulting FunctionDecl if it could be
8893/// resolved, and NULL otherwise. When @p Complain is true, this
8894/// routine will emit diagnostics if there is an error.
8895FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008896Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8897 QualType TargetType,
8898 bool Complain,
8899 DeclAccessPair &FoundResult,
8900 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008901 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008902
8903 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8904 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008905 int NumMatches = Resolver.getNumMatches();
8906 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008907 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008908 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8909 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8910 else
8911 Resolver.ComplainNoMatchesFound();
8912 }
8913 else if (NumMatches > 1 && Complain)
8914 Resolver.ComplainMultipleMatchesFound();
8915 else if (NumMatches == 1) {
8916 Fn = Resolver.getMatchingFunctionDecl();
8917 assert(Fn);
8918 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00008919 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00008920 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008921 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00008922 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008923
8924 if (pHadMultipleCandidates)
8925 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008926 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00008927}
8928
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008929/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00008930/// resolve that overloaded function expression down to a single function.
8931///
8932/// This routine can only resolve template-ids that refer to a single function
8933/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008934/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00008935/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00008936FunctionDecl *
8937Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8938 bool Complain,
8939 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008940 // C++ [over.over]p1:
8941 // [...] [Note: any redundant set of parentheses surrounding the
8942 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00008943 // C++ [over.over]p1:
8944 // [...] The overloaded function name can be preceded by the &
8945 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008946
Douglas Gregor4b52e252009-12-21 23:17:24 +00008947 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00008948 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00008949 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00008950
8951 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00008952 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008953
Douglas Gregor4b52e252009-12-21 23:17:24 +00008954 // Look through all of the overloaded functions, searching for one
8955 // whose type matches exactly.
8956 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00008957 for (UnresolvedSetIterator I = ovl->decls_begin(),
8958 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008959 // C++0x [temp.arg.explicit]p3:
8960 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008961 // where deduction is not done, if a template argument list is
8962 // specified and it, along with any default template arguments,
8963 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00008964 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00008965 FunctionTemplateDecl *FunctionTemplate
8966 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008967
Douglas Gregor4b52e252009-12-21 23:17:24 +00008968 // C++ [over.over]p2:
8969 // If the name is a function template, template argument deduction is
8970 // done (14.8.2.2), and if the argument deduction succeeds, the
8971 // resulting template argument list is used to generate a single
8972 // function template specialization, which is added to the set of
8973 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00008974 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00008975 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00008976 if (TemplateDeductionResult Result
8977 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8978 Specialization, Info)) {
8979 // FIXME: make a note of the failed deduction for diagnostics.
8980 (void)Result;
8981 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008982 }
8983
John McCall864c0412011-04-26 20:42:42 +00008984 assert(Specialization && "no specialization and no error?");
8985
Douglas Gregor4b52e252009-12-21 23:17:24 +00008986 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008987 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008988 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00008989 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8990 << ovl->getName();
8991 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008992 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00008993 return 0;
John McCall864c0412011-04-26 20:42:42 +00008994 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008995
John McCall864c0412011-04-26 20:42:42 +00008996 Matched = Specialization;
8997 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00008998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008999
Douglas Gregor4b52e252009-12-21 23:17:24 +00009000 return Matched;
9001}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009002
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009003
9004
9005
John McCall6dbba4f2011-10-11 23:14:30 +00009006// Resolve and fix an overloaded expression that can be resolved
9007// because it identifies a single function template specialization.
9008//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009009// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009010//
9011// Return true if it was logically possible to so resolve the
9012// expression, regardless of whether or not it succeeded. Always
9013// returns true if 'complain' is set.
9014bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9015 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9016 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009017 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009018 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009019 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009020
John McCall6dbba4f2011-10-11 23:14:30 +00009021 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009022
John McCall864c0412011-04-26 20:42:42 +00009023 DeclAccessPair found;
9024 ExprResult SingleFunctionExpression;
9025 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9026 ovl.Expression, /*complain*/ false, &found)) {
John McCall6dbba4f2011-10-11 23:14:30 +00009027 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
9028 SrcExpr = ExprError();
9029 return true;
9030 }
John McCall864c0412011-04-26 20:42:42 +00009031
9032 // It is only correct to resolve to an instance method if we're
9033 // resolving a form that's permitted to be a pointer to member.
9034 // Otherwise we'll end up making a bound member expression, which
9035 // is illegal in all the contexts we resolve like this.
9036 if (!ovl.HasFormOfMemberPointer &&
9037 isa<CXXMethodDecl>(fn) &&
9038 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009039 if (!complain) return false;
9040
9041 Diag(ovl.Expression->getExprLoc(),
9042 diag::err_bound_member_function)
9043 << 0 << ovl.Expression->getSourceRange();
9044
9045 // TODO: I believe we only end up here if there's a mix of
9046 // static and non-static candidates (otherwise the expression
9047 // would have 'bound member' type, not 'overload' type).
9048 // Ideally we would note which candidate was chosen and why
9049 // the static candidates were rejected.
9050 SrcExpr = ExprError();
9051 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009052 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009053
John McCall864c0412011-04-26 20:42:42 +00009054 // Fix the expresion to refer to 'fn'.
9055 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009056 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009057
9058 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009059 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009060 SingleFunctionExpression =
9061 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009062 if (SingleFunctionExpression.isInvalid()) {
9063 SrcExpr = ExprError();
9064 return true;
9065 }
9066 }
John McCall864c0412011-04-26 20:42:42 +00009067 }
9068
9069 if (!SingleFunctionExpression.isUsable()) {
9070 if (complain) {
9071 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9072 << ovl.Expression->getName()
9073 << DestTypeForComplaining
9074 << OpRangeForComplaining
9075 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009076 NoteAllOverloadCandidates(SrcExpr.get());
9077
9078 SrcExpr = ExprError();
9079 return true;
9080 }
9081
9082 return false;
John McCall864c0412011-04-26 20:42:42 +00009083 }
9084
John McCall6dbba4f2011-10-11 23:14:30 +00009085 SrcExpr = SingleFunctionExpression;
9086 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009087}
9088
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009089/// \brief Add a single candidate to the overload set.
9090static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009091 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009092 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009093 Expr **Args, unsigned NumArgs,
9094 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009095 bool PartialOverloading,
9096 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009097 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009098 if (isa<UsingShadowDecl>(Callee))
9099 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9100
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009101 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009102 if (ExplicitTemplateArgs) {
9103 assert(!KnownValid && "Explicit template arguments?");
9104 return;
9105 }
John McCall9aa472c2010-03-19 07:35:19 +00009106 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00009107 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009108 return;
John McCallba135432009-11-21 08:51:07 +00009109 }
9110
9111 if (FunctionTemplateDecl *FuncTemplate
9112 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009113 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9114 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00009115 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009116 return;
9117 }
9118
Richard Smith2ced0442011-06-26 22:19:54 +00009119 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009120}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009121
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009122/// \brief Add the overload candidates named by callee and/or found by argument
9123/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009124void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009125 Expr **Args, unsigned NumArgs,
9126 OverloadCandidateSet &CandidateSet,
9127 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009128
9129#ifndef NDEBUG
9130 // Verify that ArgumentDependentLookup is consistent with the rules
9131 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009132 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009133 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9134 // and let Y be the lookup set produced by argument dependent
9135 // lookup (defined as follows). If X contains
9136 //
9137 // -- a declaration of a class member, or
9138 //
9139 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009140 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009141 //
9142 // -- a declaration that is neither a function or a function
9143 // template
9144 //
9145 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009146
John McCall3b4294e2009-12-16 12:17:52 +00009147 if (ULE->requiresADL()) {
9148 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9149 E = ULE->decls_end(); I != E; ++I) {
9150 assert(!(*I)->getDeclContext()->isRecord());
9151 assert(isa<UsingShadowDecl>(*I) ||
9152 !(*I)->getDeclContext()->isFunctionOrMethod());
9153 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009154 }
9155 }
9156#endif
9157
John McCall3b4294e2009-12-16 12:17:52 +00009158 // It would be nice to avoid this copy.
9159 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009160 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009161 if (ULE->hasExplicitTemplateArgs()) {
9162 ULE->copyTemplateArgumentsInto(TABuffer);
9163 ExplicitTemplateArgs = &TABuffer;
9164 }
9165
9166 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9167 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00009168 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009169 Args, NumArgs, CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009170 PartialOverloading, /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009171
John McCall3b4294e2009-12-16 12:17:52 +00009172 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009173 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9174 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009175 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009176 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00009177 PartialOverloading,
9178 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009179}
John McCall578b69b2009-12-16 08:11:27 +00009180
Richard Smithf50e88a2011-06-05 22:42:48 +00009181/// Attempt to recover from an ill-formed use of a non-dependent name in a
9182/// template, where the non-dependent name was declared after the template
9183/// was defined. This is common in code written for a compilers which do not
9184/// correctly implement two-stage name lookup.
9185///
9186/// Returns true if a viable candidate was found and a diagnostic was issued.
9187static bool
9188DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9189 const CXXScopeSpec &SS, LookupResult &R,
9190 TemplateArgumentListInfo *ExplicitTemplateArgs,
9191 Expr **Args, unsigned NumArgs) {
9192 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9193 return false;
9194
9195 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9196 SemaRef.LookupQualifiedName(R, DC);
9197
9198 if (!R.empty()) {
9199 R.suppressDiagnostics();
9200
9201 if (isa<CXXRecordDecl>(DC)) {
9202 // Don't diagnose names we find in classes; we get much better
9203 // diagnostics for these from DiagnoseEmptyLookup.
9204 R.clear();
9205 return false;
9206 }
9207
9208 OverloadCandidateSet Candidates(FnLoc);
9209 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9210 AddOverloadedCallCandidate(SemaRef, I.getPair(),
9211 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith2ced0442011-06-26 22:19:54 +00009212 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009213
9214 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009215 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009216 // No viable functions. Don't bother the user with notes for functions
9217 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009218 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009219 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009220 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009221
9222 // Find the namespaces where ADL would have looked, and suggest
9223 // declaring the function there instead.
9224 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9225 Sema::AssociatedClassSet AssociatedClasses;
9226 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
9227 AssociatedNamespaces,
9228 AssociatedClasses);
9229 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009230 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009231 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009232 for (Sema::AssociatedNamespaceSet::iterator
9233 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009234 end = AssociatedNamespaces.end(); it != end; ++it) {
9235 if (!Std->Encloses(*it))
9236 SuggestedNamespaces.insert(*it);
9237 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009238 } else {
9239 // Lacking the 'std::' namespace, use all of the associated namespaces.
9240 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009241 }
9242
9243 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9244 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009245 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009246 SemaRef.Diag(Best->Function->getLocation(),
9247 diag::note_not_found_by_two_phase_lookup)
9248 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009249 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009250 SemaRef.Diag(Best->Function->getLocation(),
9251 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009252 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009253 } else {
9254 // FIXME: It would be useful to list the associated namespaces here,
9255 // but the diagnostics infrastructure doesn't provide a way to produce
9256 // a localized representation of a list of items.
9257 SemaRef.Diag(Best->Function->getLocation(),
9258 diag::note_not_found_by_two_phase_lookup)
9259 << R.getLookupName() << 2;
9260 }
9261
9262 // Try to recover by calling this function.
9263 return true;
9264 }
9265
9266 R.clear();
9267 }
9268
9269 return false;
9270}
9271
9272/// Attempt to recover from ill-formed use of a non-dependent operator in a
9273/// template, where the non-dependent operator was declared after the template
9274/// was defined.
9275///
9276/// Returns true if a viable candidate was found and a diagnostic was issued.
9277static bool
9278DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9279 SourceLocation OpLoc,
9280 Expr **Args, unsigned NumArgs) {
9281 DeclarationName OpName =
9282 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9283 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9284 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9285 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
9286}
9287
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009288namespace {
9289// Callback to limit the allowed keywords and to only accept typo corrections
9290// that are keywords or whose decls refer to functions (or template functions)
9291// that accept the given number of arguments.
9292class RecoveryCallCCC : public CorrectionCandidateCallback {
9293 public:
9294 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9295 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9296 WantTypeSpecifiers = SemaRef.getLangOptions().CPlusPlus;
9297 WantRemainingKeywords = false;
9298 }
9299
9300 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9301 if (!candidate.getCorrectionDecl())
9302 return candidate.isKeyword();
9303
9304 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9305 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9306 FunctionDecl *FD = 0;
9307 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9308 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9309 FD = FTD->getTemplatedDecl();
9310 if (!HasExplicitTemplateArgs && !FD) {
9311 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9312 // If the Decl is neither a function nor a template function,
9313 // determine if it is a pointer or reference to a function. If so,
9314 // check against the number of arguments expected for the pointee.
9315 QualType ValType = cast<ValueDecl>(ND)->getType();
9316 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9317 ValType = ValType->getPointeeType();
9318 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9319 if (FPT->getNumArgs() == NumArgs)
9320 return true;
9321 }
9322 }
9323 if (FD && FD->getNumParams() >= NumArgs &&
9324 FD->getMinRequiredArguments() <= NumArgs)
9325 return true;
9326 }
9327 return false;
9328 }
9329
9330 private:
9331 unsigned NumArgs;
9332 bool HasExplicitTemplateArgs;
9333};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009334
9335// Callback that effectively disabled typo correction
9336class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9337 public:
9338 NoTypoCorrectionCCC() {
9339 WantTypeSpecifiers = false;
9340 WantExpressionKeywords = false;
9341 WantCXXNamedCasts = false;
9342 WantRemainingKeywords = false;
9343 }
9344
9345 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9346 return false;
9347 }
9348};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009349}
9350
John McCall578b69b2009-12-16 08:11:27 +00009351/// Attempts to recover from a call where no functions were found.
9352///
9353/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009354static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009355BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009356 UnresolvedLookupExpr *ULE,
9357 SourceLocation LParenLoc,
9358 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00009359 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009360 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009361
9362 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009363 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009364 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009365
John McCall3b4294e2009-12-16 12:17:52 +00009366 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009367 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009368 if (ULE->hasExplicitTemplateArgs()) {
9369 ULE->copyTemplateArgumentsInto(TABuffer);
9370 ExplicitTemplateArgs = &TABuffer;
9371 }
9372
John McCall578b69b2009-12-16 08:11:27 +00009373 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9374 Sema::LookupOrdinaryName);
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009375 RecoveryCallCCC Validator(SemaRef, NumArgs, ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009376 NoTypoCorrectionCCC RejectAll;
9377 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9378 (CorrectionCandidateCallback*)&Validator :
9379 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009380 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9381 ExplicitTemplateArgs, Args, NumArgs) &&
9382 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009383 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00009384 ExplicitTemplateArgs, Args, NumArgs)))
John McCallf312b1e2010-08-26 23:41:50 +00009385 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009386
John McCall3b4294e2009-12-16 12:17:52 +00009387 assert(!R.empty() && "lookup results empty despite recovery");
9388
9389 // Build an implicit member call if appropriate. Just drop the
9390 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009391 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009392 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009393 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9394 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009395 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009396 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009397 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009398 else
9399 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9400
9401 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009402 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009403
9404 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009405 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009406 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009407 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00009408 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009409}
Douglas Gregord7a95972010-06-08 17:35:15 +00009410
Douglas Gregorf6b89692008-11-26 05:54:23 +00009411/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009412/// (which eventually refers to the declaration Func) and the call
9413/// arguments Args/NumArgs, attempt to resolve the function call down
9414/// to a specific function. If overload resolution succeeds, returns
9415/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009416/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009417/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009418ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009419Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009420 SourceLocation LParenLoc,
9421 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009422 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009423 Expr *ExecConfig,
9424 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009425#ifndef NDEBUG
9426 if (ULE->requiresADL()) {
9427 // To do ADL, we must have found an unqualified name.
9428 assert(!ULE->getQualifier() && "qualified name with ADL");
9429
9430 // We don't perform ADL for implicit declarations of builtins.
9431 // Verify that this was correctly set up.
9432 FunctionDecl *F;
9433 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9434 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9435 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009436 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009437
John McCall3b4294e2009-12-16 12:17:52 +00009438 // We don't perform ADL in C.
9439 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009440 } else
9441 assert(!ULE->isStdAssociatedNamespace() &&
9442 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009443#endif
9444
John McCall5acb0c92011-10-17 18:40:02 +00009445 UnbridgedCastsSet UnbridgedCasts;
9446 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9447 return ExprError();
9448
John McCall5769d612010-02-08 23:07:23 +00009449 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009450
John McCall3b4294e2009-12-16 12:17:52 +00009451 // Add the functions denoted by the callee to the set of candidate
9452 // functions, including those from argument-dependent lookup.
9453 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009454
9455 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009456 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9457 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009458 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009459 // In Microsoft mode, if we are inside a template class member function then
9460 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009461 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009462 // classes.
Francois Pichetef04ecf2011-11-11 00:12:11 +00009463 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009464 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009465 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9466 Context.DependentTy, VK_RValue,
9467 RParenLoc);
9468 CE->setTypeDependent(true);
9469 return Owned(CE);
9470 }
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009471 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009472 RParenLoc, /*EmptyLookup=*/true,
9473 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009474 }
John McCall578b69b2009-12-16 08:11:27 +00009475
John McCall5acb0c92011-10-17 18:40:02 +00009476 UnbridgedCasts.restore();
9477
Douglas Gregorf6b89692008-11-26 05:54:23 +00009478 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009479 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009480 case OR_Success: {
9481 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009482 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009483 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009484 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009485 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009486 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9487 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009488 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009489
Richard Smithf50e88a2011-06-05 22:42:48 +00009490 case OR_No_Viable_Function: {
9491 // Try to recover by looking for viable functions which the user might
9492 // have meant to call.
9493 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9494 Args, NumArgs, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009495 /*EmptyLookup=*/false,
9496 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009497 if (!Recovery.isInvalid())
9498 return Recovery;
9499
Chris Lattner4330d652009-02-17 07:29:20 +00009500 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009501 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009502 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009503 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00009504 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009505 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009506
9507 case OR_Ambiguous:
9508 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009509 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009510 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00009511 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009512
9513 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009514 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009515 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
9516 << Best->Function->isDeleted()
9517 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009518 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009519 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009520 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009521
9522 // We emitted an error for the unvailable/deleted function call but keep
9523 // the call in the AST.
9524 FunctionDecl *FDecl = Best->Function;
9525 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9526 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9527 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009528 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009529 }
9530
Douglas Gregorff331c12010-07-25 18:17:45 +00009531 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009532 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009533}
9534
John McCall6e266892010-01-26 03:27:55 +00009535static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009536 return Functions.size() > 1 ||
9537 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9538}
9539
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009540/// \brief Create a unary operation that may resolve to an overloaded
9541/// operator.
9542///
9543/// \param OpLoc The location of the operator itself (e.g., '*').
9544///
9545/// \param OpcIn The UnaryOperator::Opcode that describes this
9546/// operator.
9547///
9548/// \param Functions The set of non-member functions that will be
9549/// considered by overload resolution. The caller needs to build this
9550/// set based on the context using, e.g.,
9551/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9552/// set should not contain any member functions; those will be added
9553/// by CreateOverloadedUnaryOp().
9554///
9555/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009556ExprResult
John McCall6e266892010-01-26 03:27:55 +00009557Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9558 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009559 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009560 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009561
9562 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9563 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9564 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009565 // TODO: provide better source location info.
9566 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009567
John McCall5acb0c92011-10-17 18:40:02 +00009568 if (checkPlaceholderForOverload(*this, Input))
9569 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009570
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009571 Expr *Args[2] = { Input, 0 };
9572 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009573
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009574 // For post-increment and post-decrement, add the implicit '0' as
9575 // the second argument, so that we know this is a post-increment or
9576 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009577 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009578 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009579 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9580 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009581 NumArgs = 2;
9582 }
9583
9584 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009585 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009586 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009587 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009588 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009589 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009590 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009591
John McCallc373d482010-01-27 01:50:18 +00009592 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009593 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009594 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009595 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009596 /*ADL*/ true, IsOverloaded(Fns),
9597 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009598 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009599 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009600 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009601 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009602 OpLoc));
9603 }
9604
9605 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009606 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009607
9608 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009609 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009610
9611 // Add operator candidates that are member functions.
9612 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9613
John McCall6e266892010-01-26 03:27:55 +00009614 // Add candidates from ADL.
9615 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00009616 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00009617 /*ExplicitTemplateArgs*/ 0,
9618 CandidateSet);
9619
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009620 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009621 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009622
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009623 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9624
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009625 // Perform overload resolution.
9626 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009627 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009628 case OR_Success: {
9629 // We found a built-in operator or an overloaded operator.
9630 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009631
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009632 if (FnDecl) {
9633 // We matched an overloaded operator. Build a call to that
9634 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009635
Eli Friedman5f2987c2012-02-02 03:46:19 +00009636 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009637
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009638 // Convert the arguments.
9639 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009640 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009641
John Wiegley429bb272011-04-08 18:41:53 +00009642 ExprResult InputRes =
9643 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9644 Best->FoundDecl, Method);
9645 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009646 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009647 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009648 } else {
9649 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009650 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009651 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009652 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009653 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009654 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009655 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009656 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009657 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009658 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009659 }
9660
John McCallb697e082010-05-06 18:15:07 +00009661 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9662
John McCallf89e55a2010-11-18 06:31:45 +00009663 // Determine the result type.
9664 QualType ResultTy = FnDecl->getResultType();
9665 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9666 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009667
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009668 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009669 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009670 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009671 if (FnExpr.isInvalid())
9672 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009673
Eli Friedman4c3b8962009-11-18 03:58:17 +00009674 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009675 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009676 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009677 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009678
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009679 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009680 FnDecl))
9681 return ExprError();
9682
John McCall9ae2f072010-08-23 23:25:46 +00009683 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009684 } else {
9685 // We matched a built-in operator. Convert the arguments, then
9686 // break out so that we will build the appropriate built-in
9687 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009688 ExprResult InputRes =
9689 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9690 Best->Conversions[0], AA_Passing);
9691 if (InputRes.isInvalid())
9692 return ExprError();
9693 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009694 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009695 }
John Wiegley429bb272011-04-08 18:41:53 +00009696 }
9697
9698 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009699 // This is an erroneous use of an operator which can be overloaded by
9700 // a non-member function. Check for non-member operators which were
9701 // defined too late to be candidates.
9702 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9703 // FIXME: Recover by calling the found function.
9704 return ExprError();
9705
John Wiegley429bb272011-04-08 18:41:53 +00009706 // No viable function; fall through to handling this as a
9707 // built-in operator, which will produce an error message for us.
9708 break;
9709
9710 case OR_Ambiguous:
9711 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9712 << UnaryOperator::getOpcodeStr(Opc)
9713 << Input->getType()
9714 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009715 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley429bb272011-04-08 18:41:53 +00009716 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9717 return ExprError();
9718
9719 case OR_Deleted:
9720 Diag(OpLoc, diag::err_ovl_deleted_oper)
9721 << Best->Function->isDeleted()
9722 << UnaryOperator::getOpcodeStr(Opc)
9723 << getDeletedOrUnavailableSuffix(Best->Function)
9724 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009725 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9726 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009727 return ExprError();
9728 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009729
9730 // Either we found no viable overloaded operator or we matched a
9731 // built-in operator. In either case, fall through to trying to
9732 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00009733 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009734}
9735
Douglas Gregor063daf62009-03-13 18:40:31 +00009736/// \brief Create a binary operation that may resolve to an overloaded
9737/// operator.
9738///
9739/// \param OpLoc The location of the operator itself (e.g., '+').
9740///
9741/// \param OpcIn The BinaryOperator::Opcode that describes this
9742/// operator.
9743///
9744/// \param Functions The set of non-member functions that will be
9745/// considered by overload resolution. The caller needs to build this
9746/// set based on the context using, e.g.,
9747/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9748/// set should not contain any member functions; those will be added
9749/// by CreateOverloadedBinOp().
9750///
9751/// \param LHS Left-hand argument.
9752/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009753ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00009754Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00009755 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009756 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009757 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009758 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009759 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009760
9761 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9762 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9763 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9764
9765 // If either side is type-dependent, create an appropriate dependent
9766 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009767 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009768 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009769 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009770 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009771 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009772 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009773 Context.DependentTy,
9774 VK_RValue, OK_Ordinary,
9775 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009776
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009777 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9778 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009779 VK_LValue,
9780 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009781 Context.DependentTy,
9782 Context.DependentTy,
9783 OpLoc));
9784 }
John McCall6e266892010-01-26 03:27:55 +00009785
9786 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009787 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009788 // TODO: provide better source location info in DNLoc component.
9789 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009790 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009791 = UnresolvedLookupExpr::Create(Context, NamingClass,
9792 NestedNameSpecifierLoc(), OpNameInfo,
9793 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009794 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009795 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009796 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009797 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009798 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009799 OpLoc));
9800 }
9801
John McCall5acb0c92011-10-17 18:40:02 +00009802 // Always do placeholder-like conversions on the RHS.
9803 if (checkPlaceholderForOverload(*this, Args[1]))
9804 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009805
John McCall3c3b7f92011-10-25 17:37:35 +00009806 // Do placeholder-like conversion on the LHS; note that we should
9807 // not get here with a PseudoObject LHS.
9808 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009809 if (checkPlaceholderForOverload(*this, Args[0]))
9810 return ExprError();
9811
Sebastian Redl275c2b42009-11-18 23:10:33 +00009812 // If this is the assignment operator, we only perform overload resolution
9813 // if the left-hand side is a class or enumeration type. This is actually
9814 // a hack. The standard requires that we do overload resolution between the
9815 // various built-in candidates, but as DR507 points out, this can lead to
9816 // problems. So we do it this way, which pretty much follows what GCC does.
9817 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009818 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009819 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009820
John McCall0e800c92010-12-04 08:14:53 +00009821 // If this is the .* operator, which is not overloadable, just
9822 // create a built-in binary operator.
9823 if (Opc == BO_PtrMemD)
9824 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9825
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009826 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009827 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009828
9829 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009830 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009831
9832 // Add operator candidates that are member functions.
9833 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9834
John McCall6e266892010-01-26 03:27:55 +00009835 // Add candidates from ADL.
9836 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9837 Args, 2,
9838 /*ExplicitTemplateArgs*/ 0,
9839 CandidateSet);
9840
Douglas Gregor063daf62009-03-13 18:40:31 +00009841 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009842 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009843
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009844 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9845
Douglas Gregor063daf62009-03-13 18:40:31 +00009846 // Perform overload resolution.
9847 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009848 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00009849 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00009850 // We found a built-in operator or an overloaded operator.
9851 FunctionDecl *FnDecl = Best->Function;
9852
9853 if (FnDecl) {
9854 // We matched an overloaded operator. Build a call to that
9855 // operator.
9856
Eli Friedman5f2987c2012-02-02 03:46:19 +00009857 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009858
Douglas Gregor063daf62009-03-13 18:40:31 +00009859 // Convert the arguments.
9860 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00009861 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00009862 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009863
Chandler Carruth6df868e2010-12-12 08:17:55 +00009864 ExprResult Arg1 =
9865 PerformCopyInitialization(
9866 InitializedEntity::InitializeParameter(Context,
9867 FnDecl->getParamDecl(0)),
9868 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009869 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009870 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009871
John Wiegley429bb272011-04-08 18:41:53 +00009872 ExprResult Arg0 =
9873 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9874 Best->FoundDecl, Method);
9875 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009876 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009877 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009878 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009879 } else {
9880 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00009881 ExprResult Arg0 = PerformCopyInitialization(
9882 InitializedEntity::InitializeParameter(Context,
9883 FnDecl->getParamDecl(0)),
9884 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009885 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009886 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009887
Chandler Carruth6df868e2010-12-12 08:17:55 +00009888 ExprResult Arg1 =
9889 PerformCopyInitialization(
9890 InitializedEntity::InitializeParameter(Context,
9891 FnDecl->getParamDecl(1)),
9892 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009893 if (Arg1.isInvalid())
9894 return ExprError();
9895 Args[0] = LHS = Arg0.takeAs<Expr>();
9896 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009897 }
9898
John McCallb697e082010-05-06 18:15:07 +00009899 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9900
John McCallf89e55a2010-11-18 06:31:45 +00009901 // Determine the result type.
9902 QualType ResultTy = FnDecl->getResultType();
9903 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9904 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00009905
9906 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009907 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9908 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009909 if (FnExpr.isInvalid())
9910 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00009911
John McCall9ae2f072010-08-23 23:25:46 +00009912 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009913 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009914 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009915
9916 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009917 FnDecl))
9918 return ExprError();
9919
John McCall9ae2f072010-08-23 23:25:46 +00009920 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00009921 } else {
9922 // We matched a built-in operator. Convert the arguments, then
9923 // break out so that we will build the appropriate built-in
9924 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009925 ExprResult ArgsRes0 =
9926 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9927 Best->Conversions[0], AA_Passing);
9928 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009929 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009930 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009931
John Wiegley429bb272011-04-08 18:41:53 +00009932 ExprResult ArgsRes1 =
9933 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9934 Best->Conversions[1], AA_Passing);
9935 if (ArgsRes1.isInvalid())
9936 return ExprError();
9937 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009938 break;
9939 }
9940 }
9941
Douglas Gregor33074752009-09-30 21:46:01 +00009942 case OR_No_Viable_Function: {
9943 // C++ [over.match.oper]p9:
9944 // If the operator is the operator , [...] and there are no
9945 // viable functions, then the operator is assumed to be the
9946 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00009947 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00009948 break;
9949
Chandler Carruth6df868e2010-12-12 08:17:55 +00009950 // For class as left operand for assignment or compound assigment
9951 // operator do not fall through to handling in built-in, but report that
9952 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00009953 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009954 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00009955 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00009956 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9957 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009958 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00009959 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +00009960 // This is an erroneous use of an operator which can be overloaded by
9961 // a non-member function. Check for non-member operators which were
9962 // defined too late to be candidates.
9963 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9964 // FIXME: Recover by calling the found function.
9965 return ExprError();
9966
Douglas Gregor33074752009-09-30 21:46:01 +00009967 // No viable function; try to create a built-in operation, which will
9968 // produce an error. Then, show the non-viable candidates.
9969 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00009970 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009971 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00009972 "C++ binary operator overloading is missing candidates!");
9973 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00009974 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9975 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00009976 return move(Result);
9977 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009978
9979 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009980 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00009981 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00009982 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009983 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009984 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9985 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009986 return ExprError();
9987
9988 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +00009989 if (isImplicitlyDeleted(Best->Function)) {
9990 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
9991 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
9992 << getSpecialMember(Method)
9993 << BinaryOperator::getOpcodeStr(Opc)
9994 << getDeletedOrUnavailableSuffix(Best->Function);
9995
9996 if (Method->getParent()->isLambda()) {
9997 Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
9998 return ExprError();
9999 }
10000 } else {
10001 Diag(OpLoc, diag::err_ovl_deleted_oper)
10002 << Best->Function->isDeleted()
10003 << BinaryOperator::getOpcodeStr(Opc)
10004 << getDeletedOrUnavailableSuffix(Best->Function)
10005 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10006 }
Eli Friedman1795d372011-08-26 19:46:22 +000010007 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10008 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010009 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010010 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010011
Douglas Gregor33074752009-09-30 21:46:01 +000010012 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010013 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010014}
10015
John McCall60d7b3a2010-08-24 06:29:42 +000010016ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010017Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10018 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010019 Expr *Base, Expr *Idx) {
10020 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010021 DeclarationName OpName =
10022 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10023
10024 // If either side is type-dependent, create an appropriate dependent
10025 // expression.
10026 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10027
John McCallc373d482010-01-27 01:50:18 +000010028 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010029 // CHECKME: no 'operator' keyword?
10030 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10031 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010032 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010033 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010034 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010035 /*ADL*/ true, /*Overloaded*/ false,
10036 UnresolvedSetIterator(),
10037 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010038 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010039
Sebastian Redlf322ed62009-10-29 20:17:01 +000010040 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10041 Args, 2,
10042 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010043 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010044 RLoc));
10045 }
10046
John McCall5acb0c92011-10-17 18:40:02 +000010047 // Handle placeholders on both operands.
10048 if (checkPlaceholderForOverload(*this, Args[0]))
10049 return ExprError();
10050 if (checkPlaceholderForOverload(*this, Args[1]))
10051 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010052
Sebastian Redlf322ed62009-10-29 20:17:01 +000010053 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010054 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010055
10056 // Subscript can only be overloaded as a member function.
10057
10058 // Add operator candidates that are member functions.
10059 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10060
10061 // Add builtin operator candidates.
10062 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10063
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010064 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10065
Sebastian Redlf322ed62009-10-29 20:17:01 +000010066 // Perform overload resolution.
10067 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010068 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010069 case OR_Success: {
10070 // We found a built-in operator or an overloaded operator.
10071 FunctionDecl *FnDecl = Best->Function;
10072
10073 if (FnDecl) {
10074 // We matched an overloaded operator. Build a call to that
10075 // operator.
10076
Eli Friedman5f2987c2012-02-02 03:46:19 +000010077 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010078
John McCall9aa472c2010-03-19 07:35:19 +000010079 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010080 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010081
Sebastian Redlf322ed62009-10-29 20:17:01 +000010082 // Convert the arguments.
10083 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010084 ExprResult Arg0 =
10085 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10086 Best->FoundDecl, Method);
10087 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010088 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010089 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010090
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010091 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010092 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010093 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010094 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010095 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010096 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010097 Owned(Args[1]));
10098 if (InputInit.isInvalid())
10099 return ExprError();
10100
10101 Args[1] = InputInit.takeAs<Expr>();
10102
Sebastian Redlf322ed62009-10-29 20:17:01 +000010103 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010104 QualType ResultTy = FnDecl->getResultType();
10105 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10106 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010107
10108 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010109 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10110 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010111 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10112 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010113 OpLocInfo.getLoc(),
10114 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010115 if (FnExpr.isInvalid())
10116 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010117
John McCall9ae2f072010-08-23 23:25:46 +000010118 CXXOperatorCallExpr *TheCall =
10119 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010120 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010121 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010122
John McCall9ae2f072010-08-23 23:25:46 +000010123 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010124 FnDecl))
10125 return ExprError();
10126
John McCall9ae2f072010-08-23 23:25:46 +000010127 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010128 } else {
10129 // We matched a built-in operator. Convert the arguments, then
10130 // break out so that we will build the appropriate built-in
10131 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010132 ExprResult ArgsRes0 =
10133 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10134 Best->Conversions[0], AA_Passing);
10135 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010136 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010137 Args[0] = ArgsRes0.take();
10138
10139 ExprResult ArgsRes1 =
10140 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10141 Best->Conversions[1], AA_Passing);
10142 if (ArgsRes1.isInvalid())
10143 return ExprError();
10144 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010145
10146 break;
10147 }
10148 }
10149
10150 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010151 if (CandidateSet.empty())
10152 Diag(LLoc, diag::err_ovl_no_oper)
10153 << Args[0]->getType() << /*subscript*/ 0
10154 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10155 else
10156 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10157 << Args[0]->getType()
10158 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010159 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10160 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010161 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010162 }
10163
10164 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010165 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010166 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010167 << Args[0]->getType() << Args[1]->getType()
10168 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010169 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
10170 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010171 return ExprError();
10172
10173 case OR_Deleted:
10174 Diag(LLoc, diag::err_ovl_deleted_oper)
10175 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010176 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010177 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010178 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10179 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010180 return ExprError();
10181 }
10182
10183 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010184 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010185}
10186
Douglas Gregor88a35142008-12-22 05:46:06 +000010187/// BuildCallToMemberFunction - Build a call to a member
10188/// function. MemExpr is the expression that refers to the member
10189/// function (and includes the object parameter), Args/NumArgs are the
10190/// arguments to the function call (not including the object
10191/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010192/// expression refers to a non-static member function or an overloaded
10193/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010194ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010195Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10196 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010197 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010198 assert(MemExprE->getType() == Context.BoundMemberTy ||
10199 MemExprE->getType() == Context.OverloadTy);
10200
Douglas Gregor88a35142008-12-22 05:46:06 +000010201 // Dig out the member expression. This holds both the object
10202 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010203 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010204
John McCall864c0412011-04-26 20:42:42 +000010205 // Determine whether this is a call to a pointer-to-member function.
10206 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10207 assert(op->getType() == Context.BoundMemberTy);
10208 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10209
10210 QualType fnType =
10211 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10212
10213 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10214 QualType resultType = proto->getCallResultType(Context);
10215 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10216
10217 // Check that the object type isn't more qualified than the
10218 // member function we're calling.
10219 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10220
10221 QualType objectType = op->getLHS()->getType();
10222 if (op->getOpcode() == BO_PtrMemI)
10223 objectType = objectType->castAs<PointerType>()->getPointeeType();
10224 Qualifiers objectQuals = objectType.getQualifiers();
10225
10226 Qualifiers difference = objectQuals - funcQuals;
10227 difference.removeObjCGCAttr();
10228 difference.removeAddressSpace();
10229 if (difference) {
10230 std::string qualsString = difference.getAsString();
10231 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10232 << fnType.getUnqualifiedType()
10233 << qualsString
10234 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10235 }
10236
10237 CXXMemberCallExpr *call
10238 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10239 resultType, valueKind, RParenLoc);
10240
10241 if (CheckCallReturnType(proto->getResultType(),
10242 op->getRHS()->getSourceRange().getBegin(),
10243 call, 0))
10244 return ExprError();
10245
10246 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10247 return ExprError();
10248
10249 return MaybeBindToTemporary(call);
10250 }
10251
John McCall5acb0c92011-10-17 18:40:02 +000010252 UnbridgedCastsSet UnbridgedCasts;
10253 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10254 return ExprError();
10255
John McCall129e2df2009-11-30 22:42:35 +000010256 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010257 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010258 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010259 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010260 if (isa<MemberExpr>(NakedMemExpr)) {
10261 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010262 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010263 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010264 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010265 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010266 } else {
10267 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010268 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010269
John McCall701c89e2009-12-03 04:06:58 +000010270 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010271 Expr::Classification ObjectClassification
10272 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10273 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010274
Douglas Gregor88a35142008-12-22 05:46:06 +000010275 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010276 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010277
John McCallaa81e162009-12-01 22:10:20 +000010278 // FIXME: avoid copy.
10279 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10280 if (UnresExpr->hasExplicitTemplateArgs()) {
10281 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10282 TemplateArgs = &TemplateArgsBuffer;
10283 }
10284
John McCall129e2df2009-11-30 22:42:35 +000010285 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10286 E = UnresExpr->decls_end(); I != E; ++I) {
10287
John McCall701c89e2009-12-03 04:06:58 +000010288 NamedDecl *Func = *I;
10289 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10290 if (isa<UsingShadowDecl>(Func))
10291 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10292
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010293
Francois Pichetdbee3412011-01-18 05:04:39 +000010294 // Microsoft supports direct constructor calls.
Francois Pichet62ec1f22011-09-17 17:15:52 +000010295 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichetdbee3412011-01-18 05:04:39 +000010296 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
10297 CandidateSet);
10298 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010299 // If explicit template arguments were provided, we can't call a
10300 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010301 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010302 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010303
John McCall9aa472c2010-03-19 07:35:19 +000010304 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010305 ObjectClassification,
10306 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010307 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010308 } else {
John McCall129e2df2009-11-30 22:42:35 +000010309 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010310 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010311 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010312 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010313 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010314 }
Douglas Gregordec06662009-08-21 18:42:58 +000010315 }
Mike Stump1eb44332009-09-09 15:08:12 +000010316
John McCall129e2df2009-11-30 22:42:35 +000010317 DeclarationName DeclName = UnresExpr->getMemberName();
10318
John McCall5acb0c92011-10-17 18:40:02 +000010319 UnbridgedCasts.restore();
10320
Douglas Gregor88a35142008-12-22 05:46:06 +000010321 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010322 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010323 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010324 case OR_Success:
10325 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010326 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010327 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010328 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010329 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010330 break;
10331
10332 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010333 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010334 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010335 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010336 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +000010337 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010338 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010339
10340 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010341 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010342 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010343 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +000010344 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010345 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010346
10347 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010348 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010349 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010350 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010351 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010352 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010353 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010354 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010355 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010356 }
10357
John McCall6bb80172010-03-30 21:47:33 +000010358 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010359
John McCallaa81e162009-12-01 22:10:20 +000010360 // If overload resolution picked a static member, build a
10361 // non-member call based on that function.
10362 if (Method->isStatic()) {
10363 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10364 Args, NumArgs, RParenLoc);
10365 }
10366
John McCall129e2df2009-11-30 22:42:35 +000010367 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010368 }
10369
John McCallf89e55a2010-11-18 06:31:45 +000010370 QualType ResultType = Method->getResultType();
10371 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10372 ResultType = ResultType.getNonLValueExprType(Context);
10373
Douglas Gregor88a35142008-12-22 05:46:06 +000010374 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010375 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010376 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010377 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010378
Anders Carlssoneed3e692009-10-10 00:06:20 +000010379 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010380 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010381 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010382 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010383
Douglas Gregor88a35142008-12-22 05:46:06 +000010384 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010385 // We only need to do this if there was actually an overload; otherwise
10386 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010387 if (!Method->isStatic()) {
10388 ExprResult ObjectArg =
10389 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10390 FoundDecl, Method);
10391 if (ObjectArg.isInvalid())
10392 return ExprError();
10393 MemExpr->setBase(ObjectArg.take());
10394 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010395
10396 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010397 const FunctionProtoType *Proto =
10398 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010399 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010400 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010401 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010402
Eli Friedmane61eb042012-02-18 04:48:30 +000010403 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10404
John McCall9ae2f072010-08-23 23:25:46 +000010405 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +000010406 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010407
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010408 if ((isa<CXXConstructorDecl>(CurContext) ||
10409 isa<CXXDestructorDecl>(CurContext)) &&
10410 TheCall->getMethodDecl()->isPure()) {
10411 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10412
Chandler Carruthae198062011-06-27 08:31:58 +000010413 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010414 Diag(MemExpr->getLocStart(),
10415 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10416 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10417 << MD->getParent()->getDeclName();
10418
10419 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010420 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010421 }
John McCall9ae2f072010-08-23 23:25:46 +000010422 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010423}
10424
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010425/// BuildCallToObjectOfClassType - Build a call to an object of class
10426/// type (C++ [over.call.object]), which can end up invoking an
10427/// overloaded function call operator (@c operator()) or performing a
10428/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010429ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010430Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010431 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010432 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010433 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010434 if (checkPlaceholderForOverload(*this, Obj))
10435 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010436 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010437
10438 UnbridgedCastsSet UnbridgedCasts;
10439 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10440 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010441
John Wiegley429bb272011-04-08 18:41:53 +000010442 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10443 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010444
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010445 // C++ [over.call.object]p1:
10446 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010447 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010448 // candidate functions includes at least the function call
10449 // operators of T. The function call operators of T are obtained by
10450 // ordinary lookup of the name operator() in the context of
10451 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010452 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010453 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010454
John Wiegley429bb272011-04-08 18:41:53 +000010455 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +000010456 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010457 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010458 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010459
John McCalla24dc2e2009-11-17 02:14:36 +000010460 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10461 LookupQualifiedName(R, Record->getDecl());
10462 R.suppressDiagnostics();
10463
Douglas Gregor593564b2009-11-15 07:48:03 +000010464 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010465 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010466 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10467 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010468 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010469 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010470
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010471 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010472 // In addition, for each (non-explicit in C++0x) conversion function
10473 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010474 //
10475 // operator conversion-type-id () cv-qualifier;
10476 //
10477 // where cv-qualifier is the same cv-qualification as, or a
10478 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010479 // denotes the type "pointer to function of (P1,...,Pn) returning
10480 // R", or the type "reference to pointer to function of
10481 // (P1,...,Pn) returning R", or the type "reference to function
10482 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010483 // is also considered as a candidate function. Similarly,
10484 // surrogate call functions are added to the set of candidate
10485 // functions for each conversion function declared in an
10486 // accessible base class provided the function is not hidden
10487 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010488 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010489 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010490 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010491 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010492 NamedDecl *D = *I;
10493 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10494 if (isa<UsingShadowDecl>(D))
10495 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010496
Douglas Gregor4a27d702009-10-21 06:18:39 +000010497 // Skip over templated conversion functions; they aren't
10498 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010499 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010500 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010501
John McCall701c89e2009-12-03 04:06:58 +000010502 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010503 if (!Conv->isExplicit()) {
10504 // Strip the reference type (if any) and then the pointer type (if
10505 // any) to get down to what might be a function type.
10506 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10507 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10508 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010509
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010510 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10511 {
10512 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10513 Object.get(), Args, NumArgs, CandidateSet);
10514 }
10515 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010516 }
Mike Stump1eb44332009-09-09 15:08:12 +000010517
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010518 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10519
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010520 // Perform overload resolution.
10521 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010522 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010523 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010524 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010525 // Overload resolution succeeded; we'll build the appropriate call
10526 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010527 break;
10528
10529 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010530 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +000010531 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
10532 << Object.get()->getType() << /*call*/ 1
10533 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010534 else
John Wiegley429bb272011-04-08 18:41:53 +000010535 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +000010536 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010537 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010538 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010539 break;
10540
10541 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +000010542 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010543 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010544 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010545 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010546 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010547
10548 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +000010549 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010550 diag::err_ovl_deleted_object_call)
10551 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010552 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010553 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010554 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010555 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010556 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010557 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010558
Douglas Gregorff331c12010-07-25 18:17:45 +000010559 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010560 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010561
John McCall5acb0c92011-10-17 18:40:02 +000010562 UnbridgedCasts.restore();
10563
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010564 if (Best->Function == 0) {
10565 // Since there is no function declaration, this is one of the
10566 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010567 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010568 = cast<CXXConversionDecl>(
10569 Best->Conversions[0].UserDefined.ConversionFunction);
10570
John Wiegley429bb272011-04-08 18:41:53 +000010571 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010572 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010573
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010574 // We selected one of the surrogate functions that converts the
10575 // object parameter to a function pointer. Perform the conversion
10576 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010577
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010578 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010579 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010580 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10581 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010582 if (Call.isInvalid())
10583 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010584 // Record usage of conversion in an implicit cast.
10585 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10586 CK_UserDefinedConversion,
10587 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010588
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010589 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010590 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010591 }
10592
Eli Friedman5f2987c2012-02-02 03:46:19 +000010593 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010594 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010595 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010596
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010597 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10598 // that calls this method, using Object for the implicit object
10599 // parameter and passing along the remaining arguments.
10600 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010601 const FunctionProtoType *Proto =
10602 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010603
10604 unsigned NumArgsInProto = Proto->getNumArgs();
10605 unsigned NumArgsToCheck = NumArgs;
10606
10607 // Build the full argument list for the method call (the
10608 // implicit object parameter is placed at the beginning of the
10609 // list).
10610 Expr **MethodArgs;
10611 if (NumArgs < NumArgsInProto) {
10612 NumArgsToCheck = NumArgsInProto;
10613 MethodArgs = new Expr*[NumArgsInProto + 1];
10614 } else {
10615 MethodArgs = new Expr*[NumArgs + 1];
10616 }
John Wiegley429bb272011-04-08 18:41:53 +000010617 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010618 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10619 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010620
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010621 DeclarationNameInfo OpLocInfo(
10622 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10623 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010624 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010625 HadMultipleCandidates,
10626 OpLocInfo.getLoc(),
10627 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010628 if (NewFn.isInvalid())
10629 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010630
10631 // Once we've built TheCall, all of the expressions are properly
10632 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010633 QualType ResultTy = Method->getResultType();
10634 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10635 ResultTy = ResultTy.getNonLValueExprType(Context);
10636
John McCall9ae2f072010-08-23 23:25:46 +000010637 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010638 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010639 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010640 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010641 delete [] MethodArgs;
10642
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010643 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010644 Method))
10645 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010646
Douglas Gregor518fda12009-01-13 05:10:00 +000010647 // We may have default arguments. If so, we need to allocate more
10648 // slots in the call for them.
10649 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010650 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010651 else if (NumArgs > NumArgsInProto)
10652 NumArgsToCheck = NumArgsInProto;
10653
Chris Lattner312531a2009-04-12 08:11:20 +000010654 bool IsError = false;
10655
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010656 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010657 ExprResult ObjRes =
10658 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10659 Best->FoundDecl, Method);
10660 if (ObjRes.isInvalid())
10661 IsError = true;
10662 else
10663 Object = move(ObjRes);
10664 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010665
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010666 // Check the argument types.
10667 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010668 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010669 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010670 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010671
Douglas Gregor518fda12009-01-13 05:10:00 +000010672 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010673
John McCall60d7b3a2010-08-24 06:29:42 +000010674 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010675 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010676 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010677 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010678 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010679
Anders Carlsson3faa4862010-01-29 18:43:53 +000010680 IsError |= InputInit.isInvalid();
10681 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010682 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010683 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010684 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10685 if (DefArg.isInvalid()) {
10686 IsError = true;
10687 break;
10688 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010689
Douglas Gregord47c47d2009-11-09 19:27:57 +000010690 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010691 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010692
10693 TheCall->setArg(i + 1, Arg);
10694 }
10695
10696 // If this is a variadic call, handle args passed through "...".
10697 if (Proto->isVariadic()) {
10698 // Promote the arguments (C99 6.5.2.2p7).
10699 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000010700 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10701 IsError |= Arg.isInvalid();
10702 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010703 }
10704 }
10705
Chris Lattner312531a2009-04-12 08:11:20 +000010706 if (IsError) return true;
10707
Eli Friedmane61eb042012-02-18 04:48:30 +000010708 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10709
John McCall9ae2f072010-08-23 23:25:46 +000010710 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000010711 return true;
10712
John McCall182f7092010-08-24 06:09:16 +000010713 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010714}
10715
Douglas Gregor8ba10742008-11-20 16:27:02 +000010716/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000010717/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000010718/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000010719ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010720Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000010721 assert(Base->getType()->isRecordType() &&
10722 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000010723
John McCall5acb0c92011-10-17 18:40:02 +000010724 if (checkPlaceholderForOverload(*this, Base))
10725 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010726
John McCall5769d612010-02-08 23:07:23 +000010727 SourceLocation Loc = Base->getExprLoc();
10728
Douglas Gregor8ba10742008-11-20 16:27:02 +000010729 // C++ [over.ref]p1:
10730 //
10731 // [...] An expression x->m is interpreted as (x.operator->())->m
10732 // for a class object x of type T if T::operator->() exists and if
10733 // the operator is selected as the best match function by the
10734 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000010735 DeclarationName OpName =
10736 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000010737 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000010738 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010739
John McCall5769d612010-02-08 23:07:23 +000010740 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +000010741 PDiag(diag::err_typecheck_incomplete_tag)
10742 << Base->getSourceRange()))
10743 return ExprError();
10744
John McCalla24dc2e2009-11-17 02:14:36 +000010745 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10746 LookupQualifiedName(R, BaseRecord->getDecl());
10747 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000010748
10749 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000010750 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010751 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10752 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000010753 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000010754
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010755 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10756
Douglas Gregor8ba10742008-11-20 16:27:02 +000010757 // Perform overload resolution.
10758 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010759 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000010760 case OR_Success:
10761 // Overload resolution succeeded; we'll build the call below.
10762 break;
10763
10764 case OR_No_Viable_Function:
10765 if (CandidateSet.empty())
10766 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010767 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010768 else
10769 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010770 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010771 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010772 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010773
10774 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010775 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10776 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010777 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010778 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010779
10780 case OR_Deleted:
10781 Diag(OpLoc, diag::err_ovl_deleted_oper)
10782 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010783 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010784 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010785 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010786 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010787 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010788 }
10789
Eli Friedman5f2987c2012-02-02 03:46:19 +000010790 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010791 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010792 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010793
Douglas Gregor8ba10742008-11-20 16:27:02 +000010794 // Convert the object parameter.
10795 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010796 ExprResult BaseResult =
10797 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10798 Best->FoundDecl, Method);
10799 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010800 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010801 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010802
Douglas Gregor8ba10742008-11-20 16:27:02 +000010803 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010804 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010805 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010806 if (FnExpr.isInvalid())
10807 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010808
John McCallf89e55a2010-11-18 06:31:45 +000010809 QualType ResultTy = Method->getResultType();
10810 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10811 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010812 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010813 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010814 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010815
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010816 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010817 Method))
10818 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010819
10820 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010821}
10822
Douglas Gregor904eed32008-11-10 20:40:00 +000010823/// FixOverloadedFunctionReference - E is an expression that refers to
10824/// a C++ overloaded function (possibly with some parentheses and
10825/// perhaps a '&' around it). We have resolved the overloaded function
10826/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000010827/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000010828Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000010829 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000010830 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010831 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10832 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010833 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010834 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010835
Douglas Gregor699ee522009-11-20 19:42:02 +000010836 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010837 }
10838
Douglas Gregor699ee522009-11-20 19:42:02 +000010839 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010840 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10841 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010842 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000010843 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000010844 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000010845 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000010846 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010847 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010848
10849 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000010850 ICE->getCastKind(),
10851 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000010852 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010853 }
10854
Douglas Gregor699ee522009-11-20 19:42:02 +000010855 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000010856 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000010857 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000010858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10859 if (Method->isStatic()) {
10860 // Do nothing: static member functions aren't any different
10861 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000010862 } else {
John McCallf7a1a742009-11-24 19:00:30 +000010863 // Fix the sub expression, which really has to be an
10864 // UnresolvedLookupExpr holding an overloaded member function
10865 // or template.
John McCall6bb80172010-03-30 21:47:33 +000010866 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10867 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000010868 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010869 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000010870
John McCallba135432009-11-21 08:51:07 +000010871 assert(isa<DeclRefExpr>(SubExpr)
10872 && "fixed to something other than a decl ref");
10873 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10874 && "fixed to a member ref with no nested name qualifier");
10875
10876 // We have taken the address of a pointer to member
10877 // function. Perform the computation here so that we get the
10878 // appropriate pointer to member type.
10879 QualType ClassType
10880 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10881 QualType MemPtrType
10882 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10883
John McCallf89e55a2010-11-18 06:31:45 +000010884 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10885 VK_RValue, OK_Ordinary,
10886 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000010887 }
10888 }
John McCall6bb80172010-03-30 21:47:33 +000010889 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10890 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010891 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010892 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010893
John McCall2de56d12010-08-25 11:45:40 +000010894 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000010895 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000010896 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000010897 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010898 }
John McCallba135432009-11-21 08:51:07 +000010899
10900 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000010901 // FIXME: avoid copy.
10902 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000010903 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000010904 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10905 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000010906 }
10907
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010908 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10909 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010910 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010911 Fn,
10912 ULE->getNameLoc(),
10913 Fn->getType(),
10914 VK_LValue,
10915 Found.getDecl(),
10916 TemplateArgs);
10917 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10918 return DRE;
John McCallba135432009-11-21 08:51:07 +000010919 }
10920
John McCall129e2df2009-11-30 22:42:35 +000010921 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000010922 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000010923 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10924 if (MemExpr->hasExplicitTemplateArgs()) {
10925 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10926 TemplateArgs = &TemplateArgsBuffer;
10927 }
John McCalld5532b62009-11-23 01:53:49 +000010928
John McCallaa81e162009-12-01 22:10:20 +000010929 Expr *Base;
10930
John McCallf89e55a2010-11-18 06:31:45 +000010931 // If we're filling in a static method where we used to have an
10932 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000010933 if (MemExpr->isImplicitAccess()) {
10934 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010935 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10936 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010937 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010938 Fn,
10939 MemExpr->getMemberLoc(),
10940 Fn->getType(),
10941 VK_LValue,
10942 Found.getDecl(),
10943 TemplateArgs);
10944 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10945 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000010946 } else {
10947 SourceLocation Loc = MemExpr->getMemberLoc();
10948 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000010949 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000010950 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000010951 Base = new (Context) CXXThisExpr(Loc,
10952 MemExpr->getBaseType(),
10953 /*isImplicit=*/true);
10954 }
John McCallaa81e162009-12-01 22:10:20 +000010955 } else
John McCall3fa5cae2010-10-26 07:05:15 +000010956 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000010957
John McCallf5307512011-04-27 00:36:17 +000010958 ExprValueKind valueKind;
10959 QualType type;
10960 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10961 valueKind = VK_LValue;
10962 type = Fn->getType();
10963 } else {
10964 valueKind = VK_RValue;
10965 type = Context.BoundMemberTy;
10966 }
10967
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010968 MemberExpr *ME = MemberExpr::Create(Context, Base,
10969 MemExpr->isArrow(),
10970 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010971 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010972 Fn,
10973 Found,
10974 MemExpr->getMemberNameInfo(),
10975 TemplateArgs,
10976 type, valueKind, OK_Ordinary);
10977 ME->setHadMultipleCandidates(true);
10978 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000010979 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010980
John McCall3fa5cae2010-10-26 07:05:15 +000010981 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000010982}
10983
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010984ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000010985 DeclAccessPair Found,
10986 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000010987 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000010988}
10989
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000010990} // end namespace clang