blob: 6fa78a9a462994ad2db32bbb059e103fff91201a [file] [log] [blame]
Douglas Gregor5251f1b2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
39static Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
45}
46
John McCall5c32be02010-08-24 20:38:10 +000047static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000049 StandardConversionSequence &SCS,
50 bool CStyle);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000051
52static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
53 QualType &ToType,
54 bool InOverloadResolution,
55 StandardConversionSequence &SCS,
56 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000057static OverloadingResult
58IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
59 UserDefinedConversionSequence& User,
60 OverloadCandidateSet& Conversions,
61 bool AllowExplicit);
62
63
64static ImplicitConversionSequence::CompareKind
65CompareStandardConversionSequences(Sema &S,
66 const StandardConversionSequence& SCS1,
67 const StandardConversionSequence& SCS2);
68
69static ImplicitConversionSequence::CompareKind
70CompareQualificationConversions(Sema &S,
71 const StandardConversionSequence& SCS1,
72 const StandardConversionSequence& SCS2);
73
74static ImplicitConversionSequence::CompareKind
75CompareDerivedToBaseConversions(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79
80
Douglas Gregor5251f1b2008-10-21 16:13:35 +000081/// GetConversionCategory - Retrieve the implicit conversion
82/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000083ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084GetConversionCategory(ImplicitConversionKind Kind) {
85 static const ImplicitConversionCategory
86 Category[(int)ICK_Num_Conversion_Kinds] = {
87 ICC_Identity,
88 ICC_Lvalue_Transformation,
89 ICC_Lvalue_Transformation,
90 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000091 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 ICC_Qualification_Adjustment,
93 ICC_Promotion,
94 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000095 ICC_Promotion,
96 ICC_Conversion,
97 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 ICC_Conversion,
99 ICC_Conversion,
100 ICC_Conversion,
101 ICC_Conversion,
102 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000103 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000104 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000105 ICC_Conversion,
106 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107 ICC_Conversion
108 };
109 return Category[(int)Kind];
110}
111
112/// GetConversionRank - Retrieve the implicit conversion rank
113/// corresponding to the given implicit conversion kind.
114ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
115 static const ImplicitConversionRank
116 Rank[(int)ICK_Num_Conversion_Kinds] = {
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000122 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000123 ICR_Promotion,
124 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000125 ICR_Promotion,
126 ICR_Conversion,
127 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000133 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000134 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000135 ICR_Conversion,
136 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000137 ICR_Complex_Real_Conversion,
138 ICR_Conversion,
139 ICR_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000140 };
141 return Rank[(int)Kind];
142}
143
144/// GetImplicitConversionName - Return the name of this kind of
145/// implicit conversion.
146const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000147 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000148 "No conversion",
149 "Lvalue-to-rvalue",
150 "Array-to-pointer",
151 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000152 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 "Qualification",
154 "Integral promotion",
155 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000156 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000157 "Integral conversion",
158 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000159 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "Floating-integral conversion",
161 "Pointer conversion",
162 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000163 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000164 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000165 "Derived-to-base conversion",
166 "Vector conversion",
167 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000168 "Complex-real conversion",
169 "Block Pointer conversion",
170 "Transparent Union Conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000171 };
172 return Name[Kind];
173}
174
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000175/// StandardConversionSequence - Set the standard conversion
176/// sequence to the identity conversion.
177void StandardConversionSequence::setAsIdentityConversion() {
178 First = ICK_Identity;
179 Second = ICK_Identity;
180 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000181 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000182 ReferenceBinding = false;
183 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000184 IsLvalueReference = true;
185 BindsToFunctionLvalue = false;
186 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000187 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000188 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000189}
190
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000191/// getRank - Retrieve the rank of this standard conversion sequence
192/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
193/// implicit conversions.
194ImplicitConversionRank StandardConversionSequence::getRank() const {
195 ImplicitConversionRank Rank = ICR_Exact_Match;
196 if (GetConversionRank(First) > Rank)
197 Rank = GetConversionRank(First);
198 if (GetConversionRank(Second) > Rank)
199 Rank = GetConversionRank(Second);
200 if (GetConversionRank(Third) > Rank)
201 Rank = GetConversionRank(Third);
202 return Rank;
203}
204
205/// isPointerConversionToBool - Determines whether this conversion is
206/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000207/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000208/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000209bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000210 // Note that FromType has not necessarily been transformed by the
211 // array-to-pointer or function-to-pointer implicit conversions, so
212 // check for their presence as well as checking whether FromType is
213 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000214 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000215 (getFromType()->isPointerType() ||
216 getFromType()->isObjCObjectPointerType() ||
217 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000218 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
220 return true;
221
222 return false;
223}
224
Douglas Gregor5c407d92008-10-23 00:40:37 +0000225/// isPointerConversionToVoidPointer - Determines whether this
226/// conversion is a conversion of a pointer to a void pointer. This is
227/// used as part of the ranking of standard conversion sequences (C++
228/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000229bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000230StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000231isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000232 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000233 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234
235 // Note that FromType has not necessarily been transformed by the
236 // array-to-pointer implicit conversion, so check for its presence
237 // and redo the conversion to get a pointer.
238 if (First == ICK_Array_To_Pointer)
239 FromType = Context.getArrayDecayedType(FromType);
240
John McCall75851b12010-10-26 06:40:27 +0000241 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000242 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243 return ToPtrType->getPointeeType()->isVoidType();
244
245 return false;
246}
247
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000248/// DebugPrint - Print this standard conversion sequence to standard
249/// error. Useful for debugging overloading issues.
250void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000251 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000252 bool PrintedSomething = false;
253 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000254 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 PrintedSomething = true;
256 }
257
258 if (Second != ICK_Identity) {
259 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000262 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000263
264 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000265 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000266 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000268 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000269 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000270 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000271 PrintedSomething = true;
272 }
273
274 if (Third != ICK_Identity) {
275 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000276 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000277 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 PrintedSomething = true;
280 }
281
282 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000283 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 }
285}
286
287/// DebugPrint - Print this user-defined conversion sequence to standard
288/// error. Useful for debugging overloading issues.
289void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000290 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000291 if (Before.First || Before.Second || Before.Third) {
292 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000295 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000297 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000298 After.DebugPrint();
299 }
300}
301
302/// DebugPrint - Print this implicit conversion sequence to standard
303/// error. Useful for debugging overloading issues.
304void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000305 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 switch (ConversionKind) {
307 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000308 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000309 Standard.DebugPrint();
310 break;
311 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000312 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000313 UserDefined.DebugPrint();
314 break;
315 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000316 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000317 break;
John McCall0d1da222010-01-12 00:44:57 +0000318 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000319 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000320 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000321 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000322 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000323 break;
324 }
325
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000326 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000327}
328
John McCall0d1da222010-01-12 00:44:57 +0000329void AmbiguousConversionSequence::construct() {
330 new (&conversions()) ConversionSet();
331}
332
333void AmbiguousConversionSequence::destruct() {
334 conversions().~ConversionSet();
335}
336
337void
338AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
339 FromTypePtr = O.FromTypePtr;
340 ToTypePtr = O.ToTypePtr;
341 new (&conversions()) ConversionSet(O.conversions());
342}
343
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000344namespace {
345 // Structure used by OverloadCandidate::DeductionFailureInfo to store
346 // template parameter and template argument information.
347 struct DFIParamWithArguments {
348 TemplateParameter Param;
349 TemplateArgument FirstArg;
350 TemplateArgument SecondArg;
351 };
352}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000353
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354/// \brief Convert from Sema's representation of template deduction information
355/// to the form used in overload-candidate information.
356OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000357static MakeDeductionFailureInfo(ASTContext &Context,
358 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000359 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360 OverloadCandidate::DeductionFailureInfo Result;
361 Result.Result = static_cast<unsigned>(TDK);
362 Result.Data = 0;
363 switch (TDK) {
364 case Sema::TDK_Success:
365 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000366 case Sema::TDK_TooManyArguments:
367 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000368 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000371 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000372 Result.Data = Info.Param.getOpaqueValue();
373 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000374
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000375 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000376 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000377 // FIXME: Should allocate from normal heap so that we can free this later.
378 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000379 Saved->Param = Info.Param;
380 Saved->FirstArg = Info.FirstArg;
381 Saved->SecondArg = Info.SecondArg;
382 Result.Data = Saved;
383 break;
384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000387 Result.Data = Info.take();
388 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000390 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000391 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 return Result;
396}
John McCall0d1da222010-01-12 00:44:57 +0000397
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000398void OverloadCandidate::DeductionFailureInfo::Destroy() {
399 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
400 case Sema::TDK_Success:
401 case Sema::TDK_InstantiationDepth:
402 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000403 case Sema::TDK_TooManyArguments:
404 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000405 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000409 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000410 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411 Data = 0;
412 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000413
414 case Sema::TDK_SubstitutionFailure:
415 // FIXME: Destroy the template arugment list?
416 Data = 0;
417 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418
Douglas Gregor461761d2010-05-08 18:20:53 +0000419 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000421 case Sema::TDK_FailedOverloadResolution:
422 break;
423 }
424}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000425
426TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000427OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
428 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
429 case Sema::TDK_Success:
430 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000431 case Sema::TDK_TooManyArguments:
432 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000433 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000434 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000437 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000438 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000439
440 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000441 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000442 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000443
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000444 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000445 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000446 case Sema::TDK_FailedOverloadResolution:
447 break;
448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000449
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000450 return TemplateParameter();
451}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000452
Douglas Gregord09efd42010-05-08 20:07:26 +0000453TemplateArgumentList *
454OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
455 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
456 case Sema::TDK_Success:
457 case Sema::TDK_InstantiationDepth:
458 case Sema::TDK_TooManyArguments:
459 case Sema::TDK_TooFewArguments:
460 case Sema::TDK_Incomplete:
461 case Sema::TDK_InvalidExplicitArguments:
462 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000463 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000464 return 0;
465
466 case Sema::TDK_SubstitutionFailure:
467 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Douglas Gregord09efd42010-05-08 20:07:26 +0000469 // Unhandled
470 case Sema::TDK_NonDeducedMismatch:
471 case Sema::TDK_FailedOverloadResolution:
472 break;
473 }
474
475 return 0;
476}
477
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000478const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
479 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
480 case Sema::TDK_Success:
481 case Sema::TDK_InstantiationDepth:
482 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000483 case Sema::TDK_TooManyArguments:
484 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000485 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000486 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000487 return 0;
488
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000490 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000492
Douglas Gregor461761d2010-05-08 18:20:53 +0000493 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000495 case Sema::TDK_FailedOverloadResolution:
496 break;
497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000498
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000499 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000501
502const TemplateArgument *
503OverloadCandidate::DeductionFailureInfo::getSecondArg() {
504 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
505 case Sema::TDK_Success:
506 case Sema::TDK_InstantiationDepth:
507 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000508 case Sema::TDK_TooManyArguments:
509 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000510 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000511 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000512 return 0;
513
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000515 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000516 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
517
Douglas Gregor461761d2010-05-08 18:20:53 +0000518 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000519 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000520 case Sema::TDK_FailedOverloadResolution:
521 break;
522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000524 return 0;
525}
526
527void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000528 inherited::clear();
529 Functions.clear();
530}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000533// overload of the declarations in Old. This routine returns false if
534// New and Old cannot be overloaded, e.g., if New has the same
535// signature as some function in Old (C++ 1.3.10) or if the Old
536// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000537// it does return false, MatchedDecl will point to the decl that New
538// cannot be overloaded with. This decl may be a UsingShadowDecl on
539// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540//
541// Example: Given the following input:
542//
543// void f(int, float); // #1
544// void f(int, int); // #2
545// int f(int, int); // #3
546//
547// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000548// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000549//
John McCall3d988d92009-12-02 08:47:38 +0000550// When we process #2, Old contains only the FunctionDecl for #1. By
551// comparing the parameter types, we see that #1 and #2 are overloaded
552// (since they have different signatures), so this routine returns
553// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000554//
John McCall3d988d92009-12-02 08:47:38 +0000555// When we process #3, Old is an overload set containing #1 and #2. We
556// compare the signatures of #3 to #1 (they're overloaded, so we do
557// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
558// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000559// signature), IsOverload returns false and MatchedDecl will be set to
560// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000561//
562// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
563// into a class by a using declaration. The rules for whether to hide
564// shadow declarations ignore some properties which otherwise figure
565// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000566Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000567Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
568 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000569 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000570 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000571 NamedDecl *OldD = *I;
572
573 bool OldIsUsingDecl = false;
574 if (isa<UsingShadowDecl>(OldD)) {
575 OldIsUsingDecl = true;
576
577 // We can always introduce two using declarations into the same
578 // context, even if they have identical signatures.
579 if (NewIsUsingDecl) continue;
580
581 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
582 }
583
584 // If either declaration was introduced by a using declaration,
585 // we'll need to use slightly different rules for matching.
586 // Essentially, these rules are the normal rules, except that
587 // function templates hide function templates with different
588 // return types or template parameter lists.
589 bool UseMemberUsingDeclRules =
590 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
591
John McCall3d988d92009-12-02 08:47:38 +0000592 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000593 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
594 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
595 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
596 continue;
597 }
598
John McCalldaa3d6b2009-12-09 03:35:25 +0000599 Match = *I;
600 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000601 }
John McCall3d988d92009-12-02 08:47:38 +0000602 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000603 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
604 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
605 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
606 continue;
607 }
608
John McCalldaa3d6b2009-12-09 03:35:25 +0000609 Match = *I;
610 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000611 }
John McCalla8987a2942010-11-10 03:01:53 +0000612 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000613 // We can overload with these, which can show up when doing
614 // redeclaration checks for UsingDecls.
615 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000616 } else if (isa<TagDecl>(OldD)) {
617 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000618 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
619 // Optimistically assume that an unresolved using decl will
620 // overload; if it doesn't, we'll have to diagnose during
621 // template instantiation.
622 } else {
John McCall1f82f242009-11-18 22:49:29 +0000623 // (C++ 13p1):
624 // Only function declarations can be overloaded; object and type
625 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000626 Match = *I;
627 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000628 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000629 }
John McCall1f82f242009-11-18 22:49:29 +0000630
John McCalldaa3d6b2009-12-09 03:35:25 +0000631 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000632}
633
John McCalle9cccd82010-06-16 08:42:20 +0000634bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
635 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000636 // If both of the functions are extern "C", then they are not
637 // overloads.
638 if (Old->isExternC() && New->isExternC())
639 return false;
640
John McCall1f82f242009-11-18 22:49:29 +0000641 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
642 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
643
644 // C++ [temp.fct]p2:
645 // A function template can be overloaded with other function templates
646 // and with normal (non-template) functions.
647 if ((OldTemplate == 0) != (NewTemplate == 0))
648 return true;
649
650 // Is the function New an overload of the function Old?
651 QualType OldQType = Context.getCanonicalType(Old->getType());
652 QualType NewQType = Context.getCanonicalType(New->getType());
653
654 // Compare the signatures (C++ 1.3.10) of the two functions to
655 // determine whether they are overloads. If we find any mismatch
656 // in the signature, they are overloads.
657
658 // If either of these functions is a K&R-style function (no
659 // prototype), then we consider them to have matching signatures.
660 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
661 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
662 return false;
663
John McCall424cec92011-01-19 06:33:43 +0000664 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
665 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000666
667 // The signature of a function includes the types of its
668 // parameters (C++ 1.3.10), which includes the presence or absence
669 // of the ellipsis; see C++ DR 357).
670 if (OldQType != NewQType &&
671 (OldType->getNumArgs() != NewType->getNumArgs() ||
672 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000673 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000674 return true;
675
676 // C++ [temp.over.link]p4:
677 // The signature of a function template consists of its function
678 // signature, its return type and its template parameter list. The names
679 // of the template parameters are significant only for establishing the
680 // relationship between the template parameters and the rest of the
681 // signature.
682 //
683 // We check the return type and template parameter lists for function
684 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000685 //
686 // However, we don't consider either of these when deciding whether
687 // a member introduced by a shadow declaration is hidden.
688 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000689 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
690 OldTemplate->getTemplateParameters(),
691 false, TPL_TemplateMatch) ||
692 OldType->getResultType() != NewType->getResultType()))
693 return true;
694
695 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000696 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000697 //
698 // As part of this, also check whether one of the member functions
699 // is static, in which case they are not overloads (C++
700 // 13.1p2). While not part of the definition of the signature,
701 // this check is important to determine whether these functions
702 // can be overloaded.
703 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
704 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
705 if (OldMethod && NewMethod &&
706 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000707 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000708 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
709 if (!UseUsingDeclRules &&
710 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
711 (OldMethod->getRefQualifier() == RQ_None ||
712 NewMethod->getRefQualifier() == RQ_None)) {
713 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714 // - Member function declarations with the same name and the same
715 // parameter-type-list as well as member function template
716 // declarations with the same name, the same parameter-type-list, and
717 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000718 // them, but not all, have a ref-qualifier (8.3.5).
719 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
720 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
721 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
John McCall1f82f242009-11-18 22:49:29 +0000724 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000726
John McCall1f82f242009-11-18 22:49:29 +0000727 // The signatures match; this is not an overload.
728 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000729}
730
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000731/// TryImplicitConversion - Attempt to perform an implicit conversion
732/// from the given expression (Expr) to the given type (ToType). This
733/// function returns an implicit conversion sequence that can be used
734/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000735///
736/// void f(float f);
737/// void g(int i) { f(i); }
738///
739/// this routine would produce an implicit conversion sequence to
740/// describe the initialization of f from i, which will be a standard
741/// conversion sequence containing an lvalue-to-rvalue conversion (C++
742/// 4.1) followed by a floating-integral conversion (C++ 4.9).
743//
744/// Note that this routine only determines how the conversion can be
745/// performed; it does not actually perform the conversion. As such,
746/// it will not produce any diagnostics if no conversion is available,
747/// but will instead return an implicit conversion sequence of kind
748/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000749///
750/// If @p SuppressUserConversions, then user-defined conversions are
751/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000752/// If @p AllowExplicit, then explicit user-defined conversions are
753/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000754static ImplicitConversionSequence
755TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
756 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000758 bool InOverloadResolution,
759 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000760 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000761 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +0000762 ICS.Standard, CStyle)) {
John McCall0d1da222010-01-12 00:44:57 +0000763 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000764 return ICS;
765 }
766
John McCall5c32be02010-08-24 20:38:10 +0000767 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000768 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000769 return ICS;
770 }
771
Douglas Gregor836a7e82010-08-11 02:15:33 +0000772 // C++ [over.ics.user]p4:
773 // A conversion of an expression of class type to the same class
774 // type is given Exact Match rank, and a conversion of an
775 // expression of class type to a base class of that type is
776 // given Conversion rank, in spite of the fact that a copy/move
777 // constructor (i.e., a user-defined conversion function) is
778 // called for those cases.
779 QualType FromType = From->getType();
780 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000781 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
782 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000783 ICS.setStandard();
784 ICS.Standard.setAsIdentityConversion();
785 ICS.Standard.setFromType(FromType);
786 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Douglas Gregor5ab11652010-04-17 22:01:05 +0000788 // We don't actually check at this point whether there is a valid
789 // copy/move constructor, since overloading just assumes that it
790 // exists. When we actually perform initialization, we'll find the
791 // appropriate constructor to copy the returned object, if needed.
792 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000793
Douglas Gregor5ab11652010-04-17 22:01:05 +0000794 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000795 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000796 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Douglas Gregor836a7e82010-08-11 02:15:33 +0000798 return ICS;
799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
Douglas Gregor836a7e82010-08-11 02:15:33 +0000801 if (SuppressUserConversions) {
802 // We're not in the case above, so there is no conversion that
803 // we can perform.
804 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000805 return ICS;
806 }
807
808 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000809 OverloadCandidateSet Conversions(From->getExprLoc());
810 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000811 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000812 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000813
814 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000815 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000816 // C++ [over.ics.user]p4:
817 // A conversion of an expression of class type to the same class
818 // type is given Exact Match rank, and a conversion of an
819 // expression of class type to a base class of that type is
820 // given Conversion rank, in spite of the fact that a copy
821 // constructor (i.e., a user-defined conversion function) is
822 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000823 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000824 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000825 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000826 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
827 QualType ToCanon
828 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000829 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000830 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000831 // Turn this into a "standard" conversion sequence, so that it
832 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000833 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000834 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000835 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000836 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000837 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000838 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000839 ICS.Standard.Second = ICK_Derived_To_Base;
840 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000841 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000842
843 // C++ [over.best.ics]p4:
844 // However, when considering the argument of a user-defined
845 // conversion function that is a candidate by 13.3.1.3 when
846 // invoked for the copying of the temporary in the second step
847 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
848 // 13.3.1.6 in all cases, only standard conversion sequences and
849 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000850 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000851 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000852 }
John McCalle8c8cd22010-01-13 22:30:33 +0000853 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000854 ICS.setAmbiguous();
855 ICS.Ambiguous.setFromType(From->getType());
856 ICS.Ambiguous.setToType(ToType);
857 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
858 Cand != Conversions.end(); ++Cand)
859 if (Cand->Viable)
860 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000861 } else {
John McCall65eb8792010-02-25 01:37:24 +0000862 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000863 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000864
865 return ICS;
866}
867
John McCall5c32be02010-08-24 20:38:10 +0000868bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
869 const InitializedEntity &Entity,
870 Expr *Initializer,
871 bool SuppressUserConversions,
872 bool AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000873 bool InOverloadResolution,
874 bool CStyle) {
John McCall5c32be02010-08-24 20:38:10 +0000875 ImplicitConversionSequence ICS
876 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
877 SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878 AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000879 InOverloadResolution,
880 CStyle);
John McCall5c32be02010-08-24 20:38:10 +0000881 if (ICS.isBad()) return true;
882
883 // Perform the actual conversion.
884 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
885 return false;
886}
887
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000888/// PerformImplicitConversion - Perform an implicit conversion of the
889/// expression From to the type ToType. Returns true if there was an
890/// error, false otherwise. The expression From is replaced with the
891/// converted expression. Flavor is the kind of conversion we're
892/// performing, used in the error message. If @p AllowExplicit,
893/// explicit user-defined conversions are permitted.
894bool
895Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
896 AssignmentAction Action, bool AllowExplicit) {
897 ImplicitConversionSequence ICS;
898 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
899}
900
901bool
902Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
903 AssignmentAction Action, bool AllowExplicit,
904 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000905 ICS = clang::TryImplicitConversion(*this, From, ToType,
906 /*SuppressUserConversions=*/false,
907 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000908 /*InOverloadResolution=*/false,
909 /*CStyle=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000910 return PerformImplicitConversion(From, ToType, ICS, Action);
911}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000912
913/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000914/// conversion that strips "noreturn" off the nested function type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000915static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000916 QualType ToType, QualType &ResultTy) {
917 if (Context.hasSameUnqualifiedType(FromType, ToType))
918 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000919
John McCall991eb4b2010-12-21 00:44:39 +0000920 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
921 // where F adds one of the following at most once:
922 // - a pointer
923 // - a member pointer
924 // - a block pointer
925 CanQualType CanTo = Context.getCanonicalType(ToType);
926 CanQualType CanFrom = Context.getCanonicalType(FromType);
927 Type::TypeClass TyClass = CanTo->getTypeClass();
928 if (TyClass != CanFrom->getTypeClass()) return false;
929 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
930 if (TyClass == Type::Pointer) {
931 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
932 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
933 } else if (TyClass == Type::BlockPointer) {
934 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
935 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
936 } else if (TyClass == Type::MemberPointer) {
937 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
938 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
939 } else {
940 return false;
941 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000942
John McCall991eb4b2010-12-21 00:44:39 +0000943 TyClass = CanTo->getTypeClass();
944 if (TyClass != CanFrom->getTypeClass()) return false;
945 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
946 return false;
947 }
948
949 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
950 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
951 if (!EInfo.getNoReturn()) return false;
952
953 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
954 assert(QualType(FromFn, 0).isCanonical());
955 if (QualType(FromFn, 0) != CanTo) return false;
956
957 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000958 return true;
959}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960
Douglas Gregor46188682010-05-18 22:42:18 +0000961/// \brief Determine whether the conversion from FromType to ToType is a valid
962/// vector conversion.
963///
964/// \param ICK Will be set to the vector conversion kind, if this is a vector
965/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000966static bool IsVectorConversion(ASTContext &Context, QualType FromType,
967 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000968 // We need at least one of these types to be a vector type to have a vector
969 // conversion.
970 if (!ToType->isVectorType() && !FromType->isVectorType())
971 return false;
972
973 // Identical types require no conversions.
974 if (Context.hasSameUnqualifiedType(FromType, ToType))
975 return false;
976
977 // There are no conversions between extended vector types, only identity.
978 if (ToType->isExtVectorType()) {
979 // There are no conversions between extended vector types other than the
980 // identity conversion.
981 if (FromType->isExtVectorType())
982 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor46188682010-05-18 22:42:18 +0000984 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000985 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000986 ICK = ICK_Vector_Splat;
987 return true;
988 }
989 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000990
991 // We can perform the conversion between vector types in the following cases:
992 // 1)vector types are equivalent AltiVec and GCC vector types
993 // 2)lax vector conversions are permitted and the vector types are of the
994 // same size
995 if (ToType->isVectorType() && FromType->isVectorType()) {
996 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000997 (Context.getLangOptions().LaxVectorConversions &&
998 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000999 ICK = ICK_Vector_Conversion;
1000 return true;
1001 }
Douglas Gregor46188682010-05-18 22:42:18 +00001002 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001003
Douglas Gregor46188682010-05-18 22:42:18 +00001004 return false;
1005}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001007/// IsStandardConversion - Determines whether there is a standard
1008/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1009/// expression From to the type ToType. Standard conversion sequences
1010/// only consider non-class types; for conversions that involve class
1011/// types, use TryImplicitConversion. If a conversion exists, SCS will
1012/// contain the standard conversion sequence required to perform this
1013/// conversion and this routine will return true. Otherwise, this
1014/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001015static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1016 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001017 StandardConversionSequence &SCS,
1018 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001019 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001021 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001022 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001023 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001024 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001025 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001026 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001028 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001029 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001030 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001031 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001032 return false;
1033
Mike Stump11289f42009-09-09 15:08:12 +00001034 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001035 }
1036
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001037 // The first conversion can be an lvalue-to-rvalue conversion,
1038 // array-to-pointer conversion, or function-to-pointer conversion
1039 // (C++ 4p1).
1040
John McCall5c32be02010-08-24 20:38:10 +00001041 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001042 DeclAccessPair AccessPair;
1043 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001045 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001046 // We were able to resolve the address of the overloaded function,
1047 // so we can convert to the type of that function.
1048 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001049
1050 // we can sometimes resolve &foo<int> regardless of ToType, so check
1051 // if the type matches (identity) or we are converting to bool
1052 if (!S.Context.hasSameUnqualifiedType(
1053 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1054 QualType resultTy;
1055 // if the function type matches except for [[noreturn]], it's ok
1056 if (!IsNoReturnConversion(S.Context, FromType,
1057 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1058 // otherwise, only a boolean conversion is standard
1059 if (!ToType->isBooleanType())
1060 return false;
1061
1062 }
1063
Douglas Gregor980fb162010-04-29 18:24:40 +00001064 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1065 if (!Method->isStatic()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001067 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1068 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001069 }
1070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071
Douglas Gregor980fb162010-04-29 18:24:40 +00001072 // If the "from" expression takes the address of the overloaded
1073 // function, update the type of the resulting expression accordingly.
1074 if (FromType->getAs<FunctionType>())
1075 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001076 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001077 FromType = S.Context.getPointerType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078
Douglas Gregor980fb162010-04-29 18:24:40 +00001079 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001080 assert(S.Context.hasSameType(FromType,
1081 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001082 } else {
1083 return false;
1084 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001085 }
Mike Stump11289f42009-09-09 15:08:12 +00001086 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087 // An lvalue (3.10) of a non-function, non-array type T can be
1088 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001089 bool argIsLValue = From->isLValue();
1090 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001091 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001092 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001093 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001094
1095 // If T is a non-class type, the type of the rvalue is the
1096 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001097 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1098 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001100 } else if (FromType->isArrayType()) {
1101 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001102 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103
1104 // An lvalue or rvalue of type "array of N T" or "array of unknown
1105 // bound of T" can be converted to an rvalue of type "pointer to
1106 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001107 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001108
John McCall5c32be02010-08-24 20:38:10 +00001109 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001111 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001112
1113 // For the purpose of ranking in overload resolution
1114 // (13.3.3.1.1), this conversion is considered an
1115 // array-to-pointer conversion followed by a qualification
1116 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001117 SCS.Second = ICK_Identity;
1118 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001119 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001120 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001121 }
John McCall086a4642010-11-24 05:12:34 +00001122 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001123 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001124 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001125
1126 // An lvalue of function type T can be converted to an rvalue of
1127 // type "pointer to T." The result is a pointer to the
1128 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001129 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001130 } else {
1131 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001132 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001133 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001134 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135
1136 // The second conversion can be an integral promotion, floating
1137 // point promotion, integral conversion, floating point conversion,
1138 // floating-integral conversion, pointer conversion,
1139 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001140 // For overloading in C, this can also be a "compatible-type"
1141 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001142 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001143 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001144 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145 // The unqualified versions of the types are the same: there's no
1146 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001148 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001149 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001150 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001151 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001152 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001153 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001154 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001155 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001156 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001157 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001158 SCS.Second = ICK_Complex_Promotion;
1159 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001160 } else if (ToType->isBooleanType() &&
1161 (FromType->isArithmeticType() ||
1162 FromType->isAnyPointerType() ||
1163 FromType->isBlockPointerType() ||
1164 FromType->isMemberPointerType() ||
1165 FromType->isNullPtrType())) {
1166 // Boolean conversions (C++ 4.12).
1167 SCS.Second = ICK_Boolean_Conversion;
1168 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001169 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001170 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001171 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001172 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001173 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001174 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001175 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001176 SCS.Second = ICK_Complex_Conversion;
1177 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001178 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1179 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001180 // Complex-real conversions (C99 6.3.1.7)
1181 SCS.Second = ICK_Complex_Real;
1182 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001183 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001184 // Floating point conversions (C++ 4.8).
1185 SCS.Second = ICK_Floating_Conversion;
1186 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001187 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001188 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001189 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001190 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001191 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001192 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001193 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001194 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1195 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001196 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1197 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001198 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001199 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001200 SCS.IncompatibleObjC = IncompatibleObjC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001201 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001202 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001203 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001204 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001205 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001206 SCS.Second = SecondICK;
1207 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001208 } else if (!S.getLangOptions().CPlusPlus &&
1209 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001210 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001211 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001212 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001213 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001214 // Treat a conversion that strips "noreturn" as an identity conversion.
1215 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001216 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1217 InOverloadResolution,
1218 SCS, CStyle)) {
1219 SCS.Second = ICK_TransparentUnionConversion;
1220 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001221 } else {
1222 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001223 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001224 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001225 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001227 QualType CanonFrom;
1228 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001230 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001231 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001232 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001233 CanonFrom = S.Context.getCanonicalType(FromType);
1234 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235 } else {
1236 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001237 SCS.Third = ICK_Identity;
1238
Mike Stump11289f42009-09-09 15:08:12 +00001239 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001240 // [...] Any difference in top-level cv-qualification is
1241 // subsumed by the initialization itself and does not constitute
1242 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001243 CanonFrom = S.Context.getCanonicalType(FromType);
1244 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001245 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001246 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001247 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1248 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001249 FromType = ToType;
1250 CanonFrom = CanonTo;
1251 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001252 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001253 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001254
1255 // If we have not converted the argument type to the parameter type,
1256 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001257 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001258 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001260 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001261}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001262
1263static bool
1264IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1265 QualType &ToType,
1266 bool InOverloadResolution,
1267 StandardConversionSequence &SCS,
1268 bool CStyle) {
1269
1270 const RecordType *UT = ToType->getAsUnionType();
1271 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1272 return false;
1273 // The field to initialize within the transparent union.
1274 RecordDecl *UD = UT->getDecl();
1275 // It's compatible if the expression matches any of the fields.
1276 for (RecordDecl::field_iterator it = UD->field_begin(),
1277 itend = UD->field_end();
1278 it != itend; ++it) {
1279 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, CStyle)) {
1280 ToType = it->getType();
1281 return true;
1282 }
1283 }
1284 return false;
1285}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001286
1287/// IsIntegralPromotion - Determines whether the conversion from the
1288/// expression From (whose potentially-adjusted type is FromType) to
1289/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1290/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001291bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001292 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001293 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001294 if (!To) {
1295 return false;
1296 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297
1298 // An rvalue of type char, signed char, unsigned char, short int, or
1299 // unsigned short int can be converted to an rvalue of type int if
1300 // int can represent all the values of the source type; otherwise,
1301 // the source rvalue can be converted to an rvalue of type unsigned
1302 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001303 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1304 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001305 if (// We can promote any signed, promotable integer type to an int
1306 (FromType->isSignedIntegerType() ||
1307 // We can promote any unsigned integer type whose size is
1308 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001309 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001310 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001311 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001312 }
1313
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001314 return To->getKind() == BuiltinType::UInt;
1315 }
1316
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001317 // C++0x [conv.prom]p3:
1318 // A prvalue of an unscoped enumeration type whose underlying type is not
1319 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1320 // following types that can represent all the values of the enumeration
1321 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1322 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001323 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001324 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001325 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001326 // with lowest integer conversion rank (4.13) greater than the rank of long
1327 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001328 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001329 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1330 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1331 // provided for a scoped enumeration.
1332 if (FromEnumType->getDecl()->isScoped())
1333 return false;
1334
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001335 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001337 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001338 return Context.hasSameUnqualifiedType(ToType,
1339 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001340 }
John McCall56774992009-12-09 09:09:27 +00001341
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001342 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1344 // to an rvalue a prvalue of the first of the following types that can
1345 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001346 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001348 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001349 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001350 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001352 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001353 // Determine whether the type we're converting from is signed or
1354 // unsigned.
1355 bool FromIsSigned;
1356 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
John McCall56774992009-12-09 09:09:27 +00001358 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1359 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001360
1361 // The types we'll try to promote to, in the appropriate
1362 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001363 QualType PromoteTypes[6] = {
1364 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001365 Context.LongTy, Context.UnsignedLongTy ,
1366 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001367 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001368 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001369 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1370 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001371 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001372 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1373 // We found the type that we can promote to. If this is the
1374 // type we wanted, we have a promotion. Otherwise, no
1375 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001376 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001377 }
1378 }
1379 }
1380
1381 // An rvalue for an integral bit-field (9.6) can be converted to an
1382 // rvalue of type int if int can represent all the values of the
1383 // bit-field; otherwise, it can be converted to unsigned int if
1384 // unsigned int can represent all the values of the bit-field. If
1385 // the bit-field is larger yet, no integral promotion applies to
1386 // it. If the bit-field has an enumerated type, it is treated as any
1387 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001388 // FIXME: We should delay checking of bit-fields until we actually perform the
1389 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001390 using llvm::APSInt;
1391 if (From)
1392 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001393 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001394 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001395 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1396 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1397 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001398
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001399 // Are we promoting to an int from a bitfield that fits in an int?
1400 if (BitWidth < ToSize ||
1401 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1402 return To->getKind() == BuiltinType::Int;
1403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001405 // Are we promoting to an unsigned int from an unsigned bitfield
1406 // that fits into an unsigned int?
1407 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1408 return To->getKind() == BuiltinType::UInt;
1409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001411 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001412 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001413 }
Mike Stump11289f42009-09-09 15:08:12 +00001414
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001415 // An rvalue of type bool can be converted to an rvalue of type int,
1416 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001417 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001418 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001419 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001420
1421 return false;
1422}
1423
1424/// IsFloatingPointPromotion - Determines whether the conversion from
1425/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1426/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001427bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001428 /// An rvalue of type float can be converted to an rvalue of type
1429 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001430 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1431 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001432 if (FromBuiltin->getKind() == BuiltinType::Float &&
1433 ToBuiltin->getKind() == BuiltinType::Double)
1434 return true;
1435
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001436 // C99 6.3.1.5p1:
1437 // When a float is promoted to double or long double, or a
1438 // double is promoted to long double [...].
1439 if (!getLangOptions().CPlusPlus &&
1440 (FromBuiltin->getKind() == BuiltinType::Float ||
1441 FromBuiltin->getKind() == BuiltinType::Double) &&
1442 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1443 return true;
1444 }
1445
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001446 return false;
1447}
1448
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001449/// \brief Determine if a conversion is a complex promotion.
1450///
1451/// A complex promotion is defined as a complex -> complex conversion
1452/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001453/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001454bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001455 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001456 if (!FromComplex)
1457 return false;
1458
John McCall9dd450b2009-09-21 23:43:11 +00001459 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001460 if (!ToComplex)
1461 return false;
1462
1463 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001464 ToComplex->getElementType()) ||
1465 IsIntegralPromotion(0, FromComplex->getElementType(),
1466 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001467}
1468
Douglas Gregor237f96c2008-11-26 23:31:11 +00001469/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1470/// the pointer type FromPtr to a pointer to type ToPointee, with the
1471/// same type qualifiers as FromPtr has on its pointee type. ToType,
1472/// if non-empty, will be a pointer to ToType that may or may not have
1473/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001474static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001475BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001476 QualType ToPointee, QualType ToType,
1477 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001478 assert((FromPtr->getTypeClass() == Type::Pointer ||
1479 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1480 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001481
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001482 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1483 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1484 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
1486 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001487 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001488 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001489 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001490
1491 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001492 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001493 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001494 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001495 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001496
1497 // Build a pointer to ToPointee. It has the right qualifiers
1498 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001499 if (isa<ObjCObjectPointerType>(ToType))
1500 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001501 return Context.getPointerType(ToPointee);
1502 }
1503
1504 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001505 QualType QualifiedCanonToPointee
1506 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001507
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001508 if (isa<ObjCObjectPointerType>(ToType))
1509 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1510 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001511}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001512
Mike Stump11289f42009-09-09 15:08:12 +00001513static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001514 bool InOverloadResolution,
1515 ASTContext &Context) {
1516 // Handle value-dependent integral null pointer constants correctly.
1517 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1518 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001519 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001520 return !InOverloadResolution;
1521
Douglas Gregor56751b52009-09-25 04:25:58 +00001522 return Expr->isNullPointerConstant(Context,
1523 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1524 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001525}
Mike Stump11289f42009-09-09 15:08:12 +00001526
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001527/// IsPointerConversion - Determines whether the conversion of the
1528/// expression From, which has the (possibly adjusted) type FromType,
1529/// can be converted to the type ToType via a pointer conversion (C++
1530/// 4.10). If so, returns true and places the converted type (that
1531/// might differ from ToType in its cv-qualifiers at some level) into
1532/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001533///
Douglas Gregora29dc052008-11-27 01:19:21 +00001534/// This routine also supports conversions to and from block pointers
1535/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1536/// pointers to interfaces. FIXME: Once we've determined the
1537/// appropriate overloading rules for Objective-C, we may want to
1538/// split the Objective-C checks into a different routine; however,
1539/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001540/// conversions, so for now they live here. IncompatibleObjC will be
1541/// set if the conversion is an allowed Objective-C conversion that
1542/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001544 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001545 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001546 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001547 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001548 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1549 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001550 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001551
Mike Stump11289f42009-09-09 15:08:12 +00001552 // Conversion from a null pointer constant to any Objective-C pointer type.
1553 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001554 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001555 ConvertedType = ToType;
1556 return true;
1557 }
1558
Douglas Gregor231d1c62008-11-27 00:15:41 +00001559 // Blocks: Block pointers can be converted to void*.
1560 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001561 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001562 ConvertedType = ToType;
1563 return true;
1564 }
1565 // Blocks: A null pointer constant can be converted to a block
1566 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001567 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001568 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001569 ConvertedType = ToType;
1570 return true;
1571 }
1572
Sebastian Redl576fd422009-05-10 18:38:11 +00001573 // If the left-hand-side is nullptr_t, the right side can be a null
1574 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001575 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001576 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001577 ConvertedType = ToType;
1578 return true;
1579 }
1580
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001581 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001582 if (!ToTypePtr)
1583 return false;
1584
1585 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001586 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587 ConvertedType = ToType;
1588 return true;
1589 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001590
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001591 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001592 // , including objective-c pointers.
1593 QualType ToPointeeType = ToTypePtr->getPointeeType();
1594 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001595 ConvertedType = BuildSimilarlyQualifiedPointerType(
1596 FromType->getAs<ObjCObjectPointerType>(),
1597 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001598 ToType, Context);
1599 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001600 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001601 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001602 if (!FromTypePtr)
1603 return false;
1604
1605 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001606
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001607 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001608 // pointer conversion, so don't do all of the work below.
1609 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1610 return false;
1611
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612 // An rvalue of type "pointer to cv T," where T is an object type,
1613 // can be converted to an rvalue of type "pointer to cv void" (C++
1614 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001615 if (FromPointeeType->isIncompleteOrObjectType() &&
1616 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001617 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001618 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001619 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001620 return true;
1621 }
1622
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001623 // When we're overloading in C, we allow a special kind of pointer
1624 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001625 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001626 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001627 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001628 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001629 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001630 return true;
1631 }
1632
Douglas Gregor5c407d92008-10-23 00:40:37 +00001633 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001634 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001635 // An rvalue of type "pointer to cv D," where D is a class type,
1636 // can be converted to an rvalue of type "pointer to cv B," where
1637 // B is a base class (clause 10) of D. If B is an inaccessible
1638 // (clause 11) or ambiguous (10.2) base class of D, a program that
1639 // necessitates this conversion is ill-formed. The result of the
1640 // conversion is a pointer to the base class sub-object of the
1641 // derived class object. The null pointer value is converted to
1642 // the null pointer value of the destination type.
1643 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001644 // Note that we do not check for ambiguity or inaccessibility
1645 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001646 if (getLangOptions().CPlusPlus &&
1647 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001648 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001649 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001650 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001651 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001652 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001653 ToType, Context);
1654 return true;
1655 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001656
Douglas Gregora119f102008-12-19 19:13:09 +00001657 return false;
1658}
1659
1660/// isObjCPointerConversion - Determines whether this is an
1661/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1662/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001663bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001664 QualType& ConvertedType,
1665 bool &IncompatibleObjC) {
1666 if (!getLangOptions().ObjC1)
1667 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668
Steve Naroff7cae42b2009-07-10 23:34:53 +00001669 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001670 const ObjCObjectPointerType* ToObjCPtr =
1671 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001672 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001673 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001674
Steve Naroff7cae42b2009-07-10 23:34:53 +00001675 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001676 // If the pointee types are the same (ignoring qualifications),
1677 // then this is not a pointer conversion.
1678 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1679 FromObjCPtr->getPointeeType()))
1680 return false;
1681
Steve Naroff1329fa02009-07-15 18:40:39 +00001682 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001683 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001684 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001685 ConvertedType = ToType;
1686 return true;
1687 }
1688 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001689 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001690 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001691 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001692 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001693 ConvertedType = ToType;
1694 return true;
1695 }
1696 // Objective C++: We're able to convert from a pointer to an
1697 // interface to a pointer to a different interface.
1698 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001699 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1700 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1701 if (getLangOptions().CPlusPlus && LHS && RHS &&
1702 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1703 FromObjCPtr->getPointeeType()))
1704 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001705 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001706 ToObjCPtr->getPointeeType(),
1707 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001708 return true;
1709 }
1710
1711 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1712 // Okay: this is some kind of implicit downcast of Objective-C
1713 // interfaces, which is permitted. However, we're going to
1714 // complain about it.
1715 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001716 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001717 ToObjCPtr->getPointeeType(),
1718 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001719 return true;
1720 }
Mike Stump11289f42009-09-09 15:08:12 +00001721 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001722 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001723 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001724 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001725 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001727 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001728 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001729 // to a block pointer type.
1730 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1731 ConvertedType = ToType;
1732 return true;
1733 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001734 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001737 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001739 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001740 ConvertedType = ToType;
1741 return true;
1742 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001743 else
Douglas Gregora119f102008-12-19 19:13:09 +00001744 return false;
1745
Douglas Gregor033f56d2008-12-23 00:53:59 +00001746 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001747 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001748 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001749 else if (const BlockPointerType *FromBlockPtr =
1750 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001751 FromPointeeType = FromBlockPtr->getPointeeType();
1752 else
Douglas Gregora119f102008-12-19 19:13:09 +00001753 return false;
1754
Douglas Gregora119f102008-12-19 19:13:09 +00001755 // If we have pointers to pointers, recursively check whether this
1756 // is an Objective-C conversion.
1757 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1758 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1759 IncompatibleObjC)) {
1760 // We always complain about this conversion.
1761 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001762 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001763 return true;
1764 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001765 // Allow conversion of pointee being objective-c pointer to another one;
1766 // as in I* to id.
1767 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1768 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1769 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1770 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001771 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001772 return true;
1773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774
Douglas Gregor033f56d2008-12-23 00:53:59 +00001775 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001776 // differences in the argument and result types are in Objective-C
1777 // pointer conversions. If so, we permit the conversion (but
1778 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001779 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001780 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001781 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001782 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001783 if (FromFunctionType && ToFunctionType) {
1784 // If the function types are exactly the same, this isn't an
1785 // Objective-C pointer conversion.
1786 if (Context.getCanonicalType(FromPointeeType)
1787 == Context.getCanonicalType(ToPointeeType))
1788 return false;
1789
1790 // Perform the quick checks that will tell us whether these
1791 // function types are obviously different.
1792 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1793 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1794 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1795 return false;
1796
1797 bool HasObjCConversion = false;
1798 if (Context.getCanonicalType(FromFunctionType->getResultType())
1799 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1800 // Okay, the types match exactly. Nothing to do.
1801 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1802 ToFunctionType->getResultType(),
1803 ConvertedType, IncompatibleObjC)) {
1804 // Okay, we have an Objective-C pointer conversion.
1805 HasObjCConversion = true;
1806 } else {
1807 // Function types are too different. Abort.
1808 return false;
1809 }
Mike Stump11289f42009-09-09 15:08:12 +00001810
Douglas Gregora119f102008-12-19 19:13:09 +00001811 // Check argument types.
1812 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1813 ArgIdx != NumArgs; ++ArgIdx) {
1814 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1815 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1816 if (Context.getCanonicalType(FromArgType)
1817 == Context.getCanonicalType(ToArgType)) {
1818 // Okay, the types match exactly. Nothing to do.
1819 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1820 ConvertedType, IncompatibleObjC)) {
1821 // Okay, we have an Objective-C pointer conversion.
1822 HasObjCConversion = true;
1823 } else {
1824 // Argument types are too different. Abort.
1825 return false;
1826 }
1827 }
1828
1829 if (HasObjCConversion) {
1830 // We had an Objective-C conversion. Allow this pointer
1831 // conversion, but complain about it.
1832 ConvertedType = ToType;
1833 IncompatibleObjC = true;
1834 return true;
1835 }
1836 }
1837
Sebastian Redl72b597d2009-01-25 19:43:20 +00001838 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001839}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001841bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1842 QualType& ConvertedType) {
1843 QualType ToPointeeType;
1844 if (const BlockPointerType *ToBlockPtr =
1845 ToType->getAs<BlockPointerType>())
1846 ToPointeeType = ToBlockPtr->getPointeeType();
1847 else
1848 return false;
1849
1850 QualType FromPointeeType;
1851 if (const BlockPointerType *FromBlockPtr =
1852 FromType->getAs<BlockPointerType>())
1853 FromPointeeType = FromBlockPtr->getPointeeType();
1854 else
1855 return false;
1856 // We have pointer to blocks, check whether the only
1857 // differences in the argument and result types are in Objective-C
1858 // pointer conversions. If so, we permit the conversion.
1859
1860 const FunctionProtoType *FromFunctionType
1861 = FromPointeeType->getAs<FunctionProtoType>();
1862 const FunctionProtoType *ToFunctionType
1863 = ToPointeeType->getAs<FunctionProtoType>();
1864
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001865 if (!FromFunctionType || !ToFunctionType)
1866 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001867
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001868 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001869 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001870
1871 // Perform the quick checks that will tell us whether these
1872 // function types are obviously different.
1873 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1874 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1875 return false;
1876
1877 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1878 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1879 if (FromEInfo != ToEInfo)
1880 return false;
1881
1882 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00001883 if (Context.hasSameType(FromFunctionType->getResultType(),
1884 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001885 // Okay, the types match exactly. Nothing to do.
1886 } else {
1887 QualType RHS = FromFunctionType->getResultType();
1888 QualType LHS = ToFunctionType->getResultType();
1889 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1890 !RHS.hasQualifiers() && LHS.hasQualifiers())
1891 LHS = LHS.getUnqualifiedType();
1892
1893 if (Context.hasSameType(RHS,LHS)) {
1894 // OK exact match.
1895 } else if (isObjCPointerConversion(RHS, LHS,
1896 ConvertedType, IncompatibleObjC)) {
1897 if (IncompatibleObjC)
1898 return false;
1899 // Okay, we have an Objective-C pointer conversion.
1900 }
1901 else
1902 return false;
1903 }
1904
1905 // Check argument types.
1906 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1907 ArgIdx != NumArgs; ++ArgIdx) {
1908 IncompatibleObjC = false;
1909 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1910 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1911 if (Context.hasSameType(FromArgType, ToArgType)) {
1912 // Okay, the types match exactly. Nothing to do.
1913 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1914 ConvertedType, IncompatibleObjC)) {
1915 if (IncompatibleObjC)
1916 return false;
1917 // Okay, we have an Objective-C pointer conversion.
1918 } else
1919 // Argument types are too different. Abort.
1920 return false;
1921 }
1922 ConvertedType = ToType;
1923 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001924}
1925
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001926/// FunctionArgTypesAreEqual - This routine checks two function proto types
1927/// for equlity of their argument types. Caller has already checked that
1928/// they have same number of arguments. This routine assumes that Objective-C
1929/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00001931 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001932 if (!getLangOptions().ObjC1)
1933 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1934 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001935
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001936 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1937 N = NewType->arg_type_begin(),
1938 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1939 QualType ToType = (*O);
1940 QualType FromType = (*N);
1941 if (ToType != FromType) {
1942 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1943 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001944 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1945 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1946 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1947 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001948 continue;
1949 }
John McCall8b07ec22010-05-15 11:32:37 +00001950 else if (const ObjCObjectPointerType *PTTo =
1951 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00001953 FromType->getAs<ObjCObjectPointerType>())
1954 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1955 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001958 }
1959 }
1960 return true;
1961}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001962
Douglas Gregor39c16d42008-10-24 04:54:22 +00001963/// CheckPointerConversion - Check the pointer conversion from the
1964/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001965/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001966/// conversions for which IsPointerConversion has already returned
1967/// true. It returns true and produces a diagnostic if there was an
1968/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001969bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001970 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001971 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001972 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001973 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001974 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001975
John McCall8cb679e2010-11-15 09:13:47 +00001976 Kind = CK_BitCast;
1977
Douglas Gregor4038cf42010-06-08 17:35:15 +00001978 if (CXXBoolLiteralExpr* LitBool
1979 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001980 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Chandler Carruth477a9992011-03-01 03:29:37 +00001981 DiagRuntimeBehavior(LitBool->getExprLoc(), From,
1982 PDiag(diag::warn_init_pointer_from_false) << ToType);
Douglas Gregor4038cf42010-06-08 17:35:15 +00001983
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001984 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1985 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001986 QualType FromPointeeType = FromPtrType->getPointeeType(),
1987 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001988
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001989 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1990 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001991 // We must have a derived-to-base conversion. Check an
1992 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001993 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1994 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001995 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001996 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001997 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001999 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002000 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002001 }
2002 }
Mike Stump11289f42009-09-09 15:08:12 +00002003 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00002004 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002005 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00002006 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002007 // Objective-C++ conversions are always okay.
2008 // FIXME: We should have a different class of conversions for the
2009 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002010 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002011 return false;
John McCall8cb679e2010-11-15 09:13:47 +00002012 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002013 }
John McCall8cb679e2010-11-15 09:13:47 +00002014
2015 // We shouldn't fall into this case unless it's valid for other
2016 // reasons.
2017 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2018 Kind = CK_NullToPointer;
2019
Douglas Gregor39c16d42008-10-24 04:54:22 +00002020 return false;
2021}
2022
Sebastian Redl72b597d2009-01-25 19:43:20 +00002023/// IsMemberPointerConversion - Determines whether the conversion of the
2024/// expression From, which has the (possibly adjusted) type FromType, can be
2025/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2026/// If so, returns true and places the converted type (that might differ from
2027/// ToType in its cv-qualifiers at some level) into ConvertedType.
2028bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002030 bool InOverloadResolution,
2031 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002032 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002033 if (!ToTypePtr)
2034 return false;
2035
2036 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002037 if (From->isNullPointerConstant(Context,
2038 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2039 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002040 ConvertedType = ToType;
2041 return true;
2042 }
2043
2044 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002045 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002046 if (!FromTypePtr)
2047 return false;
2048
2049 // A pointer to member of B can be converted to a pointer to member of D,
2050 // where D is derived from B (C++ 4.11p2).
2051 QualType FromClass(FromTypePtr->getClass(), 0);
2052 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002053
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002054 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2055 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2056 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002057 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2058 ToClass.getTypePtr());
2059 return true;
2060 }
2061
2062 return false;
2063}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002064
Sebastian Redl72b597d2009-01-25 19:43:20 +00002065/// CheckMemberPointerConversion - Check the member pointer conversion from the
2066/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002067/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002068/// for which IsMemberPointerConversion has already returned true. It returns
2069/// true and produces a diagnostic if there was an error, or returns false
2070/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002071bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002072 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002073 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002074 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002075 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002077 if (!FromPtrType) {
2078 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002080 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002081 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002082 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002083 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002084 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002085
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002086 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002087 assert(ToPtrType && "No member pointer cast has a target type "
2088 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002089
Sebastian Redled8f2002009-01-28 18:33:18 +00002090 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2091 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002092
Sebastian Redled8f2002009-01-28 18:33:18 +00002093 // FIXME: What about dependent types?
2094 assert(FromClass->isRecordType() && "Pointer into non-class.");
2095 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002096
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002097 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002098 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002099 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2100 assert(DerivationOkay &&
2101 "Should not have been called if derivation isn't OK.");
2102 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002103
Sebastian Redled8f2002009-01-28 18:33:18 +00002104 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2105 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002106 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2107 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2108 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2109 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002110 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002111
Douglas Gregor89ee6822009-02-28 01:32:25 +00002112 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002113 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2114 << FromClass << ToClass << QualType(VBase, 0)
2115 << From->getSourceRange();
2116 return true;
2117 }
2118
John McCall5b0829a2010-02-10 09:31:12 +00002119 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002120 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2121 Paths.front(),
2122 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002123
Anders Carlssond7923c62009-08-22 23:33:40 +00002124 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002125 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002126 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002127 return false;
2128}
2129
Douglas Gregor9a657932008-10-21 23:43:52 +00002130/// IsQualificationConversion - Determines whether the conversion from
2131/// an rvalue of type FromType to ToType is a qualification conversion
2132/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00002133bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor58281352011-01-27 00:58:17 +00002135 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002136 FromType = Context.getCanonicalType(FromType);
2137 ToType = Context.getCanonicalType(ToType);
2138
2139 // If FromType and ToType are the same type, this is not a
2140 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002141 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002142 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002143
Douglas Gregor9a657932008-10-21 23:43:52 +00002144 // (C++ 4.4p4):
2145 // A conversion can add cv-qualifiers at levels other than the first
2146 // in multi-level pointers, subject to the following rules: [...]
2147 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002148 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002149 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002150 // Within each iteration of the loop, we check the qualifiers to
2151 // determine if this still looks like a qualification
2152 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002153 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002154 // until there are no more pointers or pointers-to-members left to
2155 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002156 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002157
2158 // -- for every j > 0, if const is in cv 1,j then const is in cv
2159 // 2,j, and similarly for volatile.
Douglas Gregor58281352011-01-27 00:58:17 +00002160 if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00002161 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002162
Douglas Gregor9a657932008-10-21 23:43:52 +00002163 // -- if the cv 1,j and cv 2,j are different, then const is in
2164 // every cv for 0 < k < j.
Douglas Gregor58281352011-01-27 00:58:17 +00002165 if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002166 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002167 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002168
Douglas Gregor9a657932008-10-21 23:43:52 +00002169 // Keep track of whether all prior cv-qualifiers in the "to" type
2170 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002171 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002172 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002173 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002174
2175 // We are left with FromType and ToType being the pointee types
2176 // after unwrapping the original FromType and ToType the same number
2177 // of types. If we unwrapped any pointers, and if FromType and
2178 // ToType have the same unqualified type (since we checked
2179 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002180 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002181}
2182
Douglas Gregor576e98c2009-01-30 23:27:23 +00002183/// Determines whether there is a user-defined conversion sequence
2184/// (C++ [over.ics.user]) that converts expression From to the type
2185/// ToType. If such a conversion exists, User will contain the
2186/// user-defined conversion sequence that performs such a conversion
2187/// and this routine will return true. Otherwise, this routine returns
2188/// false and User is unspecified.
2189///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002190/// \param AllowExplicit true if the conversion should consider C++0x
2191/// "explicit" conversion functions as well as non-explicit conversion
2192/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002193static OverloadingResult
2194IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2195 UserDefinedConversionSequence& User,
2196 OverloadCandidateSet& CandidateSet,
2197 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002198 // Whether we will only visit constructors.
2199 bool ConstructorsOnly = false;
2200
2201 // If the type we are conversion to is a class type, enumerate its
2202 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002203 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002204 // C++ [over.match.ctor]p1:
2205 // When objects of class type are direct-initialized (8.5), or
2206 // copy-initialized from an expression of the same or a
2207 // derived class type (8.5), overload resolution selects the
2208 // constructor. [...] For copy-initialization, the candidate
2209 // functions are all the converting constructors (12.3.1) of
2210 // that class. The argument list is the expression-list within
2211 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002212 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002213 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002214 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002215 ConstructorsOnly = true;
2216
John McCall5c32be02010-08-24 20:38:10 +00002217 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002218 // We're not going to find any constructors.
2219 } else if (CXXRecordDecl *ToRecordDecl
2220 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002221 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002222 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002223 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002224 NamedDecl *D = *Con;
2225 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2226
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002227 // Find the constructor (which may be a template).
2228 CXXConstructorDecl *Constructor = 0;
2229 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002230 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002231 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002232 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002233 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2234 else
John McCalla0296f72010-03-19 07:35:19 +00002235 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002236
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002237 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002238 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002239 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002240 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2241 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002243 /*SuppressUserConversions=*/
2244 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002245 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002246 // Allow one user-defined conversion when user specifies a
2247 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002248 S.AddOverloadCandidate(Constructor, FoundDecl,
2249 &From, 1, CandidateSet,
2250 /*SuppressUserConversions=*/
2251 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002252 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002253 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002254 }
2255 }
2256
Douglas Gregor5ab11652010-04-17 22:01:05 +00002257 // Enumerate conversion functions, if we're allowed to.
2258 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002259 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2260 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002261 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002262 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002263 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002264 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002265 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2266 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002267 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002268 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002269 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002270 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002271 DeclAccessPair FoundDecl = I.getPair();
2272 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002273 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2274 if (isa<UsingShadowDecl>(D))
2275 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2276
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002277 CXXConversionDecl *Conv;
2278 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002279 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2280 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002281 else
John McCallda4458e2010-03-31 01:36:47 +00002282 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002283
2284 if (AllowExplicit || !Conv->isExplicit()) {
2285 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002286 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2287 ActingContext, From, ToType,
2288 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002289 else
John McCall5c32be02010-08-24 20:38:10 +00002290 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2291 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002292 }
2293 }
2294 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002295 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002296
2297 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002298 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002299 case OR_Success:
2300 // Record the standard conversion we used and the conversion function.
2301 if (CXXConstructorDecl *Constructor
2302 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002303 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2304
John McCall5c32be02010-08-24 20:38:10 +00002305 // C++ [over.ics.user]p1:
2306 // If the user-defined conversion is specified by a
2307 // constructor (12.3.1), the initial standard conversion
2308 // sequence converts the source type to the type required by
2309 // the argument of the constructor.
2310 //
2311 QualType ThisType = Constructor->getThisType(S.Context);
2312 if (Best->Conversions[0].isEllipsis())
2313 User.EllipsisConversion = true;
2314 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002315 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002316 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002317 }
John McCall5c32be02010-08-24 20:38:10 +00002318 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002319 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002320 User.After.setAsIdentityConversion();
2321 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2322 User.After.setAllToTypes(ToType);
2323 return OR_Success;
2324 } else if (CXXConversionDecl *Conversion
2325 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002326 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2327
John McCall5c32be02010-08-24 20:38:10 +00002328 // C++ [over.ics.user]p1:
2329 //
2330 // [...] If the user-defined conversion is specified by a
2331 // conversion function (12.3.2), the initial standard
2332 // conversion sequence converts the source type to the
2333 // implicit object parameter of the conversion function.
2334 User.Before = Best->Conversions[0].Standard;
2335 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002336 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002337 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002338
John McCall5c32be02010-08-24 20:38:10 +00002339 // C++ [over.ics.user]p2:
2340 // The second standard conversion sequence converts the
2341 // result of the user-defined conversion to the target type
2342 // for the sequence. Since an implicit conversion sequence
2343 // is an initialization, the special rules for
2344 // initialization by user-defined conversion apply when
2345 // selecting the best user-defined conversion for a
2346 // user-defined conversion sequence (see 13.3.3 and
2347 // 13.3.3.1).
2348 User.After = Best->FinalConversion;
2349 return OR_Success;
2350 } else {
2351 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002352 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002353 }
2354
John McCall5c32be02010-08-24 20:38:10 +00002355 case OR_No_Viable_Function:
2356 return OR_No_Viable_Function;
2357 case OR_Deleted:
2358 // No conversion here! We're done.
2359 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
John McCall5c32be02010-08-24 20:38:10 +00002361 case OR_Ambiguous:
2362 return OR_Ambiguous;
2363 }
2364
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002365 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002366}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002367
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002368bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002369Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002370 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002371 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002372 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002373 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002374 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002375 if (OvResult == OR_Ambiguous)
2376 Diag(From->getSourceRange().getBegin(),
2377 diag::err_typecheck_ambiguous_condition)
2378 << From->getType() << ToType << From->getSourceRange();
2379 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2380 Diag(From->getSourceRange().getBegin(),
2381 diag::err_typecheck_nonviable_condition)
2382 << From->getType() << ToType << From->getSourceRange();
2383 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002384 return false;
John McCall5c32be02010-08-24 20:38:10 +00002385 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002386 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002387}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002388
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002389/// CompareImplicitConversionSequences - Compare two implicit
2390/// conversion sequences to determine whether one is better than the
2391/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002392static ImplicitConversionSequence::CompareKind
2393CompareImplicitConversionSequences(Sema &S,
2394 const ImplicitConversionSequence& ICS1,
2395 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002396{
2397 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2398 // conversion sequences (as defined in 13.3.3.1)
2399 // -- a standard conversion sequence (13.3.3.1.1) is a better
2400 // conversion sequence than a user-defined conversion sequence or
2401 // an ellipsis conversion sequence, and
2402 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2403 // conversion sequence than an ellipsis conversion sequence
2404 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002405 //
John McCall0d1da222010-01-12 00:44:57 +00002406 // C++0x [over.best.ics]p10:
2407 // For the purpose of ranking implicit conversion sequences as
2408 // described in 13.3.3.2, the ambiguous conversion sequence is
2409 // treated as a user-defined sequence that is indistinguishable
2410 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002411 if (ICS1.getKindRank() < ICS2.getKindRank())
2412 return ImplicitConversionSequence::Better;
2413 else if (ICS2.getKindRank() < ICS1.getKindRank())
2414 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002415
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002416 // The following checks require both conversion sequences to be of
2417 // the same kind.
2418 if (ICS1.getKind() != ICS2.getKind())
2419 return ImplicitConversionSequence::Indistinguishable;
2420
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002421 // Two implicit conversion sequences of the same form are
2422 // indistinguishable conversion sequences unless one of the
2423 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002424 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002425 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002426 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002427 // User-defined conversion sequence U1 is a better conversion
2428 // sequence than another user-defined conversion sequence U2 if
2429 // they contain the same user-defined conversion function or
2430 // constructor and if the second standard conversion sequence of
2431 // U1 is better than the second standard conversion sequence of
2432 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002433 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002434 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002435 return CompareStandardConversionSequences(S,
2436 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002437 ICS2.UserDefined.After);
2438 }
2439
2440 return ImplicitConversionSequence::Indistinguishable;
2441}
2442
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002443static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2444 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2445 Qualifiers Quals;
2446 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002447 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002449
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002450 return Context.hasSameUnqualifiedType(T1, T2);
2451}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002453// Per 13.3.3.2p3, compare the given standard conversion sequences to
2454// determine if one is a proper subset of the other.
2455static ImplicitConversionSequence::CompareKind
2456compareStandardConversionSubsets(ASTContext &Context,
2457 const StandardConversionSequence& SCS1,
2458 const StandardConversionSequence& SCS2) {
2459 ImplicitConversionSequence::CompareKind Result
2460 = ImplicitConversionSequence::Indistinguishable;
2461
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002462 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002463 // any non-identity conversion sequence
2464 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2465 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2466 return ImplicitConversionSequence::Better;
2467 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2468 return ImplicitConversionSequence::Worse;
2469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002471 if (SCS1.Second != SCS2.Second) {
2472 if (SCS1.Second == ICK_Identity)
2473 Result = ImplicitConversionSequence::Better;
2474 else if (SCS2.Second == ICK_Identity)
2475 Result = ImplicitConversionSequence::Worse;
2476 else
2477 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002478 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002479 return ImplicitConversionSequence::Indistinguishable;
2480
2481 if (SCS1.Third == SCS2.Third) {
2482 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2483 : ImplicitConversionSequence::Indistinguishable;
2484 }
2485
2486 if (SCS1.Third == ICK_Identity)
2487 return Result == ImplicitConversionSequence::Worse
2488 ? ImplicitConversionSequence::Indistinguishable
2489 : ImplicitConversionSequence::Better;
2490
2491 if (SCS2.Third == ICK_Identity)
2492 return Result == ImplicitConversionSequence::Better
2493 ? ImplicitConversionSequence::Indistinguishable
2494 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002495
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002496 return ImplicitConversionSequence::Indistinguishable;
2497}
2498
Douglas Gregore696ebb2011-01-26 14:52:12 +00002499/// \brief Determine whether one of the given reference bindings is better
2500/// than the other based on what kind of bindings they are.
2501static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2502 const StandardConversionSequence &SCS2) {
2503 // C++0x [over.ics.rank]p3b4:
2504 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2505 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002507 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002508 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002509 // reference*.
2510 //
2511 // FIXME: Rvalue references. We're going rogue with the above edits,
2512 // because the semantics in the current C++0x working paper (N3225 at the
2513 // time of this writing) break the standard definition of std::forward
2514 // and std::reference_wrapper when dealing with references to functions.
2515 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002516 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2517 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2518 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002519
Douglas Gregore696ebb2011-01-26 14:52:12 +00002520 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2521 SCS2.IsLvalueReference) ||
2522 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2523 !SCS2.IsLvalueReference);
2524}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002525
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002526/// CompareStandardConversionSequences - Compare two standard
2527/// conversion sequences to determine whether one is better than the
2528/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002529static ImplicitConversionSequence::CompareKind
2530CompareStandardConversionSequences(Sema &S,
2531 const StandardConversionSequence& SCS1,
2532 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002533{
2534 // Standard conversion sequence S1 is a better conversion sequence
2535 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2536
2537 // -- S1 is a proper subsequence of S2 (comparing the conversion
2538 // sequences in the canonical form defined by 13.3.3.1.1,
2539 // excluding any Lvalue Transformation; the identity conversion
2540 // sequence is considered to be a subsequence of any
2541 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002542 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002543 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002544 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002545
2546 // -- the rank of S1 is better than the rank of S2 (by the rules
2547 // defined below), or, if not that,
2548 ImplicitConversionRank Rank1 = SCS1.getRank();
2549 ImplicitConversionRank Rank2 = SCS2.getRank();
2550 if (Rank1 < Rank2)
2551 return ImplicitConversionSequence::Better;
2552 else if (Rank2 < Rank1)
2553 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002554
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002555 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2556 // are indistinguishable unless one of the following rules
2557 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002558
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002559 // A conversion that is not a conversion of a pointer, or
2560 // pointer to member, to bool is better than another conversion
2561 // that is such a conversion.
2562 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2563 return SCS2.isPointerConversionToBool()
2564 ? ImplicitConversionSequence::Better
2565 : ImplicitConversionSequence::Worse;
2566
Douglas Gregor5c407d92008-10-23 00:40:37 +00002567 // C++ [over.ics.rank]p4b2:
2568 //
2569 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002570 // conversion of B* to A* is better than conversion of B* to
2571 // void*, and conversion of A* to void* is better than conversion
2572 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002573 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002574 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002575 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002576 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002577 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2578 // Exactly one of the conversion sequences is a conversion to
2579 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002580 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2581 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002582 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2583 // Neither conversion sequence converts to a void pointer; compare
2584 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002585 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002586 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002587 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002588 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2589 // Both conversion sequences are conversions to void
2590 // pointers. Compare the source types to determine if there's an
2591 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002592 QualType FromType1 = SCS1.getFromType();
2593 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002594
2595 // Adjust the types we're converting from via the array-to-pointer
2596 // conversion, if we need to.
2597 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002598 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002599 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002600 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002601
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002602 QualType FromPointee1
2603 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2604 QualType FromPointee2
2605 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002606
John McCall5c32be02010-08-24 20:38:10 +00002607 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002608 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002609 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002610 return ImplicitConversionSequence::Worse;
2611
2612 // Objective-C++: If one interface is more specific than the
2613 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002614 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2615 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002616 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002617 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002618 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002619 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002620 return ImplicitConversionSequence::Worse;
2621 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002622 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002623
2624 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2625 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002626 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002627 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002628 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002629
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002630 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002631 // Check for a better reference binding based on the kind of bindings.
2632 if (isBetterReferenceBindingKind(SCS1, SCS2))
2633 return ImplicitConversionSequence::Better;
2634 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2635 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002636
Sebastian Redlb28b4072009-03-22 23:49:27 +00002637 // C++ [over.ics.rank]p3b4:
2638 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2639 // which the references refer are the same type except for
2640 // top-level cv-qualifiers, and the type to which the reference
2641 // initialized by S2 refers is more cv-qualified than the type
2642 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002643 QualType T1 = SCS1.getToType(2);
2644 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002645 T1 = S.Context.getCanonicalType(T1);
2646 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002647 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002648 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2649 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002650 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002651 // If the type is an array type, promote the element qualifiers to the
2652 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002653 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002654 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002655 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002656 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002657 if (T2.isMoreQualifiedThan(T1))
2658 return ImplicitConversionSequence::Better;
2659 else if (T1.isMoreQualifiedThan(T2))
2660 return ImplicitConversionSequence::Worse;
2661 }
2662 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002663
2664 return ImplicitConversionSequence::Indistinguishable;
2665}
2666
2667/// CompareQualificationConversions - Compares two standard conversion
2668/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002669/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2670ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002671CompareQualificationConversions(Sema &S,
2672 const StandardConversionSequence& SCS1,
2673 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002674 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002675 // -- S1 and S2 differ only in their qualification conversion and
2676 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2677 // cv-qualification signature of type T1 is a proper subset of
2678 // the cv-qualification signature of type T2, and S1 is not the
2679 // deprecated string literal array-to-pointer conversion (4.2).
2680 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2681 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2682 return ImplicitConversionSequence::Indistinguishable;
2683
2684 // FIXME: the example in the standard doesn't use a qualification
2685 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002686 QualType T1 = SCS1.getToType(2);
2687 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002688 T1 = S.Context.getCanonicalType(T1);
2689 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002690 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002691 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2692 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002693
2694 // If the types are the same, we won't learn anything by unwrapped
2695 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002696 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002697 return ImplicitConversionSequence::Indistinguishable;
2698
Chandler Carruth607f38e2009-12-29 07:16:59 +00002699 // If the type is an array type, promote the element qualifiers to the type
2700 // for comparison.
2701 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002702 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002703 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002704 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002705
Mike Stump11289f42009-09-09 15:08:12 +00002706 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002707 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002708 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002709 // Within each iteration of the loop, we check the qualifiers to
2710 // determine if this still looks like a qualification
2711 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002712 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002713 // until there are no more pointers or pointers-to-members left
2714 // to unwrap. This essentially mimics what
2715 // IsQualificationConversion does, but here we're checking for a
2716 // strict subset of qualifiers.
2717 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2718 // The qualifiers are the same, so this doesn't tell us anything
2719 // about how the sequences rank.
2720 ;
2721 else if (T2.isMoreQualifiedThan(T1)) {
2722 // T1 has fewer qualifiers, so it could be the better sequence.
2723 if (Result == ImplicitConversionSequence::Worse)
2724 // Neither has qualifiers that are a subset of the other's
2725 // qualifiers.
2726 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002727
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002728 Result = ImplicitConversionSequence::Better;
2729 } else if (T1.isMoreQualifiedThan(T2)) {
2730 // T2 has fewer qualifiers, so it could be the better sequence.
2731 if (Result == ImplicitConversionSequence::Better)
2732 // Neither has qualifiers that are a subset of the other's
2733 // qualifiers.
2734 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002735
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002736 Result = ImplicitConversionSequence::Worse;
2737 } else {
2738 // Qualifiers are disjoint.
2739 return ImplicitConversionSequence::Indistinguishable;
2740 }
2741
2742 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002743 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002744 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002745 }
2746
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002747 // Check that the winning standard conversion sequence isn't using
2748 // the deprecated string literal array to pointer conversion.
2749 switch (Result) {
2750 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002751 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002752 Result = ImplicitConversionSequence::Indistinguishable;
2753 break;
2754
2755 case ImplicitConversionSequence::Indistinguishable:
2756 break;
2757
2758 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002759 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002760 Result = ImplicitConversionSequence::Indistinguishable;
2761 break;
2762 }
2763
2764 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002765}
2766
Douglas Gregor5c407d92008-10-23 00:40:37 +00002767/// CompareDerivedToBaseConversions - Compares two standard conversion
2768/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002769/// various kinds of derived-to-base conversions (C++
2770/// [over.ics.rank]p4b3). As part of these checks, we also look at
2771/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002772ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002773CompareDerivedToBaseConversions(Sema &S,
2774 const StandardConversionSequence& SCS1,
2775 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002776 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002777 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002778 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002779 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002780
2781 // Adjust the types we're converting from via the array-to-pointer
2782 // conversion, if we need to.
2783 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002784 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002785 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002786 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002787
2788 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002789 FromType1 = S.Context.getCanonicalType(FromType1);
2790 ToType1 = S.Context.getCanonicalType(ToType1);
2791 FromType2 = S.Context.getCanonicalType(FromType2);
2792 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002793
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002794 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002795 //
2796 // If class B is derived directly or indirectly from class A and
2797 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002798 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002799 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002800 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002801 SCS2.Second == ICK_Pointer_Conversion &&
2802 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2803 FromType1->isPointerType() && FromType2->isPointerType() &&
2804 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002805 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002806 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002807 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002808 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002809 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002810 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002811 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002812 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002813
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002814 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002815 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002816 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002817 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002818 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002819 return ImplicitConversionSequence::Worse;
2820 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002821
2822 // -- conversion of B* to A* is better than conversion of C* to A*,
2823 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002824 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002825 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002826 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002827 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00002828 }
2829 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2830 SCS2.Second == ICK_Pointer_Conversion) {
2831 const ObjCObjectPointerType *FromPtr1
2832 = FromType1->getAs<ObjCObjectPointerType>();
2833 const ObjCObjectPointerType *FromPtr2
2834 = FromType2->getAs<ObjCObjectPointerType>();
2835 const ObjCObjectPointerType *ToPtr1
2836 = ToType1->getAs<ObjCObjectPointerType>();
2837 const ObjCObjectPointerType *ToPtr2
2838 = ToType2->getAs<ObjCObjectPointerType>();
2839
2840 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2841 // Apply the same conversion ranking rules for Objective-C pointer types
2842 // that we do for C++ pointers to class types. However, we employ the
2843 // Objective-C pseudo-subtyping relationship used for assignment of
2844 // Objective-C pointer types.
2845 bool FromAssignLeft
2846 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2847 bool FromAssignRight
2848 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2849 bool ToAssignLeft
2850 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2851 bool ToAssignRight
2852 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2853
2854 // A conversion to an a non-id object pointer type or qualified 'id'
2855 // type is better than a conversion to 'id'.
2856 if (ToPtr1->isObjCIdType() &&
2857 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2858 return ImplicitConversionSequence::Worse;
2859 if (ToPtr2->isObjCIdType() &&
2860 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2861 return ImplicitConversionSequence::Better;
2862
2863 // A conversion to a non-id object pointer type is better than a
2864 // conversion to a qualified 'id' type
2865 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2866 return ImplicitConversionSequence::Worse;
2867 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2868 return ImplicitConversionSequence::Better;
2869
2870 // A conversion to an a non-Class object pointer type or qualified 'Class'
2871 // type is better than a conversion to 'Class'.
2872 if (ToPtr1->isObjCClassType() &&
2873 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2874 return ImplicitConversionSequence::Worse;
2875 if (ToPtr2->isObjCClassType() &&
2876 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2877 return ImplicitConversionSequence::Better;
2878
2879 // A conversion to a non-Class object pointer type is better than a
2880 // conversion to a qualified 'Class' type.
2881 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2882 return ImplicitConversionSequence::Worse;
2883 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2884 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00002885
Douglas Gregor058d3de2011-01-31 18:51:41 +00002886 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2887 if (S.Context.hasSameType(FromType1, FromType2) &&
2888 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2889 (ToAssignLeft != ToAssignRight))
2890 return ToAssignLeft? ImplicitConversionSequence::Worse
2891 : ImplicitConversionSequence::Better;
2892
2893 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2894 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2895 (FromAssignLeft != FromAssignRight))
2896 return FromAssignLeft? ImplicitConversionSequence::Better
2897 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002898 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002899 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00002900
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002901 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002902 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2903 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2904 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002905 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002906 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002907 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002908 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002909 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002910 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002912 ToType2->getAs<MemberPointerType>();
2913 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2914 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2915 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2916 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2917 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2918 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2919 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2920 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002921 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002922 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002923 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002924 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002925 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002926 return ImplicitConversionSequence::Better;
2927 }
2928 // conversion of B::* to C::* is better than conversion of A::* to C::*
2929 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002930 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002931 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002932 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002933 return ImplicitConversionSequence::Worse;
2934 }
2935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002936
Douglas Gregor5ab11652010-04-17 22:01:05 +00002937 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002938 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002939 // -- binding of an expression of type C to a reference of type
2940 // B& is better than binding an expression of type C to a
2941 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002942 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2943 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2944 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002945 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002946 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002947 return ImplicitConversionSequence::Worse;
2948 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002949
Douglas Gregor2fe98832008-11-03 19:09:14 +00002950 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002951 // -- binding of an expression of type B to a reference of type
2952 // A& is better than binding an expression of type C to a
2953 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002954 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2955 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2956 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002957 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002958 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002959 return ImplicitConversionSequence::Worse;
2960 }
2961 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002962
Douglas Gregor5c407d92008-10-23 00:40:37 +00002963 return ImplicitConversionSequence::Indistinguishable;
2964}
2965
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002966/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2967/// determine whether they are reference-related,
2968/// reference-compatible, reference-compatible with added
2969/// qualification, or incompatible, for use in C++ initialization by
2970/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2971/// type, and the first type (T1) is the pointee type of the reference
2972/// type being initialized.
2973Sema::ReferenceCompareResult
2974Sema::CompareReferenceRelationship(SourceLocation Loc,
2975 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002976 bool &DerivedToBase,
2977 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002978 assert(!OrigT1->isReferenceType() &&
2979 "T1 must be the pointee type of the reference type");
2980 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2981
2982 QualType T1 = Context.getCanonicalType(OrigT1);
2983 QualType T2 = Context.getCanonicalType(OrigT2);
2984 Qualifiers T1Quals, T2Quals;
2985 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2986 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2987
2988 // C++ [dcl.init.ref]p4:
2989 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2990 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2991 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002992 DerivedToBase = false;
2993 ObjCConversion = false;
2994 if (UnqualT1 == UnqualT2) {
2995 // Nothing to do.
2996 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002997 IsDerivedFrom(UnqualT2, UnqualT1))
2998 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002999 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3000 UnqualT2->isObjCObjectOrInterfaceType() &&
3001 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3002 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003003 else
3004 return Ref_Incompatible;
3005
3006 // At this point, we know that T1 and T2 are reference-related (at
3007 // least).
3008
3009 // If the type is an array type, promote the element qualifiers to the type
3010 // for comparison.
3011 if (isa<ArrayType>(T1) && T1Quals)
3012 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3013 if (isa<ArrayType>(T2) && T2Quals)
3014 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3015
3016 // C++ [dcl.init.ref]p4:
3017 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3018 // reference-related to T2 and cv1 is the same cv-qualification
3019 // as, or greater cv-qualification than, cv2. For purposes of
3020 // overload resolution, cases for which cv1 is greater
3021 // cv-qualification than cv2 are identified as
3022 // reference-compatible with added qualification (see 13.3.3.2).
3023 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
3024 return Ref_Compatible;
3025 else if (T1.isMoreQualifiedThan(T2))
3026 return Ref_Compatible_With_Added_Qualification;
3027 else
3028 return Ref_Related;
3029}
3030
Douglas Gregor836a7e82010-08-11 02:15:33 +00003031/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003032/// with DeclType. Return true if something definite is found.
3033static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003034FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3035 QualType DeclType, SourceLocation DeclLoc,
3036 Expr *Init, QualType T2, bool AllowRvalues,
3037 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003038 assert(T2->isRecordType() && "Can only find conversions of record types.");
3039 CXXRecordDecl *T2RecordDecl
3040 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3041
3042 OverloadCandidateSet CandidateSet(DeclLoc);
3043 const UnresolvedSetImpl *Conversions
3044 = T2RecordDecl->getVisibleConversionFunctions();
3045 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3046 E = Conversions->end(); I != E; ++I) {
3047 NamedDecl *D = *I;
3048 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3049 if (isa<UsingShadowDecl>(D))
3050 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3051
3052 FunctionTemplateDecl *ConvTemplate
3053 = dyn_cast<FunctionTemplateDecl>(D);
3054 CXXConversionDecl *Conv;
3055 if (ConvTemplate)
3056 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3057 else
3058 Conv = cast<CXXConversionDecl>(D);
3059
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003061 // explicit conversions, skip it.
3062 if (!AllowExplicit && Conv->isExplicit())
3063 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064
Douglas Gregor836a7e82010-08-11 02:15:33 +00003065 if (AllowRvalues) {
3066 bool DerivedToBase = false;
3067 bool ObjCConversion = false;
3068 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003069 S.CompareReferenceRelationship(
3070 DeclLoc,
3071 Conv->getConversionType().getNonReferenceType()
3072 .getUnqualifiedType(),
3073 DeclType.getNonReferenceType().getUnqualifiedType(),
3074 DerivedToBase, ObjCConversion) ==
3075 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003076 continue;
3077 } else {
3078 // If the conversion function doesn't return a reference type,
3079 // it can't be considered for this conversion. An rvalue reference
3080 // is only acceptable if its referencee is a function type.
3081
3082 const ReferenceType *RefType =
3083 Conv->getConversionType()->getAs<ReferenceType>();
3084 if (!RefType ||
3085 (!RefType->isLValueReferenceType() &&
3086 !RefType->getPointeeType()->isFunctionType()))
3087 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089
Douglas Gregor836a7e82010-08-11 02:15:33 +00003090 if (ConvTemplate)
3091 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003092 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003093 else
3094 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003095 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003096 }
3097
3098 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003099 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003100 case OR_Success:
3101 // C++ [over.ics.ref]p1:
3102 //
3103 // [...] If the parameter binds directly to the result of
3104 // applying a conversion function to the argument
3105 // expression, the implicit conversion sequence is a
3106 // user-defined conversion sequence (13.3.3.1.2), with the
3107 // second standard conversion sequence either an identity
3108 // conversion or, if the conversion function returns an
3109 // entity of a type that is a derived class of the parameter
3110 // type, a derived-to-base Conversion.
3111 if (!Best->FinalConversion.DirectBinding)
3112 return false;
3113
Chandler Carruth30141632011-02-25 19:41:05 +00003114 if (Best->Function)
3115 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003116 ICS.setUserDefined();
3117 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3118 ICS.UserDefined.After = Best->FinalConversion;
3119 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003120 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003121 ICS.UserDefined.EllipsisConversion = false;
3122 assert(ICS.UserDefined.After.ReferenceBinding &&
3123 ICS.UserDefined.After.DirectBinding &&
3124 "Expected a direct reference binding!");
3125 return true;
3126
3127 case OR_Ambiguous:
3128 ICS.setAmbiguous();
3129 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3130 Cand != CandidateSet.end(); ++Cand)
3131 if (Cand->Viable)
3132 ICS.Ambiguous.addConversion(Cand->Function);
3133 return true;
3134
3135 case OR_No_Viable_Function:
3136 case OR_Deleted:
3137 // There was no suitable conversion, or we found a deleted
3138 // conversion; continue with other checks.
3139 return false;
3140 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003141
Eric Christopheraba9fb22010-06-30 18:36:32 +00003142 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003143}
3144
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003145/// \brief Compute an implicit conversion sequence for reference
3146/// initialization.
3147static ImplicitConversionSequence
3148TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3149 SourceLocation DeclLoc,
3150 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003151 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003152 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3153
3154 // Most paths end in a failed conversion.
3155 ImplicitConversionSequence ICS;
3156 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3157
3158 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3159 QualType T2 = Init->getType();
3160
3161 // If the initializer is the address of an overloaded function, try
3162 // to resolve the overloaded function. If all goes well, T2 is the
3163 // type of the resulting function.
3164 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3165 DeclAccessPair Found;
3166 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3167 false, Found))
3168 T2 = Fn->getType();
3169 }
3170
3171 // Compute some basic properties of the types and the initializer.
3172 bool isRValRef = DeclType->isRValueReferenceType();
3173 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003174 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003175 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003176 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003177 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3178 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003179
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003180
Sebastian Redld92badf2010-06-30 18:13:39 +00003181 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003182 // A reference to type "cv1 T1" is initialized by an expression
3183 // of type "cv2 T2" as follows:
3184
Sebastian Redld92badf2010-06-30 18:13:39 +00003185 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003186 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003187 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3188 // reference-compatible with "cv2 T2," or
3189 //
3190 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3191 if (InitCategory.isLValue() &&
3192 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003193 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003194 // When a parameter of reference type binds directly (8.5.3)
3195 // to an argument expression, the implicit conversion sequence
3196 // is the identity conversion, unless the argument expression
3197 // has a type that is a derived class of the parameter type,
3198 // in which case the implicit conversion sequence is a
3199 // derived-to-base Conversion (13.3.3.1).
3200 ICS.setStandard();
3201 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003202 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3203 : ObjCConversion? ICK_Compatible_Conversion
3204 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003205 ICS.Standard.Third = ICK_Identity;
3206 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3207 ICS.Standard.setToType(0, T2);
3208 ICS.Standard.setToType(1, T1);
3209 ICS.Standard.setToType(2, T1);
3210 ICS.Standard.ReferenceBinding = true;
3211 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003212 ICS.Standard.IsLvalueReference = !isRValRef;
3213 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3214 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003215 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003216 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003217
Sebastian Redld92badf2010-06-30 18:13:39 +00003218 // Nothing more to do: the inaccessibility/ambiguity check for
3219 // derived-to-base conversions is suppressed when we're
3220 // computing the implicit conversion sequence (C++
3221 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003222 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003223 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003224
Sebastian Redld92badf2010-06-30 18:13:39 +00003225 // -- has a class type (i.e., T2 is a class type), where T1 is
3226 // not reference-related to T2, and can be implicitly
3227 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3228 // is reference-compatible with "cv3 T3" 92) (this
3229 // conversion is selected by enumerating the applicable
3230 // conversion functions (13.3.1.6) and choosing the best
3231 // one through overload resolution (13.3)),
3232 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003234 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003235 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3236 Init, T2, /*AllowRvalues=*/false,
3237 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003238 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003239 }
3240 }
3241
Sebastian Redld92badf2010-06-30 18:13:39 +00003242 // -- Otherwise, the reference shall be an lvalue reference to a
3243 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003244 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003246 // We actually handle one oddity of C++ [over.ics.ref] at this
3247 // point, which is that, due to p2 (which short-circuits reference
3248 // binding by only attempting a simple conversion for non-direct
3249 // bindings) and p3's strange wording, we allow a const volatile
3250 // reference to bind to an rvalue. Hence the check for the presence
3251 // of "const" rather than checking for "const" being the only
3252 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003253 // This is also the point where rvalue references and lvalue inits no longer
3254 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003255 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003256 return ICS;
3257
Douglas Gregorf143cd52011-01-24 16:14:37 +00003258 // -- If the initializer expression
3259 //
3260 // -- is an xvalue, class prvalue, array prvalue or function
3261 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3262 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3263 (InitCategory.isXValue() ||
3264 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3265 (InitCategory.isLValue() && T2->isFunctionType()))) {
3266 ICS.setStandard();
3267 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003268 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003269 : ObjCConversion? ICK_Compatible_Conversion
3270 : ICK_Identity;
3271 ICS.Standard.Third = ICK_Identity;
3272 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3273 ICS.Standard.setToType(0, T2);
3274 ICS.Standard.setToType(1, T1);
3275 ICS.Standard.setToType(2, T1);
3276 ICS.Standard.ReferenceBinding = true;
3277 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3278 // binding unless we're binding to a class prvalue.
3279 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3280 // allow the use of rvalue references in C++98/03 for the benefit of
3281 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003282 ICS.Standard.DirectBinding =
3283 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003284 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003285 ICS.Standard.IsLvalueReference = !isRValRef;
3286 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003288 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003289 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003291 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003292
Douglas Gregorf143cd52011-01-24 16:14:37 +00003293 // -- has a class type (i.e., T2 is a class type), where T1 is not
3294 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003295 // an xvalue, class prvalue, or function lvalue of type
3296 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003297 // "cv3 T3",
3298 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003299 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003300 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003301 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003302 // class subobject).
3303 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003305 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3306 Init, T2, /*AllowRvalues=*/true,
3307 AllowExplicit)) {
3308 // In the second case, if the reference is an rvalue reference
3309 // and the second standard conversion sequence of the
3310 // user-defined conversion sequence includes an lvalue-to-rvalue
3311 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003313 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3314 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3315
Douglas Gregor95273c32011-01-21 16:36:05 +00003316 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003319 // -- Otherwise, a temporary of type "cv1 T1" is created and
3320 // initialized from the initializer expression using the
3321 // rules for a non-reference copy initialization (8.5). The
3322 // reference is then bound to the temporary. If T1 is
3323 // reference-related to T2, cv1 must be the same
3324 // cv-qualification as, or greater cv-qualification than,
3325 // cv2; otherwise, the program is ill-formed.
3326 if (RefRelationship == Sema::Ref_Related) {
3327 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3328 // we would be reference-compatible or reference-compatible with
3329 // added qualification. But that wasn't the case, so the reference
3330 // initialization fails.
3331 return ICS;
3332 }
3333
3334 // If at least one of the types is a class type, the types are not
3335 // related, and we aren't allowed any user conversions, the
3336 // reference binding fails. This case is important for breaking
3337 // recursion, since TryImplicitConversion below will attempt to
3338 // create a temporary through the use of a copy constructor.
3339 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3340 (T1->isRecordType() || T2->isRecordType()))
3341 return ICS;
3342
Douglas Gregorcba72b12011-01-21 05:18:22 +00003343 // If T1 is reference-related to T2 and the reference is an rvalue
3344 // reference, the initializer expression shall not be an lvalue.
3345 if (RefRelationship >= Sema::Ref_Related &&
3346 isRValRef && Init->Classify(S.Context).isLValue())
3347 return ICS;
3348
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003349 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003350 // When a parameter of reference type is not bound directly to
3351 // an argument expression, the conversion sequence is the one
3352 // required to convert the argument expression to the
3353 // underlying type of the reference according to
3354 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3355 // to copy-initializing a temporary of the underlying type with
3356 // the argument expression. Any difference in top-level
3357 // cv-qualification is subsumed by the initialization itself
3358 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003359 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3360 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003361 /*InOverloadResolution=*/false,
3362 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003363
3364 // Of course, that's still a reference binding.
3365 if (ICS.isStandard()) {
3366 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003367 ICS.Standard.IsLvalueReference = !isRValRef;
3368 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3369 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003370 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003371 } else if (ICS.isUserDefined()) {
3372 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003373 ICS.Standard.IsLvalueReference = !isRValRef;
3374 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3375 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003376 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003377 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003378
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003379 return ICS;
3380}
3381
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003382/// TryCopyInitialization - Try to copy-initialize a value of type
3383/// ToType from the expression From. Return the implicit conversion
3384/// sequence required to pass this argument, which may be a bad
3385/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003386/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003387/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003388static ImplicitConversionSequence
3389TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003391 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003392 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003393 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003394 /*FIXME:*/From->getLocStart(),
3395 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003396 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003397
John McCall5c32be02010-08-24 20:38:10 +00003398 return TryImplicitConversion(S, From, ToType,
3399 SuppressUserConversions,
3400 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003401 InOverloadResolution,
3402 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003403}
3404
Douglas Gregor436424c2008-11-18 23:14:02 +00003405/// TryObjectArgumentInitialization - Try to initialize the object
3406/// parameter of the given member function (@c Method) from the
3407/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003408static ImplicitConversionSequence
3409TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003410 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003411 CXXMethodDecl *Method,
3412 CXXRecordDecl *ActingContext) {
3413 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003414 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3415 // const volatile object.
3416 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3417 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003418 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003419
3420 // Set up the conversion sequence as a "bad" conversion, to allow us
3421 // to exit early.
3422 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003423
3424 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003425 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003426 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003427 FromType = PT->getPointeeType();
3428
Douglas Gregor02824322011-01-26 19:30:28 +00003429 // When we had a pointer, it's implicitly dereferenced, so we
3430 // better have an lvalue.
3431 assert(FromClassification.isLValue());
3432 }
3433
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003434 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003435
Douglas Gregor02824322011-01-26 19:30:28 +00003436 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003438 // parameter is
3439 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003440 // - "lvalue reference to cv X" for functions declared without a
3441 // ref-qualifier or with the & ref-qualifier
3442 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003443 // ref-qualifier
3444 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003446 // cv-qualification on the member function declaration.
3447 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003449 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003450 // (C++ [over.match.funcs]p5). We perform a simplified version of
3451 // reference binding here, that allows class rvalues to bind to
3452 // non-constant references.
3453
Douglas Gregor02824322011-01-26 19:30:28 +00003454 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003455 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003457 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003458 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003459 ICS.setBad(BadConversionSequence::bad_qualifiers,
3460 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003461 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003462 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003463
3464 // Check that we have either the same type or a derived type. It
3465 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003466 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003467 ImplicitConversionKind SecondKind;
3468 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3469 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003470 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003471 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003472 else {
John McCall65eb8792010-02-25 01:37:24 +00003473 ICS.setBad(BadConversionSequence::unrelated_class,
3474 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003475 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003476 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003477
Douglas Gregor02824322011-01-26 19:30:28 +00003478 // Check the ref-qualifier.
3479 switch (Method->getRefQualifier()) {
3480 case RQ_None:
3481 // Do nothing; we don't care about lvalueness or rvalueness.
3482 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregor02824322011-01-26 19:30:28 +00003484 case RQ_LValue:
3485 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3486 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003487 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003488 ImplicitParamType);
3489 return ICS;
3490 }
3491 break;
3492
3493 case RQ_RValue:
3494 if (!FromClassification.isRValue()) {
3495 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003497 ImplicitParamType);
3498 return ICS;
3499 }
3500 break;
3501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregor436424c2008-11-18 23:14:02 +00003503 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003504 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003505 ICS.Standard.setAsIdentityConversion();
3506 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003507 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003508 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003509 ICS.Standard.ReferenceBinding = true;
3510 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003512 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003513 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3514 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3515 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003516 return ICS;
3517}
3518
3519/// PerformObjectArgumentInitialization - Perform initialization of
3520/// the implicit object parameter for the given Method with the given
3521/// expression.
3522bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523Sema::PerformObjectArgumentInitialization(Expr *&From,
3524 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003525 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003526 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003527 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003528 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003529 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003530
Douglas Gregor02824322011-01-26 19:30:28 +00003531 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003532 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003533 FromRecordType = PT->getPointeeType();
3534 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003535 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003536 } else {
3537 FromRecordType = From->getType();
3538 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003539 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003540 }
3541
John McCall6e9f8f62009-12-03 04:06:58 +00003542 // Note that we always use the true parent context when performing
3543 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003544 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003545 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3546 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003547 if (ICS.isBad()) {
3548 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3549 Qualifiers FromQs = FromRecordType.getQualifiers();
3550 Qualifiers ToQs = DestType.getQualifiers();
3551 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3552 if (CVR) {
3553 Diag(From->getSourceRange().getBegin(),
3554 diag::err_member_function_call_bad_cvr)
3555 << Method->getDeclName() << FromRecordType << (CVR - 1)
3556 << From->getSourceRange();
3557 Diag(Method->getLocation(), diag::note_previous_decl)
3558 << Method->getDeclName();
3559 return true;
3560 }
3561 }
3562
Douglas Gregor436424c2008-11-18 23:14:02 +00003563 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003564 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003565 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003566 }
Mike Stump11289f42009-09-09 15:08:12 +00003567
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003568 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003569 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003570
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003571 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003572 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003573 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003574 return false;
3575}
3576
Douglas Gregor5fb53972009-01-14 15:45:31 +00003577/// TryContextuallyConvertToBool - Attempt to contextually convert the
3578/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003579static ImplicitConversionSequence
3580TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003581 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003582 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003583 // FIXME: Are these flags correct?
3584 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003585 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003586 /*InOverloadResolution=*/false,
3587 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003588}
3589
3590/// PerformContextuallyConvertToBool - Perform a contextual conversion
3591/// of the expression From to bool (C++0x [conv]p3).
3592bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003593 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003594 if (!ICS.isBad())
3595 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Fariborz Jahanian76197412009-11-18 18:26:29 +00003597 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003598 return Diag(From->getSourceRange().getBegin(),
3599 diag::err_typecheck_bool_condition)
3600 << From->getType() << From->getSourceRange();
3601 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003602}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003604/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3605/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003606static ImplicitConversionSequence
3607TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3608 QualType Ty = S.Context.getObjCIdType();
3609 return TryImplicitConversion(S, From, Ty,
3610 // FIXME: Are these flags correct?
3611 /*SuppressUserConversions=*/false,
3612 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003613 /*InOverloadResolution=*/false,
3614 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003615}
John McCall5c32be02010-08-24 20:38:10 +00003616
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003617/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3618/// of the expression From to 'id'.
3619bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003620 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003621 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003622 if (!ICS.isBad())
3623 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3624 return true;
3625}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003626
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003628/// enumeration type.
3629///
3630/// This routine will attempt to convert an expression of class type to an
3631/// integral or enumeration type, if that class type only has a single
3632/// conversion to an integral or enumeration type.
3633///
Douglas Gregor4799d032010-06-30 00:20:43 +00003634/// \param Loc The source location of the construct that requires the
3635/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003636///
Douglas Gregor4799d032010-06-30 00:20:43 +00003637/// \param FromE The expression we're converting from.
3638///
3639/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3640/// have integral or enumeration type.
3641///
3642/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3643/// incomplete class type.
3644///
3645/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3646/// explicit conversion function (because no implicit conversion functions
3647/// were available). This is a recovery mode.
3648///
3649/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3650/// showing which conversion was picked.
3651///
3652/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3653/// conversion function that could convert to integral or enumeration type.
3654///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003656/// usable conversion function.
3657///
3658/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3659/// function, which may be an extension in this case.
3660///
3661/// \returns The expression, converted to an integral or enumeration type if
3662/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663ExprResult
John McCallb268a282010-08-23 23:25:46 +00003664Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003665 const PartialDiagnostic &NotIntDiag,
3666 const PartialDiagnostic &IncompleteDiag,
3667 const PartialDiagnostic &ExplicitConvDiag,
3668 const PartialDiagnostic &ExplicitConvNote,
3669 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003670 const PartialDiagnostic &AmbigNote,
3671 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003672 // We can't perform any more checking for type-dependent expressions.
3673 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003674 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003676 // If the expression already has integral or enumeration type, we're golden.
3677 QualType T = From->getType();
3678 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003679 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003680
3681 // FIXME: Check for missing '()' if T is a function type?
3682
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003684 // expression of integral or enumeration type.
3685 const RecordType *RecordTy = T->getAs<RecordType>();
3686 if (!RecordTy || !getLangOptions().CPlusPlus) {
3687 Diag(Loc, NotIntDiag)
3688 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003689 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003692 // We must have a complete class type.
3693 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003694 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003695
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003696 // Look for a conversion to an integral or enumeration type.
3697 UnresolvedSet<4> ViableConversions;
3698 UnresolvedSet<4> ExplicitConversions;
3699 const UnresolvedSetImpl *Conversions
3700 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003702 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703 E = Conversions->end();
3704 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003705 ++I) {
3706 if (CXXConversionDecl *Conversion
3707 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3708 if (Conversion->getConversionType().getNonReferenceType()
3709 ->isIntegralOrEnumerationType()) {
3710 if (Conversion->isExplicit())
3711 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3712 else
3713 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3714 }
3715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003717 switch (ViableConversions.size()) {
3718 case 0:
3719 if (ExplicitConversions.size() == 1) {
3720 DeclAccessPair Found = ExplicitConversions[0];
3721 CXXConversionDecl *Conversion
3722 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003724 // The user probably meant to invoke the given explicit
3725 // conversion; use it.
3726 QualType ConvTy
3727 = Conversion->getConversionType().getNonReferenceType();
3728 std::string TypeStr;
3729 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003731 Diag(Loc, ExplicitConvDiag)
3732 << T << ConvTy
3733 << FixItHint::CreateInsertion(From->getLocStart(),
3734 "static_cast<" + TypeStr + ">(")
3735 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3736 ")");
3737 Diag(Conversion->getLocation(), ExplicitConvNote)
3738 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
3740 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003741 // explicit conversion function.
3742 if (isSFINAEContext())
3743 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003745 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003746 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3747 if (Result.isInvalid())
3748 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Douglas Gregor668443e2011-01-20 00:18:04 +00003750 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003753 // We'll complain below about a non-integral condition type.
3754 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003756 case 1: {
3757 // Apply this conversion.
3758 DeclAccessPair Found = ViableConversions[0];
3759 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760
Douglas Gregor4799d032010-06-30 00:20:43 +00003761 CXXConversionDecl *Conversion
3762 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3763 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00003765 if (ConvDiag.getDiagID()) {
3766 if (isSFINAEContext())
3767 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768
Douglas Gregor4799d032010-06-30 00:20:43 +00003769 Diag(Loc, ConvDiag)
3770 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772
Douglas Gregor668443e2011-01-20 00:18:04 +00003773 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003774 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003775 if (Result.isInvalid())
3776 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777
Douglas Gregor668443e2011-01-20 00:18:04 +00003778 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003779 break;
3780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003781
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003782 default:
3783 Diag(Loc, AmbigDiag)
3784 << T << From->getSourceRange();
3785 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3786 CXXConversionDecl *Conv
3787 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3788 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3789 Diag(Conv->getLocation(), AmbigNote)
3790 << ConvTy->isEnumeralType() << ConvTy;
3791 }
John McCallb268a282010-08-23 23:25:46 +00003792 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794
Douglas Gregor5823da32010-06-29 23:25:20 +00003795 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003796 Diag(Loc, NotIntDiag)
3797 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003798
John McCallb268a282010-08-23 23:25:46 +00003799 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003800}
3801
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003802/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003803/// candidate functions, using the given function call arguments. If
3804/// @p SuppressUserConversions, then don't allow user-defined
3805/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003806///
3807/// \para PartialOverloading true if we are performing "partial" overloading
3808/// based on an incomplete set of function arguments. This feature is used by
3809/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003810void
3811Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003812 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003813 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003814 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003815 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003816 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003817 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003818 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003819 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003820 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003821 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003822
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003823 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003824 if (!isa<CXXConstructorDecl>(Method)) {
3825 // If we get here, it's because we're calling a member function
3826 // that is named without a member access expression (e.g.,
3827 // "this->f") that was either written explicitly or created
3828 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003829 // function, e.g., X::f(). We use an empty type for the implied
3830 // object argument (C++ [over.call.func]p3), and the acting context
3831 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003832 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00003834 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003835 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003836 return;
3837 }
3838 // We treat a constructor like a non-member function, since its object
3839 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003840 }
3841
Douglas Gregorff7028a2009-11-13 23:59:09 +00003842 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003843 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003844
Douglas Gregor27381f32009-11-23 12:27:39 +00003845 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003846 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003847
Douglas Gregorffe14e32009-11-14 01:20:54 +00003848 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3849 // C++ [class.copy]p3:
3850 // A member function template is never instantiated to perform the copy
3851 // of a class object to an object of its class type.
3852 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003853 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003854 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003855 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3856 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003857 return;
3858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003859
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003860 // Add this candidate
3861 CandidateSet.push_back(OverloadCandidate());
3862 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003863 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003864 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003865 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003866 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003867 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003868 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003870 unsigned NumArgsInProto = Proto->getNumArgs();
3871
3872 // (C++ 13.3.2p2): A candidate function having fewer than m
3873 // parameters is viable only if it has an ellipsis in its parameter
3874 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003875 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00003876 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003877 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003878 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003879 return;
3880 }
3881
3882 // (C++ 13.3.2p2): A candidate function having more than m parameters
3883 // is viable only if the (m+1)st parameter has a default argument
3884 // (8.3.6). For the purposes of overload resolution, the
3885 // parameter list is truncated on the right, so that there are
3886 // exactly m parameters.
3887 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003888 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003889 // Not enough arguments.
3890 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003891 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003892 return;
3893 }
3894
3895 // Determine the implicit conversion sequences for each of the
3896 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003897 Candidate.Conversions.resize(NumArgs);
3898 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3899 if (ArgIdx < NumArgsInProto) {
3900 // (C++ 13.3.2p3): for F to be a viable function, there shall
3901 // exist for each argument an implicit conversion sequence
3902 // (13.3.3.1) that converts that argument to the corresponding
3903 // parameter of F.
3904 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003905 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003906 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003908 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003909 if (Candidate.Conversions[ArgIdx].isBad()) {
3910 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003911 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003912 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003913 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003914 } else {
3915 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3916 // argument for which there is no corresponding parameter is
3917 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003918 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003919 }
3920 }
3921}
3922
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003923/// \brief Add all of the function declarations in the given function set to
3924/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003925void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003926 Expr **Args, unsigned NumArgs,
3927 OverloadCandidateSet& CandidateSet,
3928 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003929 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003930 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003932 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003933 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003934 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003935 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003936 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003937 CandidateSet, SuppressUserConversions);
3938 else
John McCalla0296f72010-03-19 07:35:19 +00003939 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003940 SuppressUserConversions);
3941 } else {
John McCalla0296f72010-03-19 07:35:19 +00003942 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003943 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3944 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003945 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003946 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003947 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00003949 Args[0]->Classify(Context),
3950 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003951 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003952 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003953 else
John McCalla0296f72010-03-19 07:35:19 +00003954 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003955 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003956 Args, NumArgs, CandidateSet,
3957 SuppressUserConversions);
3958 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003959 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003960}
3961
John McCallf0f1cf02009-11-17 07:50:12 +00003962/// AddMethodCandidate - Adds a named decl (which is some kind of
3963/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003964void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003965 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003966 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00003967 Expr **Args, unsigned NumArgs,
3968 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003969 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003970 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003971 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003972
3973 if (isa<UsingShadowDecl>(Decl))
3974 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003975
John McCallf0f1cf02009-11-17 07:50:12 +00003976 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3977 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3978 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003979 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3980 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003981 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003982 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003983 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003984 } else {
John McCalla0296f72010-03-19 07:35:19 +00003985 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00003986 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003987 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003988 }
3989}
3990
Douglas Gregor436424c2008-11-18 23:14:02 +00003991/// AddMethodCandidate - Adds the given C++ member function to the set
3992/// of candidate functions, using the given function call arguments
3993/// and the object argument (@c Object). For example, in a call
3994/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3995/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3996/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003997/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003998void
John McCalla0296f72010-03-19 07:35:19 +00003999Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004000 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004001 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004002 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004003 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004004 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004005 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004006 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004007 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004008 assert(!isa<CXXConstructorDecl>(Method) &&
4009 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004010
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004011 if (!CandidateSet.isNewCandidate(Method))
4012 return;
4013
Douglas Gregor27381f32009-11-23 12:27:39 +00004014 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004015 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004016
Douglas Gregor436424c2008-11-18 23:14:02 +00004017 // Add this candidate
4018 CandidateSet.push_back(OverloadCandidate());
4019 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004020 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004021 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004022 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004023 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004024 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004025
4026 unsigned NumArgsInProto = Proto->getNumArgs();
4027
4028 // (C++ 13.3.2p2): A candidate function having fewer than m
4029 // parameters is viable only if it has an ellipsis in its parameter
4030 // list (8.3.5).
4031 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4032 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004033 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004034 return;
4035 }
4036
4037 // (C++ 13.3.2p2): A candidate function having more than m parameters
4038 // is viable only if the (m+1)st parameter has a default argument
4039 // (8.3.6). For the purposes of overload resolution, the
4040 // parameter list is truncated on the right, so that there are
4041 // exactly m parameters.
4042 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4043 if (NumArgs < MinRequiredArgs) {
4044 // Not enough arguments.
4045 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004046 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004047 return;
4048 }
4049
4050 Candidate.Viable = true;
4051 Candidate.Conversions.resize(NumArgs + 1);
4052
John McCall6e9f8f62009-12-03 04:06:58 +00004053 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004054 // The implicit object argument is ignored.
4055 Candidate.IgnoreObjectArgument = true;
4056 else {
4057 // Determine the implicit conversion sequence for the object
4058 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004059 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004060 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4061 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004062 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004063 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004064 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004065 return;
4066 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004067 }
4068
4069 // Determine the implicit conversion sequences for each of the
4070 // arguments.
4071 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4072 if (ArgIdx < NumArgsInProto) {
4073 // (C++ 13.3.2p3): for F to be a viable function, there shall
4074 // exist for each argument an implicit conversion sequence
4075 // (13.3.3.1) that converts that argument to the corresponding
4076 // parameter of F.
4077 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004078 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004079 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00004081 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00004082 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004083 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004084 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004085 break;
4086 }
4087 } else {
4088 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4089 // argument for which there is no corresponding parameter is
4090 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004091 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004092 }
4093 }
4094}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095
Douglas Gregor97628d62009-08-21 00:16:32 +00004096/// \brief Add a C++ member function template as a candidate to the candidate
4097/// set, using template argument deduction to produce an appropriate member
4098/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004099void
Douglas Gregor97628d62009-08-21 00:16:32 +00004100Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004101 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004102 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004103 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004104 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004105 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004106 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004107 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004108 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004109 if (!CandidateSet.isNewCandidate(MethodTmpl))
4110 return;
4111
Douglas Gregor97628d62009-08-21 00:16:32 +00004112 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004113 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004114 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004115 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004116 // candidate functions in the usual way.113) A given name can refer to one
4117 // or more function templates and also to a set of overloaded non-template
4118 // functions. In such a case, the candidate functions generated from each
4119 // function template are combined with the set of non-template candidate
4120 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004121 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004122 FunctionDecl *Specialization = 0;
4123 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004124 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004125 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004126 CandidateSet.push_back(OverloadCandidate());
4127 OverloadCandidate &Candidate = CandidateSet.back();
4128 Candidate.FoundDecl = FoundDecl;
4129 Candidate.Function = MethodTmpl->getTemplatedDecl();
4130 Candidate.Viable = false;
4131 Candidate.FailureKind = ovl_fail_bad_deduction;
4132 Candidate.IsSurrogate = false;
4133 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004134 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004135 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004136 Info);
4137 return;
4138 }
Mike Stump11289f42009-09-09 15:08:12 +00004139
Douglas Gregor97628d62009-08-21 00:16:32 +00004140 // Add the function template specialization produced by template argument
4141 // deduction as a candidate.
4142 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004143 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004144 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004145 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004146 ActingContext, ObjectType, ObjectClassification,
4147 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004148}
4149
Douglas Gregor05155d82009-08-21 23:19:43 +00004150/// \brief Add a C++ function template specialization as a candidate
4151/// in the candidate set, using template argument deduction to produce
4152/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004153void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004154Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004155 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004156 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004157 Expr **Args, unsigned NumArgs,
4158 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004159 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004160 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4161 return;
4162
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004163 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004164 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004165 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004166 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004167 // candidate functions in the usual way.113) A given name can refer to one
4168 // or more function templates and also to a set of overloaded non-template
4169 // functions. In such a case, the candidate functions generated from each
4170 // function template are combined with the set of non-template candidate
4171 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004172 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004173 FunctionDecl *Specialization = 0;
4174 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004175 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004176 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004177 CandidateSet.push_back(OverloadCandidate());
4178 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004179 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004180 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4181 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004182 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004183 Candidate.IsSurrogate = false;
4184 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004185 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004187 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004188 return;
4189 }
Mike Stump11289f42009-09-09 15:08:12 +00004190
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004191 // Add the function template specialization produced by template argument
4192 // deduction as a candidate.
4193 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004194 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004195 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004196}
Mike Stump11289f42009-09-09 15:08:12 +00004197
Douglas Gregora1f013e2008-11-07 22:36:19 +00004198/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004199/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004200/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004201/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004202/// (which may or may not be the same type as the type that the
4203/// conversion function produces).
4204void
4205Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004206 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004207 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004208 Expr *From, QualType ToType,
4209 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004210 assert(!Conversion->getDescribedFunctionTemplate() &&
4211 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004212 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004213 if (!CandidateSet.isNewCandidate(Conversion))
4214 return;
4215
Douglas Gregor27381f32009-11-23 12:27:39 +00004216 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004217 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004218
Douglas Gregora1f013e2008-11-07 22:36:19 +00004219 // Add this candidate
4220 CandidateSet.push_back(OverloadCandidate());
4221 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004222 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004223 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004224 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004225 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004226 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004227 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004228 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004229 Candidate.Viable = true;
4230 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004231 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004232
Douglas Gregor6affc782010-08-19 15:37:02 +00004233 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234 // For conversion functions, the function is considered to be a member of
4235 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004236 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004237 //
4238 // Determine the implicit conversion sequence for the implicit
4239 // object parameter.
4240 QualType ImplicitParamType = From->getType();
4241 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4242 ImplicitParamType = FromPtrType->getPointeeType();
4243 CXXRecordDecl *ConversionContext
4244 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004246 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247 = TryObjectArgumentInitialization(*this, From->getType(),
4248 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004249 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250
John McCall0d1da222010-01-12 00:44:57 +00004251 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004252 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004253 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004254 return;
4255 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004256
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004258 // derived to base as such conversions are given Conversion Rank. They only
4259 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4260 QualType FromCanon
4261 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4262 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4263 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4264 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004265 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004266 return;
4267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregora1f013e2008-11-07 22:36:19 +00004269 // To determine what the conversion from the result of calling the
4270 // conversion function to the type we're eventually trying to
4271 // convert to (ToType), we need to synthesize a call to the
4272 // conversion function and attempt copy initialization from it. This
4273 // makes sure that we get the right semantics with respect to
4274 // lvalues/rvalues and the type. Fortunately, we can allocate this
4275 // call on the stack and we don't need its arguments to be
4276 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004277 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004278 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004279 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4280 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004281 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004282 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004283
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004284 QualType CallResultType
4285 = Conversion->getConversionType().getNonLValueExprType(Context);
4286 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4287 Candidate.Viable = false;
4288 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4289 return;
4290 }
4291
John McCall7decc9e2010-11-18 06:31:45 +00004292 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4293
Mike Stump11289f42009-09-09 15:08:12 +00004294 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004295 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4296 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004297 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004298 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004299 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004300 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004301 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004302 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004303
John McCall0d1da222010-01-12 00:44:57 +00004304 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004305 case ImplicitConversionSequence::StandardConversion:
4306 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004308 // C++ [over.ics.user]p3:
4309 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004311 // shall have exact match rank.
4312 if (Conversion->getPrimaryTemplate() &&
4313 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4314 Candidate.Viable = false;
4315 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317
Douglas Gregorcba72b12011-01-21 05:18:22 +00004318 // C++0x [dcl.init.ref]p5:
4319 // In the second case, if the reference is an rvalue reference and
4320 // the second standard conversion sequence of the user-defined
4321 // conversion sequence includes an lvalue-to-rvalue conversion, the
4322 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004324 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4325 Candidate.Viable = false;
4326 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4327 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004328 break;
4329
4330 case ImplicitConversionSequence::BadConversion:
4331 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004332 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004333 break;
4334
4335 default:
Mike Stump11289f42009-09-09 15:08:12 +00004336 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004337 "Can only end up with a standard conversion sequence or failure");
4338 }
4339}
4340
Douglas Gregor05155d82009-08-21 23:19:43 +00004341/// \brief Adds a conversion function template specialization
4342/// candidate to the overload set, using template argument deduction
4343/// to deduce the template arguments of the conversion function
4344/// template from the type that we are converting to (C++
4345/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004346void
Douglas Gregor05155d82009-08-21 23:19:43 +00004347Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004348 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004349 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004350 Expr *From, QualType ToType,
4351 OverloadCandidateSet &CandidateSet) {
4352 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4353 "Only conversion function templates permitted here");
4354
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004355 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4356 return;
4357
John McCallbc077cf2010-02-08 23:07:23 +00004358 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004359 CXXConversionDecl *Specialization = 0;
4360 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004361 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004362 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004363 CandidateSet.push_back(OverloadCandidate());
4364 OverloadCandidate &Candidate = CandidateSet.back();
4365 Candidate.FoundDecl = FoundDecl;
4366 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4367 Candidate.Viable = false;
4368 Candidate.FailureKind = ovl_fail_bad_deduction;
4369 Candidate.IsSurrogate = false;
4370 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004371 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004373 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004374 return;
4375 }
Mike Stump11289f42009-09-09 15:08:12 +00004376
Douglas Gregor05155d82009-08-21 23:19:43 +00004377 // Add the conversion function template specialization produced by
4378 // template argument deduction as a candidate.
4379 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004380 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004381 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004382}
4383
Douglas Gregorab7897a2008-11-19 22:57:39 +00004384/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4385/// converts the given @c Object to a function pointer via the
4386/// conversion function @c Conversion, and then attempts to call it
4387/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4388/// the type of function that we'll eventually be calling.
4389void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004390 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004391 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004392 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004393 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004394 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004395 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004396 if (!CandidateSet.isNewCandidate(Conversion))
4397 return;
4398
Douglas Gregor27381f32009-11-23 12:27:39 +00004399 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004400 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004401
Douglas Gregorab7897a2008-11-19 22:57:39 +00004402 CandidateSet.push_back(OverloadCandidate());
4403 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004404 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004405 Candidate.Function = 0;
4406 Candidate.Surrogate = Conversion;
4407 Candidate.Viable = true;
4408 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004409 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004410 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004411 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004412
4413 // Determine the implicit conversion sequence for the implicit
4414 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004415 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004417 Object->Classify(Context),
4418 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004419 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004420 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004421 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004422 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004423 return;
4424 }
4425
4426 // The first conversion is actually a user-defined conversion whose
4427 // first conversion is ObjectInit's standard conversion (which is
4428 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004429 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004430 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004431 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004432 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004434 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004435 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004436 = Candidate.Conversions[0].UserDefined.Before;
4437 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4438
Mike Stump11289f42009-09-09 15:08:12 +00004439 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004440 unsigned NumArgsInProto = Proto->getNumArgs();
4441
4442 // (C++ 13.3.2p2): A candidate function having fewer than m
4443 // parameters is viable only if it has an ellipsis in its parameter
4444 // list (8.3.5).
4445 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4446 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004447 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004448 return;
4449 }
4450
4451 // Function types don't have any default arguments, so just check if
4452 // we have enough arguments.
4453 if (NumArgs < NumArgsInProto) {
4454 // Not enough arguments.
4455 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004456 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004457 return;
4458 }
4459
4460 // Determine the implicit conversion sequences for each of the
4461 // arguments.
4462 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4463 if (ArgIdx < NumArgsInProto) {
4464 // (C++ 13.3.2p3): for F to be a viable function, there shall
4465 // exist for each argument an implicit conversion sequence
4466 // (13.3.3.1) that converts that argument to the corresponding
4467 // parameter of F.
4468 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004469 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004470 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004471 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004472 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004473 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004474 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004475 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004476 break;
4477 }
4478 } else {
4479 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4480 // argument for which there is no corresponding parameter is
4481 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004482 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004483 }
4484 }
4485}
4486
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004487/// \brief Add overload candidates for overloaded operators that are
4488/// member functions.
4489///
4490/// Add the overloaded operator candidates that are member functions
4491/// for the operator Op that was used in an operator expression such
4492/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4493/// CandidateSet will store the added overload candidates. (C++
4494/// [over.match.oper]).
4495void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4496 SourceLocation OpLoc,
4497 Expr **Args, unsigned NumArgs,
4498 OverloadCandidateSet& CandidateSet,
4499 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004500 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4501
4502 // C++ [over.match.oper]p3:
4503 // For a unary operator @ with an operand of a type whose
4504 // cv-unqualified version is T1, and for a binary operator @ with
4505 // a left operand of a type whose cv-unqualified version is T1 and
4506 // a right operand of a type whose cv-unqualified version is T2,
4507 // three sets of candidate functions, designated member
4508 // candidates, non-member candidates and built-in candidates, are
4509 // constructed as follows:
4510 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004511
4512 // -- If T1 is a class type, the set of member candidates is the
4513 // result of the qualified lookup of T1::operator@
4514 // (13.3.1.1.1); otherwise, the set of member candidates is
4515 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004516 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004517 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004518 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004519 return;
Mike Stump11289f42009-09-09 15:08:12 +00004520
John McCall27b18f82009-11-17 02:14:36 +00004521 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4522 LookupQualifiedName(Operators, T1Rec->getDecl());
4523 Operators.suppressDiagnostics();
4524
Mike Stump11289f42009-09-09 15:08:12 +00004525 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004526 OperEnd = Operators.end();
4527 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004528 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004529 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004531 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004532 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004533 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004534}
4535
Douglas Gregora11693b2008-11-12 17:17:38 +00004536/// AddBuiltinCandidate - Add a candidate for a built-in
4537/// operator. ResultTy and ParamTys are the result and parameter types
4538/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004539/// arguments being passed to the candidate. IsAssignmentOperator
4540/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004541/// operator. NumContextualBoolArguments is the number of arguments
4542/// (at the beginning of the argument list) that will be contextually
4543/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004544void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004545 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004546 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004547 bool IsAssignmentOperator,
4548 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004549 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004550 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004551
Douglas Gregora11693b2008-11-12 17:17:38 +00004552 // Add this candidate
4553 CandidateSet.push_back(OverloadCandidate());
4554 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004555 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004556 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004557 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004558 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004559 Candidate.BuiltinTypes.ResultTy = ResultTy;
4560 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4561 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4562
4563 // Determine the implicit conversion sequences for each of the
4564 // arguments.
4565 Candidate.Viable = true;
4566 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004567 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004568 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004569 // C++ [over.match.oper]p4:
4570 // For the built-in assignment operators, conversions of the
4571 // left operand are restricted as follows:
4572 // -- no temporaries are introduced to hold the left operand, and
4573 // -- no user-defined conversions are applied to the left
4574 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004575 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004576 //
4577 // We block these conversions by turning off user-defined
4578 // conversions, since that is the only way that initialization of
4579 // a reference to a non-class type can occur from something that
4580 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004581 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004582 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004583 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004584 Candidate.Conversions[ArgIdx]
4585 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004586 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004587 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004588 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004589 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004590 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004591 }
John McCall0d1da222010-01-12 00:44:57 +00004592 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004593 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004594 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004595 break;
4596 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004597 }
4598}
4599
4600/// BuiltinCandidateTypeSet - A set of types that will be used for the
4601/// candidate operator functions for built-in operators (C++
4602/// [over.built]). The types are separated into pointer types and
4603/// enumeration types.
4604class BuiltinCandidateTypeSet {
4605 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004606 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004607
4608 /// PointerTypes - The set of pointer types that will be used in the
4609 /// built-in candidates.
4610 TypeSet PointerTypes;
4611
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004612 /// MemberPointerTypes - The set of member pointer types that will be
4613 /// used in the built-in candidates.
4614 TypeSet MemberPointerTypes;
4615
Douglas Gregora11693b2008-11-12 17:17:38 +00004616 /// EnumerationTypes - The set of enumeration types that will be
4617 /// used in the built-in candidates.
4618 TypeSet EnumerationTypes;
4619
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004620 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004621 /// candidates.
4622 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004623
4624 /// \brief A flag indicating non-record types are viable candidates
4625 bool HasNonRecordTypes;
4626
4627 /// \brief A flag indicating whether either arithmetic or enumeration types
4628 /// were present in the candidate set.
4629 bool HasArithmeticOrEnumeralTypes;
4630
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004631 /// Sema - The semantic analysis instance where we are building the
4632 /// candidate type set.
4633 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004634
Douglas Gregora11693b2008-11-12 17:17:38 +00004635 /// Context - The AST context in which we will build the type sets.
4636 ASTContext &Context;
4637
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004638 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4639 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004640 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004641
4642public:
4643 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004644 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004645
Mike Stump11289f42009-09-09 15:08:12 +00004646 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004647 : HasNonRecordTypes(false),
4648 HasArithmeticOrEnumeralTypes(false),
4649 SemaRef(SemaRef),
4650 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004651
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004652 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004653 SourceLocation Loc,
4654 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004655 bool AllowExplicitConversions,
4656 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004657
4658 /// pointer_begin - First pointer type found;
4659 iterator pointer_begin() { return PointerTypes.begin(); }
4660
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004661 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004662 iterator pointer_end() { return PointerTypes.end(); }
4663
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004664 /// member_pointer_begin - First member pointer type found;
4665 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4666
4667 /// member_pointer_end - Past the last member pointer type found;
4668 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4669
Douglas Gregora11693b2008-11-12 17:17:38 +00004670 /// enumeration_begin - First enumeration type found;
4671 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4672
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004673 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004674 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004675
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004676 iterator vector_begin() { return VectorTypes.begin(); }
4677 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004678
4679 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4680 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004681};
4682
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004683/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004684/// the set of pointer types along with any more-qualified variants of
4685/// that type. For example, if @p Ty is "int const *", this routine
4686/// will add "int const *", "int const volatile *", "int const
4687/// restrict *", and "int const volatile restrict *" to the set of
4688/// pointer types. Returns true if the add of @p Ty itself succeeded,
4689/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004690///
4691/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004692bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004693BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4694 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004695
Douglas Gregora11693b2008-11-12 17:17:38 +00004696 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004697 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004698 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004699
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004700 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004701 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004702 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004703 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004704 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004705 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004706 buildObjCPtr = true;
4707 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004708 else
4709 assert(false && "type was not a pointer type!");
4710 }
4711 else
4712 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
Sebastian Redl4990a632009-11-18 20:39:26 +00004714 // Don't add qualified variants of arrays. For one, they're not allowed
4715 // (the qualifier would sink to the element type), and for another, the
4716 // only overload situation where it matters is subscript or pointer +- int,
4717 // and those shouldn't have qualifier variants anyway.
4718 if (PointeeTy->isArrayType())
4719 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004720 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004721 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004722 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004723 bool hasVolatile = VisibleQuals.hasVolatile();
4724 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725
John McCall8ccfcb52009-09-24 19:53:00 +00004726 // Iterate through all strict supersets of BaseCVR.
4727 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4728 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004729 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4730 // in the types.
4731 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4732 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004733 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004734 if (!buildObjCPtr)
4735 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4736 else
4737 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004738 }
4739
4740 return true;
4741}
4742
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004743/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4744/// to the set of pointer types along with any more-qualified variants of
4745/// that type. For example, if @p Ty is "int const *", this routine
4746/// will add "int const *", "int const volatile *", "int const
4747/// restrict *", and "int const volatile restrict *" to the set of
4748/// pointer types. Returns true if the add of @p Ty itself succeeded,
4749/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004750///
4751/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004752bool
4753BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4754 QualType Ty) {
4755 // Insert this type.
4756 if (!MemberPointerTypes.insert(Ty))
4757 return false;
4758
John McCall8ccfcb52009-09-24 19:53:00 +00004759 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4760 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004761
John McCall8ccfcb52009-09-24 19:53:00 +00004762 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004763 // Don't add qualified variants of arrays. For one, they're not allowed
4764 // (the qualifier would sink to the element type), and for another, the
4765 // only overload situation where it matters is subscript or pointer +- int,
4766 // and those shouldn't have qualifier variants anyway.
4767 if (PointeeTy->isArrayType())
4768 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004769 const Type *ClassTy = PointerTy->getClass();
4770
4771 // Iterate through all strict supersets of the pointee type's CVR
4772 // qualifiers.
4773 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4774 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4775 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776
John McCall8ccfcb52009-09-24 19:53:00 +00004777 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004778 MemberPointerTypes.insert(
4779 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004780 }
4781
4782 return true;
4783}
4784
Douglas Gregora11693b2008-11-12 17:17:38 +00004785/// AddTypesConvertedFrom - Add each of the types to which the type @p
4786/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004787/// primarily interested in pointer types and enumeration types. We also
4788/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004789/// AllowUserConversions is true if we should look at the conversion
4790/// functions of a class type, and AllowExplicitConversions if we
4791/// should also include the explicit conversion functions of a class
4792/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004793void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004794BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004795 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004796 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004797 bool AllowExplicitConversions,
4798 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004799 // Only deal with canonical types.
4800 Ty = Context.getCanonicalType(Ty);
4801
4802 // Look through reference types; they aren't part of the type of an
4803 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004804 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004805 Ty = RefTy->getPointeeType();
4806
John McCall33ddac02011-01-19 10:06:00 +00004807 // If we're dealing with an array type, decay to the pointer.
4808 if (Ty->isArrayType())
4809 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4810
4811 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004812 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004813
Chandler Carruth00a38332010-12-13 01:44:01 +00004814 // Flag if we ever add a non-record type.
4815 const RecordType *TyRec = Ty->getAs<RecordType>();
4816 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4817
Chandler Carruth00a38332010-12-13 01:44:01 +00004818 // Flag if we encounter an arithmetic type.
4819 HasArithmeticOrEnumeralTypes =
4820 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4821
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004822 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4823 PointerTypes.insert(Ty);
4824 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004825 // Insert our type, and its more-qualified variants, into the set
4826 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004827 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004828 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004829 } else if (Ty->isMemberPointerType()) {
4830 // Member pointers are far easier, since the pointee can't be converted.
4831 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4832 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004833 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004834 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004835 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004836 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004837 // We treat vector types as arithmetic types in many contexts as an
4838 // extension.
4839 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004840 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004841 } else if (AllowUserConversions && TyRec) {
4842 // No conversion functions in incomplete types.
4843 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4844 return;
Mike Stump11289f42009-09-09 15:08:12 +00004845
Chandler Carruth00a38332010-12-13 01:44:01 +00004846 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4847 const UnresolvedSetImpl *Conversions
4848 = ClassDecl->getVisibleConversionFunctions();
4849 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4850 E = Conversions->end(); I != E; ++I) {
4851 NamedDecl *D = I.getDecl();
4852 if (isa<UsingShadowDecl>(D))
4853 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004854
Chandler Carruth00a38332010-12-13 01:44:01 +00004855 // Skip conversion function templates; they don't tell us anything
4856 // about which builtin types we can convert to.
4857 if (isa<FunctionTemplateDecl>(D))
4858 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004859
Chandler Carruth00a38332010-12-13 01:44:01 +00004860 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4861 if (AllowExplicitConversions || !Conv->isExplicit()) {
4862 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4863 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004864 }
4865 }
4866 }
4867}
4868
Douglas Gregor84605ae2009-08-24 13:43:27 +00004869/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4870/// the volatile- and non-volatile-qualified assignment operators for the
4871/// given type to the candidate set.
4872static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4873 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004874 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004875 unsigned NumArgs,
4876 OverloadCandidateSet &CandidateSet) {
4877 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004878
Douglas Gregor84605ae2009-08-24 13:43:27 +00004879 // T& operator=(T&, T)
4880 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4881 ParamTypes[1] = T;
4882 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4883 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004884
Douglas Gregor84605ae2009-08-24 13:43:27 +00004885 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4886 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004887 ParamTypes[0]
4888 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004889 ParamTypes[1] = T;
4890 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004891 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004892 }
4893}
Mike Stump11289f42009-09-09 15:08:12 +00004894
Sebastian Redl1054fae2009-10-25 17:03:50 +00004895/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4896/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004897static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4898 Qualifiers VRQuals;
4899 const RecordType *TyRec;
4900 if (const MemberPointerType *RHSMPType =
4901 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004902 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004903 else
4904 TyRec = ArgExpr->getType()->getAs<RecordType>();
4905 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004906 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004907 VRQuals.addVolatile();
4908 VRQuals.addRestrict();
4909 return VRQuals;
4910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004912 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004913 if (!ClassDecl->hasDefinition())
4914 return VRQuals;
4915
John McCallad371252010-01-20 00:46:10 +00004916 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004917 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918
John McCallad371252010-01-20 00:46:10 +00004919 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004920 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004921 NamedDecl *D = I.getDecl();
4922 if (isa<UsingShadowDecl>(D))
4923 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4924 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004925 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4926 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4927 CanTy = ResTypeRef->getPointeeType();
4928 // Need to go down the pointer/mempointer chain and add qualifiers
4929 // as see them.
4930 bool done = false;
4931 while (!done) {
4932 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4933 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004934 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004935 CanTy->getAs<MemberPointerType>())
4936 CanTy = ResTypeMPtr->getPointeeType();
4937 else
4938 done = true;
4939 if (CanTy.isVolatileQualified())
4940 VRQuals.addVolatile();
4941 if (CanTy.isRestrictQualified())
4942 VRQuals.addRestrict();
4943 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4944 return VRQuals;
4945 }
4946 }
4947 }
4948 return VRQuals;
4949}
John McCall52872982010-11-13 05:51:15 +00004950
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004951namespace {
John McCall52872982010-11-13 05:51:15 +00004952
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004953/// \brief Helper class to manage the addition of builtin operator overload
4954/// candidates. It provides shared state and utility methods used throughout
4955/// the process, as well as a helper method to add each group of builtin
4956/// operator overloads from the standard to a candidate set.
4957class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004958 // Common instance state available to all overload candidate addition methods.
4959 Sema &S;
4960 Expr **Args;
4961 unsigned NumArgs;
4962 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004963 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004964 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4965 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004966
Chandler Carruthc6586e52010-12-12 10:35:00 +00004967 // Define some constants used to index and iterate over the arithemetic types
4968 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004969 // The "promoted arithmetic types" are the arithmetic
4970 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004971 static const unsigned FirstIntegralType = 3;
4972 static const unsigned LastIntegralType = 18;
4973 static const unsigned FirstPromotedIntegralType = 3,
4974 LastPromotedIntegralType = 9;
4975 static const unsigned FirstPromotedArithmeticType = 0,
4976 LastPromotedArithmeticType = 9;
4977 static const unsigned NumArithmeticTypes = 18;
4978
Chandler Carruthc6586e52010-12-12 10:35:00 +00004979 /// \brief Get the canonical type for a given arithmetic type index.
4980 CanQualType getArithmeticType(unsigned index) {
4981 assert(index < NumArithmeticTypes);
4982 static CanQualType ASTContext::* const
4983 ArithmeticTypes[NumArithmeticTypes] = {
4984 // Start of promoted types.
4985 &ASTContext::FloatTy,
4986 &ASTContext::DoubleTy,
4987 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004988
Chandler Carruthc6586e52010-12-12 10:35:00 +00004989 // Start of integral types.
4990 &ASTContext::IntTy,
4991 &ASTContext::LongTy,
4992 &ASTContext::LongLongTy,
4993 &ASTContext::UnsignedIntTy,
4994 &ASTContext::UnsignedLongTy,
4995 &ASTContext::UnsignedLongLongTy,
4996 // End of promoted types.
4997
4998 &ASTContext::BoolTy,
4999 &ASTContext::CharTy,
5000 &ASTContext::WCharTy,
5001 &ASTContext::Char16Ty,
5002 &ASTContext::Char32Ty,
5003 &ASTContext::SignedCharTy,
5004 &ASTContext::ShortTy,
5005 &ASTContext::UnsignedCharTy,
5006 &ASTContext::UnsignedShortTy,
5007 // End of integral types.
5008 // FIXME: What about complex?
5009 };
5010 return S.Context.*ArithmeticTypes[index];
5011 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005012
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005013 /// \brief Gets the canonical type resulting from the usual arithemetic
5014 /// converions for the given arithmetic types.
5015 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5016 // Accelerator table for performing the usual arithmetic conversions.
5017 // The rules are basically:
5018 // - if either is floating-point, use the wider floating-point
5019 // - if same signedness, use the higher rank
5020 // - if same size, use unsigned of the higher rank
5021 // - use the larger type
5022 // These rules, together with the axiom that higher ranks are
5023 // never smaller, are sufficient to precompute all of these results
5024 // *except* when dealing with signed types of higher rank.
5025 // (we could precompute SLL x UI for all known platforms, but it's
5026 // better not to make any assumptions).
5027 enum PromotedType {
5028 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5029 };
5030 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5031 [LastPromotedArithmeticType] = {
5032 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5033 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5034 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5035 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5036 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5037 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5038 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5039 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5040 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5041 };
5042
5043 assert(L < LastPromotedArithmeticType);
5044 assert(R < LastPromotedArithmeticType);
5045 int Idx = ConversionsTable[L][R];
5046
5047 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005048 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005049
5050 // Slow path: we need to compare widths.
5051 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005052 CanQualType LT = getArithmeticType(L),
5053 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005054 unsigned LW = S.Context.getIntWidth(LT),
5055 RW = S.Context.getIntWidth(RT);
5056
5057 // If they're different widths, use the signed type.
5058 if (LW > RW) return LT;
5059 else if (LW < RW) return RT;
5060
5061 // Otherwise, use the unsigned type of the signed type's rank.
5062 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5063 assert(L == SLL || R == SLL);
5064 return S.Context.UnsignedLongLongTy;
5065 }
5066
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005067 /// \brief Helper method to factor out the common pattern of adding overloads
5068 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005069 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5070 bool HasVolatile) {
5071 QualType ParamTypes[2] = {
5072 S.Context.getLValueReferenceType(CandidateTy),
5073 S.Context.IntTy
5074 };
5075
5076 // Non-volatile version.
5077 if (NumArgs == 1)
5078 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5079 else
5080 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5081
5082 // Use a heuristic to reduce number of builtin candidates in the set:
5083 // add volatile version only if there are conversions to a volatile type.
5084 if (HasVolatile) {
5085 ParamTypes[0] =
5086 S.Context.getLValueReferenceType(
5087 S.Context.getVolatileType(CandidateTy));
5088 if (NumArgs == 1)
5089 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5090 else
5091 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5092 }
5093 }
5094
5095public:
5096 BuiltinOperatorOverloadBuilder(
5097 Sema &S, Expr **Args, unsigned NumArgs,
5098 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005099 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005100 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5101 OverloadCandidateSet &CandidateSet)
5102 : S(S), Args(Args), NumArgs(NumArgs),
5103 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005104 HasArithmeticOrEnumeralCandidateType(
5105 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005106 CandidateTypes(CandidateTypes),
5107 CandidateSet(CandidateSet) {
5108 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005109 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005110 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005111 assert(getArithmeticType(LastPromotedIntegralType - 1)
5112 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005113 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005114 assert(getArithmeticType(FirstPromotedArithmeticType)
5115 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005116 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005117 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5118 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005119 "Invalid last promoted arithmetic type");
5120 }
5121
5122 // C++ [over.built]p3:
5123 //
5124 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5125 // is either volatile or empty, there exist candidate operator
5126 // functions of the form
5127 //
5128 // VQ T& operator++(VQ T&);
5129 // T operator++(VQ T&, int);
5130 //
5131 // C++ [over.built]p4:
5132 //
5133 // For every pair (T, VQ), where T is an arithmetic type other
5134 // than bool, and VQ is either volatile or empty, there exist
5135 // candidate operator functions of the form
5136 //
5137 // VQ T& operator--(VQ T&);
5138 // T operator--(VQ T&, int);
5139 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005140 if (!HasArithmeticOrEnumeralCandidateType)
5141 return;
5142
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005143 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5144 Arith < NumArithmeticTypes; ++Arith) {
5145 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005146 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005147 VisibleTypeConversionsQuals.hasVolatile());
5148 }
5149 }
5150
5151 // C++ [over.built]p5:
5152 //
5153 // For every pair (T, VQ), where T is a cv-qualified or
5154 // cv-unqualified object type, and VQ is either volatile or
5155 // empty, there exist candidate operator functions of the form
5156 //
5157 // T*VQ& operator++(T*VQ&);
5158 // T*VQ& operator--(T*VQ&);
5159 // T* operator++(T*VQ&, int);
5160 // T* operator--(T*VQ&, int);
5161 void addPlusPlusMinusMinusPointerOverloads() {
5162 for (BuiltinCandidateTypeSet::iterator
5163 Ptr = CandidateTypes[0].pointer_begin(),
5164 PtrEnd = CandidateTypes[0].pointer_end();
5165 Ptr != PtrEnd; ++Ptr) {
5166 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005167 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005168 continue;
5169
5170 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5171 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5172 VisibleTypeConversionsQuals.hasVolatile()));
5173 }
5174 }
5175
5176 // C++ [over.built]p6:
5177 // For every cv-qualified or cv-unqualified object type T, there
5178 // exist candidate operator functions of the form
5179 //
5180 // T& operator*(T*);
5181 //
5182 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005183 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005184 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005185 // T& operator*(T*);
5186 void addUnaryStarPointerOverloads() {
5187 for (BuiltinCandidateTypeSet::iterator
5188 Ptr = CandidateTypes[0].pointer_begin(),
5189 PtrEnd = CandidateTypes[0].pointer_end();
5190 Ptr != PtrEnd; ++Ptr) {
5191 QualType ParamTy = *Ptr;
5192 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005193 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5194 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195
Douglas Gregor02824322011-01-26 19:30:28 +00005196 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5197 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5198 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005200 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5201 &ParamTy, Args, 1, CandidateSet);
5202 }
5203 }
5204
5205 // C++ [over.built]p9:
5206 // For every promoted arithmetic type T, there exist candidate
5207 // operator functions of the form
5208 //
5209 // T operator+(T);
5210 // T operator-(T);
5211 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005212 if (!HasArithmeticOrEnumeralCandidateType)
5213 return;
5214
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005215 for (unsigned Arith = FirstPromotedArithmeticType;
5216 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005217 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005218 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5219 }
5220
5221 // Extension: We also add these operators for vector types.
5222 for (BuiltinCandidateTypeSet::iterator
5223 Vec = CandidateTypes[0].vector_begin(),
5224 VecEnd = CandidateTypes[0].vector_end();
5225 Vec != VecEnd; ++Vec) {
5226 QualType VecTy = *Vec;
5227 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5228 }
5229 }
5230
5231 // C++ [over.built]p8:
5232 // For every type T, there exist candidate operator functions of
5233 // the form
5234 //
5235 // T* operator+(T*);
5236 void addUnaryPlusPointerOverloads() {
5237 for (BuiltinCandidateTypeSet::iterator
5238 Ptr = CandidateTypes[0].pointer_begin(),
5239 PtrEnd = CandidateTypes[0].pointer_end();
5240 Ptr != PtrEnd; ++Ptr) {
5241 QualType ParamTy = *Ptr;
5242 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5243 }
5244 }
5245
5246 // C++ [over.built]p10:
5247 // For every promoted integral type T, there exist candidate
5248 // operator functions of the form
5249 //
5250 // T operator~(T);
5251 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005252 if (!HasArithmeticOrEnumeralCandidateType)
5253 return;
5254
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005255 for (unsigned Int = FirstPromotedIntegralType;
5256 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005257 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005258 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5259 }
5260
5261 // Extension: We also add this operator for vector types.
5262 for (BuiltinCandidateTypeSet::iterator
5263 Vec = CandidateTypes[0].vector_begin(),
5264 VecEnd = CandidateTypes[0].vector_end();
5265 Vec != VecEnd; ++Vec) {
5266 QualType VecTy = *Vec;
5267 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5268 }
5269 }
5270
5271 // C++ [over.match.oper]p16:
5272 // For every pointer to member type T, there exist candidate operator
5273 // functions of the form
5274 //
5275 // bool operator==(T,T);
5276 // bool operator!=(T,T);
5277 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5278 /// Set of (canonical) types that we've already handled.
5279 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5280
5281 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5282 for (BuiltinCandidateTypeSet::iterator
5283 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5284 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5285 MemPtr != MemPtrEnd;
5286 ++MemPtr) {
5287 // Don't add the same builtin candidate twice.
5288 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5289 continue;
5290
5291 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5292 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5293 CandidateSet);
5294 }
5295 }
5296 }
5297
5298 // C++ [over.built]p15:
5299 //
5300 // For every pointer or enumeration type T, there exist
5301 // candidate operator functions of the form
5302 //
5303 // bool operator<(T, T);
5304 // bool operator>(T, T);
5305 // bool operator<=(T, T);
5306 // bool operator>=(T, T);
5307 // bool operator==(T, T);
5308 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005309 void addRelationalPointerOrEnumeralOverloads() {
5310 // C++ [over.built]p1:
5311 // If there is a user-written candidate with the same name and parameter
5312 // types as a built-in candidate operator function, the built-in operator
5313 // function is hidden and is not included in the set of candidate
5314 // functions.
5315 //
5316 // The text is actually in a note, but if we don't implement it then we end
5317 // up with ambiguities when the user provides an overloaded operator for
5318 // an enumeration type. Note that only enumeration types have this problem,
5319 // so we track which enumeration types we've seen operators for. Also, the
5320 // only other overloaded operator with enumeration argumenst, operator=,
5321 // cannot be overloaded for enumeration types, so this is the only place
5322 // where we must suppress candidates like this.
5323 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5324 UserDefinedBinaryOperators;
5325
5326 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5327 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5328 CandidateTypes[ArgIdx].enumeration_end()) {
5329 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5330 CEnd = CandidateSet.end();
5331 C != CEnd; ++C) {
5332 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5333 continue;
5334
5335 QualType FirstParamType =
5336 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5337 QualType SecondParamType =
5338 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5339
5340 // Skip if either parameter isn't of enumeral type.
5341 if (!FirstParamType->isEnumeralType() ||
5342 !SecondParamType->isEnumeralType())
5343 continue;
5344
5345 // Add this operator to the set of known user-defined operators.
5346 UserDefinedBinaryOperators.insert(
5347 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5348 S.Context.getCanonicalType(SecondParamType)));
5349 }
5350 }
5351 }
5352
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005353 /// Set of (canonical) types that we've already handled.
5354 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5355
5356 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5357 for (BuiltinCandidateTypeSet::iterator
5358 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5359 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5360 Ptr != PtrEnd; ++Ptr) {
5361 // Don't add the same builtin candidate twice.
5362 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5363 continue;
5364
5365 QualType ParamTypes[2] = { *Ptr, *Ptr };
5366 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5367 CandidateSet);
5368 }
5369 for (BuiltinCandidateTypeSet::iterator
5370 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5371 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5372 Enum != EnumEnd; ++Enum) {
5373 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5374
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005375 // Don't add the same builtin candidate twice, or if a user defined
5376 // candidate exists.
5377 if (!AddedTypes.insert(CanonType) ||
5378 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5379 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005380 continue;
5381
5382 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005383 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5384 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005385 }
5386 }
5387 }
5388
5389 // C++ [over.built]p13:
5390 //
5391 // For every cv-qualified or cv-unqualified object type T
5392 // there exist candidate operator functions of the form
5393 //
5394 // T* operator+(T*, ptrdiff_t);
5395 // T& operator[](T*, ptrdiff_t); [BELOW]
5396 // T* operator-(T*, ptrdiff_t);
5397 // T* operator+(ptrdiff_t, T*);
5398 // T& operator[](ptrdiff_t, T*); [BELOW]
5399 //
5400 // C++ [over.built]p14:
5401 //
5402 // For every T, where T is a pointer to object type, there
5403 // exist candidate operator functions of the form
5404 //
5405 // ptrdiff_t operator-(T, T);
5406 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5407 /// Set of (canonical) types that we've already handled.
5408 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5409
5410 for (int Arg = 0; Arg < 2; ++Arg) {
5411 QualType AsymetricParamTypes[2] = {
5412 S.Context.getPointerDiffType(),
5413 S.Context.getPointerDiffType(),
5414 };
5415 for (BuiltinCandidateTypeSet::iterator
5416 Ptr = CandidateTypes[Arg].pointer_begin(),
5417 PtrEnd = CandidateTypes[Arg].pointer_end();
5418 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005419 QualType PointeeTy = (*Ptr)->getPointeeType();
5420 if (!PointeeTy->isObjectType())
5421 continue;
5422
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005423 AsymetricParamTypes[Arg] = *Ptr;
5424 if (Arg == 0 || Op == OO_Plus) {
5425 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5426 // T* operator+(ptrdiff_t, T*);
5427 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5428 CandidateSet);
5429 }
5430 if (Op == OO_Minus) {
5431 // ptrdiff_t operator-(T, T);
5432 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5433 continue;
5434
5435 QualType ParamTypes[2] = { *Ptr, *Ptr };
5436 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5437 Args, 2, CandidateSet);
5438 }
5439 }
5440 }
5441 }
5442
5443 // C++ [over.built]p12:
5444 //
5445 // For every pair of promoted arithmetic types L and R, there
5446 // exist candidate operator functions of the form
5447 //
5448 // LR operator*(L, R);
5449 // LR operator/(L, R);
5450 // LR operator+(L, R);
5451 // LR operator-(L, R);
5452 // bool operator<(L, R);
5453 // bool operator>(L, R);
5454 // bool operator<=(L, R);
5455 // bool operator>=(L, R);
5456 // bool operator==(L, R);
5457 // bool operator!=(L, R);
5458 //
5459 // where LR is the result of the usual arithmetic conversions
5460 // between types L and R.
5461 //
5462 // C++ [over.built]p24:
5463 //
5464 // For every pair of promoted arithmetic types L and R, there exist
5465 // candidate operator functions of the form
5466 //
5467 // LR operator?(bool, L, R);
5468 //
5469 // where LR is the result of the usual arithmetic conversions
5470 // between types L and R.
5471 // Our candidates ignore the first parameter.
5472 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005473 if (!HasArithmeticOrEnumeralCandidateType)
5474 return;
5475
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005476 for (unsigned Left = FirstPromotedArithmeticType;
5477 Left < LastPromotedArithmeticType; ++Left) {
5478 for (unsigned Right = FirstPromotedArithmeticType;
5479 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005480 QualType LandR[2] = { getArithmeticType(Left),
5481 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005482 QualType Result =
5483 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005484 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005485 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5486 }
5487 }
5488
5489 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5490 // conditional operator for vector types.
5491 for (BuiltinCandidateTypeSet::iterator
5492 Vec1 = CandidateTypes[0].vector_begin(),
5493 Vec1End = CandidateTypes[0].vector_end();
5494 Vec1 != Vec1End; ++Vec1) {
5495 for (BuiltinCandidateTypeSet::iterator
5496 Vec2 = CandidateTypes[1].vector_begin(),
5497 Vec2End = CandidateTypes[1].vector_end();
5498 Vec2 != Vec2End; ++Vec2) {
5499 QualType LandR[2] = { *Vec1, *Vec2 };
5500 QualType Result = S.Context.BoolTy;
5501 if (!isComparison) {
5502 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5503 Result = *Vec1;
5504 else
5505 Result = *Vec2;
5506 }
5507
5508 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5509 }
5510 }
5511 }
5512
5513 // C++ [over.built]p17:
5514 //
5515 // For every pair of promoted integral types L and R, there
5516 // exist candidate operator functions of the form
5517 //
5518 // LR operator%(L, R);
5519 // LR operator&(L, R);
5520 // LR operator^(L, R);
5521 // LR operator|(L, R);
5522 // L operator<<(L, R);
5523 // L operator>>(L, R);
5524 //
5525 // where LR is the result of the usual arithmetic conversions
5526 // between types L and R.
5527 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005528 if (!HasArithmeticOrEnumeralCandidateType)
5529 return;
5530
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005531 for (unsigned Left = FirstPromotedIntegralType;
5532 Left < LastPromotedIntegralType; ++Left) {
5533 for (unsigned Right = FirstPromotedIntegralType;
5534 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005535 QualType LandR[2] = { getArithmeticType(Left),
5536 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005537 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5538 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005539 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005540 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5541 }
5542 }
5543 }
5544
5545 // C++ [over.built]p20:
5546 //
5547 // For every pair (T, VQ), where T is an enumeration or
5548 // pointer to member type and VQ is either volatile or
5549 // empty, there exist candidate operator functions of the form
5550 //
5551 // VQ T& operator=(VQ T&, T);
5552 void addAssignmentMemberPointerOrEnumeralOverloads() {
5553 /// Set of (canonical) types that we've already handled.
5554 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5555
5556 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5557 for (BuiltinCandidateTypeSet::iterator
5558 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5559 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5560 Enum != EnumEnd; ++Enum) {
5561 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5562 continue;
5563
5564 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5565 CandidateSet);
5566 }
5567
5568 for (BuiltinCandidateTypeSet::iterator
5569 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5570 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5571 MemPtr != MemPtrEnd; ++MemPtr) {
5572 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5573 continue;
5574
5575 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5576 CandidateSet);
5577 }
5578 }
5579 }
5580
5581 // C++ [over.built]p19:
5582 //
5583 // For every pair (T, VQ), where T is any type and VQ is either
5584 // volatile or empty, there exist candidate operator functions
5585 // of the form
5586 //
5587 // T*VQ& operator=(T*VQ&, T*);
5588 //
5589 // C++ [over.built]p21:
5590 //
5591 // For every pair (T, VQ), where T is a cv-qualified or
5592 // cv-unqualified object type and VQ is either volatile or
5593 // empty, there exist candidate operator functions of the form
5594 //
5595 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5596 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5597 void addAssignmentPointerOverloads(bool isEqualOp) {
5598 /// Set of (canonical) types that we've already handled.
5599 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5600
5601 for (BuiltinCandidateTypeSet::iterator
5602 Ptr = CandidateTypes[0].pointer_begin(),
5603 PtrEnd = CandidateTypes[0].pointer_end();
5604 Ptr != PtrEnd; ++Ptr) {
5605 // If this is operator=, keep track of the builtin candidates we added.
5606 if (isEqualOp)
5607 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005608 else if (!(*Ptr)->getPointeeType()->isObjectType())
5609 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005610
5611 // non-volatile version
5612 QualType ParamTypes[2] = {
5613 S.Context.getLValueReferenceType(*Ptr),
5614 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5615 };
5616 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5617 /*IsAssigmentOperator=*/ isEqualOp);
5618
5619 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5620 VisibleTypeConversionsQuals.hasVolatile()) {
5621 // volatile version
5622 ParamTypes[0] =
5623 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5624 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5625 /*IsAssigmentOperator=*/isEqualOp);
5626 }
5627 }
5628
5629 if (isEqualOp) {
5630 for (BuiltinCandidateTypeSet::iterator
5631 Ptr = CandidateTypes[1].pointer_begin(),
5632 PtrEnd = CandidateTypes[1].pointer_end();
5633 Ptr != PtrEnd; ++Ptr) {
5634 // Make sure we don't add the same candidate twice.
5635 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5636 continue;
5637
Chandler Carruth8e543b32010-12-12 08:17:55 +00005638 QualType ParamTypes[2] = {
5639 S.Context.getLValueReferenceType(*Ptr),
5640 *Ptr,
5641 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005642
5643 // non-volatile version
5644 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5645 /*IsAssigmentOperator=*/true);
5646
5647 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5648 VisibleTypeConversionsQuals.hasVolatile()) {
5649 // volatile version
5650 ParamTypes[0] =
5651 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005652 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5653 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005654 }
5655 }
5656 }
5657 }
5658
5659 // C++ [over.built]p18:
5660 //
5661 // For every triple (L, VQ, R), where L is an arithmetic type,
5662 // VQ is either volatile or empty, and R is a promoted
5663 // arithmetic type, there exist candidate operator functions of
5664 // the form
5665 //
5666 // VQ L& operator=(VQ L&, R);
5667 // VQ L& operator*=(VQ L&, R);
5668 // VQ L& operator/=(VQ L&, R);
5669 // VQ L& operator+=(VQ L&, R);
5670 // VQ L& operator-=(VQ L&, R);
5671 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005672 if (!HasArithmeticOrEnumeralCandidateType)
5673 return;
5674
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005675 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5676 for (unsigned Right = FirstPromotedArithmeticType;
5677 Right < LastPromotedArithmeticType; ++Right) {
5678 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005679 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005680
5681 // Add this built-in operator as a candidate (VQ is empty).
5682 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005683 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005684 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5685 /*IsAssigmentOperator=*/isEqualOp);
5686
5687 // Add this built-in operator as a candidate (VQ is 'volatile').
5688 if (VisibleTypeConversionsQuals.hasVolatile()) {
5689 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005690 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005691 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005692 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5693 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005694 /*IsAssigmentOperator=*/isEqualOp);
5695 }
5696 }
5697 }
5698
5699 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5700 for (BuiltinCandidateTypeSet::iterator
5701 Vec1 = CandidateTypes[0].vector_begin(),
5702 Vec1End = CandidateTypes[0].vector_end();
5703 Vec1 != Vec1End; ++Vec1) {
5704 for (BuiltinCandidateTypeSet::iterator
5705 Vec2 = CandidateTypes[1].vector_begin(),
5706 Vec2End = CandidateTypes[1].vector_end();
5707 Vec2 != Vec2End; ++Vec2) {
5708 QualType ParamTypes[2];
5709 ParamTypes[1] = *Vec2;
5710 // Add this built-in operator as a candidate (VQ is empty).
5711 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5712 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5713 /*IsAssigmentOperator=*/isEqualOp);
5714
5715 // Add this built-in operator as a candidate (VQ is 'volatile').
5716 if (VisibleTypeConversionsQuals.hasVolatile()) {
5717 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5718 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005719 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5720 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005721 /*IsAssigmentOperator=*/isEqualOp);
5722 }
5723 }
5724 }
5725 }
5726
5727 // C++ [over.built]p22:
5728 //
5729 // For every triple (L, VQ, R), where L is an integral type, VQ
5730 // is either volatile or empty, and R is a promoted integral
5731 // type, there exist candidate operator functions of the form
5732 //
5733 // VQ L& operator%=(VQ L&, R);
5734 // VQ L& operator<<=(VQ L&, R);
5735 // VQ L& operator>>=(VQ L&, R);
5736 // VQ L& operator&=(VQ L&, R);
5737 // VQ L& operator^=(VQ L&, R);
5738 // VQ L& operator|=(VQ L&, R);
5739 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005740 if (!HasArithmeticOrEnumeralCandidateType)
5741 return;
5742
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005743 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5744 for (unsigned Right = FirstPromotedIntegralType;
5745 Right < LastPromotedIntegralType; ++Right) {
5746 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005747 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005748
5749 // Add this built-in operator as a candidate (VQ is empty).
5750 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005751 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005752 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5753 if (VisibleTypeConversionsQuals.hasVolatile()) {
5754 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005755 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005756 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5757 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5758 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5759 CandidateSet);
5760 }
5761 }
5762 }
5763 }
5764
5765 // C++ [over.operator]p23:
5766 //
5767 // There also exist candidate operator functions of the form
5768 //
5769 // bool operator!(bool);
5770 // bool operator&&(bool, bool);
5771 // bool operator||(bool, bool);
5772 void addExclaimOverload() {
5773 QualType ParamTy = S.Context.BoolTy;
5774 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5775 /*IsAssignmentOperator=*/false,
5776 /*NumContextualBoolArguments=*/1);
5777 }
5778 void addAmpAmpOrPipePipeOverload() {
5779 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5780 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5781 /*IsAssignmentOperator=*/false,
5782 /*NumContextualBoolArguments=*/2);
5783 }
5784
5785 // C++ [over.built]p13:
5786 //
5787 // For every cv-qualified or cv-unqualified object type T there
5788 // exist candidate operator functions of the form
5789 //
5790 // T* operator+(T*, ptrdiff_t); [ABOVE]
5791 // T& operator[](T*, ptrdiff_t);
5792 // T* operator-(T*, ptrdiff_t); [ABOVE]
5793 // T* operator+(ptrdiff_t, T*); [ABOVE]
5794 // T& operator[](ptrdiff_t, T*);
5795 void addSubscriptOverloads() {
5796 for (BuiltinCandidateTypeSet::iterator
5797 Ptr = CandidateTypes[0].pointer_begin(),
5798 PtrEnd = CandidateTypes[0].pointer_end();
5799 Ptr != PtrEnd; ++Ptr) {
5800 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5801 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005802 if (!PointeeType->isObjectType())
5803 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005804
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005805 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5806
5807 // T& operator[](T*, ptrdiff_t)
5808 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5809 }
5810
5811 for (BuiltinCandidateTypeSet::iterator
5812 Ptr = CandidateTypes[1].pointer_begin(),
5813 PtrEnd = CandidateTypes[1].pointer_end();
5814 Ptr != PtrEnd; ++Ptr) {
5815 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5816 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005817 if (!PointeeType->isObjectType())
5818 continue;
5819
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005820 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5821
5822 // T& operator[](ptrdiff_t, T*)
5823 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5824 }
5825 }
5826
5827 // C++ [over.built]p11:
5828 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5829 // C1 is the same type as C2 or is a derived class of C2, T is an object
5830 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5831 // there exist candidate operator functions of the form
5832 //
5833 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5834 //
5835 // where CV12 is the union of CV1 and CV2.
5836 void addArrowStarOverloads() {
5837 for (BuiltinCandidateTypeSet::iterator
5838 Ptr = CandidateTypes[0].pointer_begin(),
5839 PtrEnd = CandidateTypes[0].pointer_end();
5840 Ptr != PtrEnd; ++Ptr) {
5841 QualType C1Ty = (*Ptr);
5842 QualType C1;
5843 QualifierCollector Q1;
5844 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5845 if (!isa<RecordType>(C1))
5846 continue;
5847 // heuristic to reduce number of builtin candidates in the set.
5848 // Add volatile/restrict version only if there are conversions to a
5849 // volatile/restrict type.
5850 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5851 continue;
5852 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5853 continue;
5854 for (BuiltinCandidateTypeSet::iterator
5855 MemPtr = CandidateTypes[1].member_pointer_begin(),
5856 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5857 MemPtr != MemPtrEnd; ++MemPtr) {
5858 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5859 QualType C2 = QualType(mptr->getClass(), 0);
5860 C2 = C2.getUnqualifiedType();
5861 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5862 break;
5863 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5864 // build CV12 T&
5865 QualType T = mptr->getPointeeType();
5866 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5867 T.isVolatileQualified())
5868 continue;
5869 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5870 T.isRestrictQualified())
5871 continue;
5872 T = Q1.apply(S.Context, T);
5873 QualType ResultTy = S.Context.getLValueReferenceType(T);
5874 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5875 }
5876 }
5877 }
5878
5879 // Note that we don't consider the first argument, since it has been
5880 // contextually converted to bool long ago. The candidates below are
5881 // therefore added as binary.
5882 //
5883 // C++ [over.built]p25:
5884 // For every type T, where T is a pointer, pointer-to-member, or scoped
5885 // enumeration type, there exist candidate operator functions of the form
5886 //
5887 // T operator?(bool, T, T);
5888 //
5889 void addConditionalOperatorOverloads() {
5890 /// Set of (canonical) types that we've already handled.
5891 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5892
5893 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5894 for (BuiltinCandidateTypeSet::iterator
5895 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5896 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5897 Ptr != PtrEnd; ++Ptr) {
5898 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5899 continue;
5900
5901 QualType ParamTypes[2] = { *Ptr, *Ptr };
5902 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5903 }
5904
5905 for (BuiltinCandidateTypeSet::iterator
5906 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5907 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5908 MemPtr != MemPtrEnd; ++MemPtr) {
5909 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5910 continue;
5911
5912 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5913 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5914 }
5915
5916 if (S.getLangOptions().CPlusPlus0x) {
5917 for (BuiltinCandidateTypeSet::iterator
5918 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5919 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5920 Enum != EnumEnd; ++Enum) {
5921 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5922 continue;
5923
5924 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5925 continue;
5926
5927 QualType ParamTypes[2] = { *Enum, *Enum };
5928 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5929 }
5930 }
5931 }
5932 }
5933};
5934
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005935} // end anonymous namespace
5936
5937/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5938/// operator overloads to the candidate set (C++ [over.built]), based
5939/// on the operator @p Op and the arguments given. For example, if the
5940/// operator is a binary '+', this routine might add "int
5941/// operator+(int, int)" to cover integer addition.
5942void
5943Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5944 SourceLocation OpLoc,
5945 Expr **Args, unsigned NumArgs,
5946 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005947 // Find all of the types that the arguments can convert to, but only
5948 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005949 // that make use of these types. Also record whether we encounter non-record
5950 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005951 Qualifiers VisibleTypeConversionsQuals;
5952 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005953 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5954 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005955
5956 bool HasNonRecordCandidateType = false;
5957 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005958 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5959 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5960 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5961 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5962 OpLoc,
5963 true,
5964 (Op == OO_Exclaim ||
5965 Op == OO_AmpAmp ||
5966 Op == OO_PipePipe),
5967 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005968 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5969 CandidateTypes[ArgIdx].hasNonRecordTypes();
5970 HasArithmeticOrEnumeralCandidateType =
5971 HasArithmeticOrEnumeralCandidateType ||
5972 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005973 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005974
Chandler Carruth00a38332010-12-13 01:44:01 +00005975 // Exit early when no non-record types have been added to the candidate set
5976 // for any of the arguments to the operator.
5977 if (!HasNonRecordCandidateType)
5978 return;
5979
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005980 // Setup an object to manage the common state for building overloads.
5981 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5982 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005983 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005984 CandidateTypes, CandidateSet);
5985
5986 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005987 switch (Op) {
5988 case OO_None:
5989 case NUM_OVERLOADED_OPERATORS:
5990 assert(false && "Expected an overloaded operator");
5991 break;
5992
Chandler Carruth5184de02010-12-12 08:51:33 +00005993 case OO_New:
5994 case OO_Delete:
5995 case OO_Array_New:
5996 case OO_Array_Delete:
5997 case OO_Call:
5998 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5999 break;
6000
6001 case OO_Comma:
6002 case OO_Arrow:
6003 // C++ [over.match.oper]p3:
6004 // -- For the operator ',', the unary operator '&', or the
6005 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006006 break;
6007
6008 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006009 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006010 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006011 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006012
6013 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006014 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006015 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006016 } else {
6017 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6018 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6019 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006020 break;
6021
Chandler Carruth5184de02010-12-12 08:51:33 +00006022 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006023 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006024 OpBuilder.addUnaryStarPointerOverloads();
6025 else
6026 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6027 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006028
Chandler Carruth5184de02010-12-12 08:51:33 +00006029 case OO_Slash:
6030 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006031 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006032
6033 case OO_PlusPlus:
6034 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006035 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6036 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006037 break;
6038
Douglas Gregor84605ae2009-08-24 13:43:27 +00006039 case OO_EqualEqual:
6040 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006041 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006042 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006043
Douglas Gregora11693b2008-11-12 17:17:38 +00006044 case OO_Less:
6045 case OO_Greater:
6046 case OO_LessEqual:
6047 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006048 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006049 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6050 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006051
Douglas Gregora11693b2008-11-12 17:17:38 +00006052 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006053 case OO_Caret:
6054 case OO_Pipe:
6055 case OO_LessLess:
6056 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006057 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006058 break;
6059
Chandler Carruth5184de02010-12-12 08:51:33 +00006060 case OO_Amp: // '&' is either unary or binary
6061 if (NumArgs == 1)
6062 // C++ [over.match.oper]p3:
6063 // -- For the operator ',', the unary operator '&', or the
6064 // operator '->', the built-in candidates set is empty.
6065 break;
6066
6067 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6068 break;
6069
6070 case OO_Tilde:
6071 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6072 break;
6073
Douglas Gregora11693b2008-11-12 17:17:38 +00006074 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006075 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006076 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006077
6078 case OO_PlusEqual:
6079 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006080 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006081 // Fall through.
6082
6083 case OO_StarEqual:
6084 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006085 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006086 break;
6087
6088 case OO_PercentEqual:
6089 case OO_LessLessEqual:
6090 case OO_GreaterGreaterEqual:
6091 case OO_AmpEqual:
6092 case OO_CaretEqual:
6093 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006094 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006095 break;
6096
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006097 case OO_Exclaim:
6098 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006099 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006100
Douglas Gregora11693b2008-11-12 17:17:38 +00006101 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006102 case OO_PipePipe:
6103 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006104 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006105
6106 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006107 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006108 break;
6109
6110 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006111 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006112 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006113
6114 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006115 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006116 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6117 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006118 }
6119}
6120
Douglas Gregore254f902009-02-04 00:32:51 +00006121/// \brief Add function candidates found via argument-dependent lookup
6122/// to the set of overloading candidates.
6123///
6124/// This routine performs argument-dependent name lookup based on the
6125/// given function name (which may also be an operator name) and adds
6126/// all of the overload candidates found by ADL to the overload
6127/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006128void
Douglas Gregore254f902009-02-04 00:32:51 +00006129Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006130 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006131 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006132 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006133 OverloadCandidateSet& CandidateSet,
6134 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00006135 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006136
John McCall91f61fc2010-01-26 06:04:06 +00006137 // FIXME: This approach for uniquing ADL results (and removing
6138 // redundant candidates from the set) relies on pointer-equality,
6139 // which means we need to key off the canonical decl. However,
6140 // always going back to the canonical decl might not get us the
6141 // right set of default arguments. What default arguments are
6142 // we supposed to consider on ADL candidates, anyway?
6143
Douglas Gregorcabea402009-09-22 15:41:20 +00006144 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00006145 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00006146
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006147 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006148 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6149 CandEnd = CandidateSet.end();
6150 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006151 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006152 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006153 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006154 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006155 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006156
6157 // For each of the ADL candidates we found, add it to the overload
6158 // set.
John McCall8fe68082010-01-26 07:16:45 +00006159 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006160 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006161 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006162 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006163 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006164
John McCalla0296f72010-03-19 07:35:19 +00006165 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006166 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006167 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006168 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006169 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006170 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006171 }
Douglas Gregore254f902009-02-04 00:32:51 +00006172}
6173
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006174/// isBetterOverloadCandidate - Determines whether the first overload
6175/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006176bool
John McCall5c32be02010-08-24 20:38:10 +00006177isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006178 const OverloadCandidate &Cand1,
6179 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006180 SourceLocation Loc,
6181 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006182 // Define viable functions to be better candidates than non-viable
6183 // functions.
6184 if (!Cand2.Viable)
6185 return Cand1.Viable;
6186 else if (!Cand1.Viable)
6187 return false;
6188
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006189 // C++ [over.match.best]p1:
6190 //
6191 // -- if F is a static member function, ICS1(F) is defined such
6192 // that ICS1(F) is neither better nor worse than ICS1(G) for
6193 // any function G, and, symmetrically, ICS1(G) is neither
6194 // better nor worse than ICS1(F).
6195 unsigned StartArg = 0;
6196 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6197 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006198
Douglas Gregord3cb3562009-07-07 23:38:56 +00006199 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006200 // A viable function F1 is defined to be a better function than another
6201 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006202 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006203 unsigned NumArgs = Cand1.Conversions.size();
6204 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6205 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006206 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006207 switch (CompareImplicitConversionSequences(S,
6208 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006209 Cand2.Conversions[ArgIdx])) {
6210 case ImplicitConversionSequence::Better:
6211 // Cand1 has a better conversion sequence.
6212 HasBetterConversion = true;
6213 break;
6214
6215 case ImplicitConversionSequence::Worse:
6216 // Cand1 can't be better than Cand2.
6217 return false;
6218
6219 case ImplicitConversionSequence::Indistinguishable:
6220 // Do nothing.
6221 break;
6222 }
6223 }
6224
Mike Stump11289f42009-09-09 15:08:12 +00006225 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006226 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006227 if (HasBetterConversion)
6228 return true;
6229
Mike Stump11289f42009-09-09 15:08:12 +00006230 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006231 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006232 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006233 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6234 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006235
6236 // -- F1 and F2 are function template specializations, and the function
6237 // template for F1 is more specialized than the template for F2
6238 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006239 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006240 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006241 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006242 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006243 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6244 Cand2.Function->getPrimaryTemplate(),
6245 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006246 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006247 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006248 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006249 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006251
Douglas Gregora1f013e2008-11-07 22:36:19 +00006252 // -- the context is an initialization by user-defined conversion
6253 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6254 // from the return type of F1 to the destination type (i.e.,
6255 // the type of the entity being initialized) is a better
6256 // conversion sequence than the standard conversion sequence
6257 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006258 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006259 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006260 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006261 switch (CompareStandardConversionSequences(S,
6262 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006263 Cand2.FinalConversion)) {
6264 case ImplicitConversionSequence::Better:
6265 // Cand1 has a better conversion sequence.
6266 return true;
6267
6268 case ImplicitConversionSequence::Worse:
6269 // Cand1 can't be better than Cand2.
6270 return false;
6271
6272 case ImplicitConversionSequence::Indistinguishable:
6273 // Do nothing
6274 break;
6275 }
6276 }
6277
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006278 return false;
6279}
6280
Mike Stump11289f42009-09-09 15:08:12 +00006281/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006282/// within an overload candidate set.
6283///
6284/// \param CandidateSet the set of candidate functions.
6285///
6286/// \param Loc the location of the function name (or operator symbol) for
6287/// which overload resolution occurs.
6288///
Mike Stump11289f42009-09-09 15:08:12 +00006289/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006290/// function, Best points to the candidate function found.
6291///
6292/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006293OverloadingResult
6294OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006295 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006296 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006297 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006298 Best = end();
6299 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6300 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006301 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006302 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006303 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006304 }
6305
6306 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006307 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006308 return OR_No_Viable_Function;
6309
6310 // Make sure that this function is better than every other viable
6311 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006312 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006313 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006314 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006315 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006316 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006317 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006318 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006319 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006320 }
Mike Stump11289f42009-09-09 15:08:12 +00006321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006322 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006323 if (Best->Function &&
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006324 (Best->Function->isDeleted() || Best->Function->isUnavailable()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006325 return OR_Deleted;
6326
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006327 return OR_Success;
6328}
6329
John McCall53262c92010-01-12 02:15:36 +00006330namespace {
6331
6332enum OverloadCandidateKind {
6333 oc_function,
6334 oc_method,
6335 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006336 oc_function_template,
6337 oc_method_template,
6338 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006339 oc_implicit_default_constructor,
6340 oc_implicit_copy_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006341 oc_implicit_copy_assignment,
6342 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006343};
6344
John McCalle1ac8d12010-01-13 00:25:19 +00006345OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6346 FunctionDecl *Fn,
6347 std::string &Description) {
6348 bool isTemplate = false;
6349
6350 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6351 isTemplate = true;
6352 Description = S.getTemplateArgumentBindingsText(
6353 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6354 }
John McCallfd0b2f82010-01-06 09:43:14 +00006355
6356 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006357 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006358 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006359
Sebastian Redl08905022011-02-05 19:23:19 +00006360 if (Ctor->getInheritedConstructor())
6361 return oc_implicit_inherited_constructor;
6362
John McCall53262c92010-01-12 02:15:36 +00006363 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6364 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006365 }
6366
6367 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6368 // This actually gets spelled 'candidate function' for now, but
6369 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006370 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006371 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006372
Douglas Gregorec3bec02010-09-27 22:37:28 +00006373 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006374 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006375 return oc_implicit_copy_assignment;
6376 }
6377
John McCalle1ac8d12010-01-13 00:25:19 +00006378 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006379}
6380
Sebastian Redl08905022011-02-05 19:23:19 +00006381void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6382 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6383 if (!Ctor) return;
6384
6385 Ctor = Ctor->getInheritedConstructor();
6386 if (!Ctor) return;
6387
6388 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6389}
6390
John McCall53262c92010-01-12 02:15:36 +00006391} // end anonymous namespace
6392
6393// Notes the location of an overload candidate.
6394void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006395 std::string FnDesc;
6396 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6397 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6398 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006399 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006400}
6401
Douglas Gregorb491ed32011-02-19 21:32:49 +00006402//Notes the location of all overload candidates designated through
6403// OverloadedExpr
6404void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6405 assert(OverloadedExpr->getType() == Context.OverloadTy);
6406
6407 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6408 OverloadExpr *OvlExpr = Ovl.Expression;
6409
6410 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6411 IEnd = OvlExpr->decls_end();
6412 I != IEnd; ++I) {
6413 if (FunctionTemplateDecl *FunTmpl =
6414 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6415 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6416 } else if (FunctionDecl *Fun
6417 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6418 NoteOverloadCandidate(Fun);
6419 }
6420 }
6421}
6422
John McCall0d1da222010-01-12 00:44:57 +00006423/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6424/// "lead" diagnostic; it will be given two arguments, the source and
6425/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006426void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6427 Sema &S,
6428 SourceLocation CaretLoc,
6429 const PartialDiagnostic &PDiag) const {
6430 S.Diag(CaretLoc, PDiag)
6431 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006432 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006433 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6434 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006435 }
John McCall12f97bc2010-01-08 04:41:39 +00006436}
6437
John McCall0d1da222010-01-12 00:44:57 +00006438namespace {
6439
John McCall6a61b522010-01-13 09:16:55 +00006440void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6441 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6442 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006443 assert(Cand->Function && "for now, candidate must be a function");
6444 FunctionDecl *Fn = Cand->Function;
6445
6446 // There's a conversion slot for the object argument if this is a
6447 // non-constructor method. Note that 'I' corresponds the
6448 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006449 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006450 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006451 if (I == 0)
6452 isObjectArgument = true;
6453 else
6454 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006455 }
6456
John McCalle1ac8d12010-01-13 00:25:19 +00006457 std::string FnDesc;
6458 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6459
John McCall6a61b522010-01-13 09:16:55 +00006460 Expr *FromExpr = Conv.Bad.FromExpr;
6461 QualType FromTy = Conv.Bad.getFromType();
6462 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006463
John McCallfb7ad0f2010-02-02 02:42:52 +00006464 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006465 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006466 Expr *E = FromExpr->IgnoreParens();
6467 if (isa<UnaryOperator>(E))
6468 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006469 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006470
6471 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6472 << (unsigned) FnKind << FnDesc
6473 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6474 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006475 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006476 return;
6477 }
6478
John McCall6d174642010-01-23 08:10:49 +00006479 // Do some hand-waving analysis to see if the non-viability is due
6480 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006481 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6482 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6483 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6484 CToTy = RT->getPointeeType();
6485 else {
6486 // TODO: detect and diagnose the full richness of const mismatches.
6487 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6488 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6489 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6490 }
6491
6492 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6493 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6494 // It is dumb that we have to do this here.
6495 while (isa<ArrayType>(CFromTy))
6496 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6497 while (isa<ArrayType>(CToTy))
6498 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6499
6500 Qualifiers FromQs = CFromTy.getQualifiers();
6501 Qualifiers ToQs = CToTy.getQualifiers();
6502
6503 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6505 << (unsigned) FnKind << FnDesc
6506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6507 << FromTy
6508 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6509 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006510 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006511 return;
6512 }
6513
6514 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6515 assert(CVR && "unexpected qualifiers mismatch");
6516
6517 if (isObjectArgument) {
6518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6519 << (unsigned) FnKind << FnDesc
6520 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6521 << FromTy << (CVR - 1);
6522 } else {
6523 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6524 << (unsigned) FnKind << FnDesc
6525 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6526 << FromTy << (CVR - 1) << I+1;
6527 }
Sebastian Redl08905022011-02-05 19:23:19 +00006528 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006529 return;
6530 }
6531
John McCall6d174642010-01-23 08:10:49 +00006532 // Diagnose references or pointers to incomplete types differently,
6533 // since it's far from impossible that the incompleteness triggered
6534 // the failure.
6535 QualType TempFromTy = FromTy.getNonReferenceType();
6536 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6537 TempFromTy = PTy->getPointeeType();
6538 if (TempFromTy->isIncompleteType()) {
6539 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6540 << (unsigned) FnKind << FnDesc
6541 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6542 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006543 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006544 return;
6545 }
6546
Douglas Gregor56f2e342010-06-30 23:01:39 +00006547 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006548 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006549 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6550 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6551 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6552 FromPtrTy->getPointeeType()) &&
6553 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6554 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006555 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006556 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006557 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006558 }
6559 } else if (const ObjCObjectPointerType *FromPtrTy
6560 = FromTy->getAs<ObjCObjectPointerType>()) {
6561 if (const ObjCObjectPointerType *ToPtrTy
6562 = ToTy->getAs<ObjCObjectPointerType>())
6563 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6564 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6565 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6566 FromPtrTy->getPointeeType()) &&
6567 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006568 BaseToDerivedConversion = 2;
6569 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6570 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6571 !FromTy->isIncompleteType() &&
6572 !ToRefTy->getPointeeType()->isIncompleteType() &&
6573 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6574 BaseToDerivedConversion = 3;
6575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006576
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006577 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006578 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006579 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006580 << (unsigned) FnKind << FnDesc
6581 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006582 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006583 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006584 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006585 return;
6586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006587
John McCall47000992010-01-14 03:28:57 +00006588 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006589 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6590 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006591 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006592 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006593 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006594}
6595
6596void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6597 unsigned NumFormalArgs) {
6598 // TODO: treat calls to a missing default constructor as a special case
6599
6600 FunctionDecl *Fn = Cand->Function;
6601 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6602
6603 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006604
John McCall6a61b522010-01-13 09:16:55 +00006605 // at least / at most / exactly
6606 unsigned mode, modeCount;
6607 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006608 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6609 (Cand->FailureKind == ovl_fail_bad_deduction &&
6610 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006611 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006612 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006613 mode = 0; // "at least"
6614 else
6615 mode = 2; // "exactly"
6616 modeCount = MinParams;
6617 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006618 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6619 (Cand->FailureKind == ovl_fail_bad_deduction &&
6620 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006621 if (MinParams != FnTy->getNumArgs())
6622 mode = 1; // "at most"
6623 else
6624 mode = 2; // "exactly"
6625 modeCount = FnTy->getNumArgs();
6626 }
6627
6628 std::string Description;
6629 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6630
6631 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006632 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006633 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006634 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006635}
6636
John McCall8b9ed552010-02-01 18:53:26 +00006637/// Diagnose a failed template-argument deduction.
6638void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6639 Expr **Args, unsigned NumArgs) {
6640 FunctionDecl *Fn = Cand->Function; // pattern
6641
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006642 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006643 NamedDecl *ParamD;
6644 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6645 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6646 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006647 switch (Cand->DeductionFailure.Result) {
6648 case Sema::TDK_Success:
6649 llvm_unreachable("TDK_success while diagnosing bad deduction");
6650
6651 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006652 assert(ParamD && "no parameter found for incomplete deduction result");
6653 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6654 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006655 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006656 return;
6657 }
6658
John McCall42d7d192010-08-05 09:05:08 +00006659 case Sema::TDK_Underqualified: {
6660 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6661 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6662
6663 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6664
6665 // Param will have been canonicalized, but it should just be a
6666 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006667 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006668 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006669 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006670 assert(S.Context.hasSameType(Param, NonCanonParam));
6671
6672 // Arg has also been canonicalized, but there's nothing we can do
6673 // about that. It also doesn't matter as much, because it won't
6674 // have any template parameters in it (because deduction isn't
6675 // done on dependent types).
6676 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6677
6678 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6679 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00006680 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00006681 return;
6682 }
6683
6684 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006685 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006686 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006687 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006688 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006689 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006690 which = 1;
6691 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006692 which = 2;
6693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006694
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006695 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006697 << *Cand->DeductionFailure.getFirstArg()
6698 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00006699 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006700 return;
6701 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006702
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006703 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006704 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006705 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006706 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006707 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6708 << ParamD->getDeclName();
6709 else {
6710 int index = 0;
6711 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6712 index = TTP->getIndex();
6713 else if (NonTypeTemplateParmDecl *NTTP
6714 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6715 index = NTTP->getIndex();
6716 else
6717 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006718 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006719 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6720 << (index + 1);
6721 }
Sebastian Redl08905022011-02-05 19:23:19 +00006722 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006723 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006724
Douglas Gregor02eb4832010-05-08 18:13:28 +00006725 case Sema::TDK_TooManyArguments:
6726 case Sema::TDK_TooFewArguments:
6727 DiagnoseArityMismatch(S, Cand, NumArgs);
6728 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006729
6730 case Sema::TDK_InstantiationDepth:
6731 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00006732 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006733 return;
6734
6735 case Sema::TDK_SubstitutionFailure: {
6736 std::string ArgString;
6737 if (TemplateArgumentList *Args
6738 = Cand->DeductionFailure.getTemplateArgumentList())
6739 ArgString = S.getTemplateArgumentBindingsText(
6740 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6741 *Args);
6742 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6743 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00006744 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006745 return;
6746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747
John McCall8b9ed552010-02-01 18:53:26 +00006748 // TODO: diagnose these individually, then kill off
6749 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006750 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006751 case Sema::TDK_FailedOverloadResolution:
6752 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00006753 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006754 return;
6755 }
6756}
6757
6758/// Generates a 'note' diagnostic for an overload candidate. We've
6759/// already generated a primary error at the call site.
6760///
6761/// It really does need to be a single diagnostic with its caret
6762/// pointed at the candidate declaration. Yes, this creates some
6763/// major challenges of technical writing. Yes, this makes pointing
6764/// out problems with specific arguments quite awkward. It's still
6765/// better than generating twenty screens of text for every failed
6766/// overload.
6767///
6768/// It would be great to be able to express per-candidate problems
6769/// more richly for those diagnostic clients that cared, but we'd
6770/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006771void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6772 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006773 FunctionDecl *Fn = Cand->Function;
6774
John McCall12f97bc2010-01-08 04:41:39 +00006775 // Note deleted candidates, but only if they're viable.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006776 if (Cand->Viable && (Fn->isDeleted() || Fn->isUnavailable())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006777 std::string FnDesc;
6778 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006779
6780 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006781 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00006782 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00006783 return;
John McCall12f97bc2010-01-08 04:41:39 +00006784 }
6785
John McCalle1ac8d12010-01-13 00:25:19 +00006786 // We don't really have anything else to say about viable candidates.
6787 if (Cand->Viable) {
6788 S.NoteOverloadCandidate(Fn);
6789 return;
6790 }
John McCall0d1da222010-01-12 00:44:57 +00006791
John McCall6a61b522010-01-13 09:16:55 +00006792 switch (Cand->FailureKind) {
6793 case ovl_fail_too_many_arguments:
6794 case ovl_fail_too_few_arguments:
6795 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006796
John McCall6a61b522010-01-13 09:16:55 +00006797 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006798 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6799
John McCallfe796dd2010-01-23 05:17:32 +00006800 case ovl_fail_trivial_conversion:
6801 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006802 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006803 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006804
John McCall65eb8792010-02-25 01:37:24 +00006805 case ovl_fail_bad_conversion: {
6806 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6807 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006808 if (Cand->Conversions[I].isBad())
6809 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810
John McCall6a61b522010-01-13 09:16:55 +00006811 // FIXME: this currently happens when we're called from SemaInit
6812 // when user-conversion overload fails. Figure out how to handle
6813 // those conditions and diagnose them well.
6814 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006815 }
John McCall65eb8792010-02-25 01:37:24 +00006816 }
John McCalld3224162010-01-08 00:58:21 +00006817}
6818
6819void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6820 // Desugar the type of the surrogate down to a function type,
6821 // retaining as many typedefs as possible while still showing
6822 // the function type (and, therefore, its parameter types).
6823 QualType FnType = Cand->Surrogate->getConversionType();
6824 bool isLValueReference = false;
6825 bool isRValueReference = false;
6826 bool isPointer = false;
6827 if (const LValueReferenceType *FnTypeRef =
6828 FnType->getAs<LValueReferenceType>()) {
6829 FnType = FnTypeRef->getPointeeType();
6830 isLValueReference = true;
6831 } else if (const RValueReferenceType *FnTypeRef =
6832 FnType->getAs<RValueReferenceType>()) {
6833 FnType = FnTypeRef->getPointeeType();
6834 isRValueReference = true;
6835 }
6836 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6837 FnType = FnTypePtr->getPointeeType();
6838 isPointer = true;
6839 }
6840 // Desugar down to a function type.
6841 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6842 // Reconstruct the pointer/reference as appropriate.
6843 if (isPointer) FnType = S.Context.getPointerType(FnType);
6844 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6845 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6846
6847 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6848 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00006849 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00006850}
6851
6852void NoteBuiltinOperatorCandidate(Sema &S,
6853 const char *Opc,
6854 SourceLocation OpLoc,
6855 OverloadCandidate *Cand) {
6856 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6857 std::string TypeStr("operator");
6858 TypeStr += Opc;
6859 TypeStr += "(";
6860 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6861 if (Cand->Conversions.size() == 1) {
6862 TypeStr += ")";
6863 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6864 } else {
6865 TypeStr += ", ";
6866 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6867 TypeStr += ")";
6868 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6869 }
6870}
6871
6872void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6873 OverloadCandidate *Cand) {
6874 unsigned NoOperands = Cand->Conversions.size();
6875 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6876 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006877 if (ICS.isBad()) break; // all meaningless after first invalid
6878 if (!ICS.isAmbiguous()) continue;
6879
John McCall5c32be02010-08-24 20:38:10 +00006880 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006881 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006882 }
6883}
6884
John McCall3712d9e2010-01-15 23:32:50 +00006885SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6886 if (Cand->Function)
6887 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006888 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006889 return Cand->Surrogate->getLocation();
6890 return SourceLocation();
6891}
6892
John McCallad2587a2010-01-12 00:48:53 +00006893struct CompareOverloadCandidatesForDisplay {
6894 Sema &S;
6895 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006896
6897 bool operator()(const OverloadCandidate *L,
6898 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006899 // Fast-path this check.
6900 if (L == R) return false;
6901
John McCall12f97bc2010-01-08 04:41:39 +00006902 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006903 if (L->Viable) {
6904 if (!R->Viable) return true;
6905
6906 // TODO: introduce a tri-valued comparison for overload
6907 // candidates. Would be more worthwhile if we had a sort
6908 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006909 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6910 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006911 } else if (R->Viable)
6912 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006913
John McCall3712d9e2010-01-15 23:32:50 +00006914 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006915
John McCall3712d9e2010-01-15 23:32:50 +00006916 // Criteria by which we can sort non-viable candidates:
6917 if (!L->Viable) {
6918 // 1. Arity mismatches come after other candidates.
6919 if (L->FailureKind == ovl_fail_too_many_arguments ||
6920 L->FailureKind == ovl_fail_too_few_arguments)
6921 return false;
6922 if (R->FailureKind == ovl_fail_too_many_arguments ||
6923 R->FailureKind == ovl_fail_too_few_arguments)
6924 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006925
John McCallfe796dd2010-01-23 05:17:32 +00006926 // 2. Bad conversions come first and are ordered by the number
6927 // of bad conversions and quality of good conversions.
6928 if (L->FailureKind == ovl_fail_bad_conversion) {
6929 if (R->FailureKind != ovl_fail_bad_conversion)
6930 return true;
6931
6932 // If there's any ordering between the defined conversions...
6933 // FIXME: this might not be transitive.
6934 assert(L->Conversions.size() == R->Conversions.size());
6935
6936 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006937 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6938 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006939 switch (CompareImplicitConversionSequences(S,
6940 L->Conversions[I],
6941 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006942 case ImplicitConversionSequence::Better:
6943 leftBetter++;
6944 break;
6945
6946 case ImplicitConversionSequence::Worse:
6947 leftBetter--;
6948 break;
6949
6950 case ImplicitConversionSequence::Indistinguishable:
6951 break;
6952 }
6953 }
6954 if (leftBetter > 0) return true;
6955 if (leftBetter < 0) return false;
6956
6957 } else if (R->FailureKind == ovl_fail_bad_conversion)
6958 return false;
6959
John McCall3712d9e2010-01-15 23:32:50 +00006960 // TODO: others?
6961 }
6962
6963 // Sort everything else by location.
6964 SourceLocation LLoc = GetLocationForCandidate(L);
6965 SourceLocation RLoc = GetLocationForCandidate(R);
6966
6967 // Put candidates without locations (e.g. builtins) at the end.
6968 if (LLoc.isInvalid()) return false;
6969 if (RLoc.isInvalid()) return true;
6970
6971 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006972 }
6973};
6974
John McCallfe796dd2010-01-23 05:17:32 +00006975/// CompleteNonViableCandidate - Normally, overload resolution only
6976/// computes up to the first
6977void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6978 Expr **Args, unsigned NumArgs) {
6979 assert(!Cand->Viable);
6980
6981 // Don't do anything on failures other than bad conversion.
6982 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6983
6984 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006985 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006986 unsigned ConvCount = Cand->Conversions.size();
6987 while (true) {
6988 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6989 ConvIdx++;
6990 if (Cand->Conversions[ConvIdx - 1].isBad())
6991 break;
6992 }
6993
6994 if (ConvIdx == ConvCount)
6995 return;
6996
John McCall65eb8792010-02-25 01:37:24 +00006997 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6998 "remaining conversion is initialized?");
6999
Douglas Gregoradc7a702010-04-16 17:45:54 +00007000 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007001 // operation somehow.
7002 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007003
7004 const FunctionProtoType* Proto;
7005 unsigned ArgIdx = ConvIdx;
7006
7007 if (Cand->IsSurrogate) {
7008 QualType ConvType
7009 = Cand->Surrogate->getConversionType().getNonReferenceType();
7010 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7011 ConvType = ConvPtrType->getPointeeType();
7012 Proto = ConvType->getAs<FunctionProtoType>();
7013 ArgIdx--;
7014 } else if (Cand->Function) {
7015 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7016 if (isa<CXXMethodDecl>(Cand->Function) &&
7017 !isa<CXXConstructorDecl>(Cand->Function))
7018 ArgIdx--;
7019 } else {
7020 // Builtin binary operator with a bad first conversion.
7021 assert(ConvCount <= 3);
7022 for (; ConvIdx != ConvCount; ++ConvIdx)
7023 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007024 = TryCopyInitialization(S, Args[ConvIdx],
7025 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007026 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007027 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00007028 return;
7029 }
7030
7031 // Fill in the rest of the conversions.
7032 unsigned NumArgsInProto = Proto->getNumArgs();
7033 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7034 if (ArgIdx < NumArgsInProto)
7035 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007036 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007038 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00007039 else
7040 Cand->Conversions[ConvIdx].setEllipsis();
7041 }
7042}
7043
John McCalld3224162010-01-08 00:58:21 +00007044} // end anonymous namespace
7045
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007046/// PrintOverloadCandidates - When overload resolution fails, prints
7047/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007048/// set.
John McCall5c32be02010-08-24 20:38:10 +00007049void OverloadCandidateSet::NoteCandidates(Sema &S,
7050 OverloadCandidateDisplayKind OCD,
7051 Expr **Args, unsigned NumArgs,
7052 const char *Opc,
7053 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007054 // Sort the candidates by viability and position. Sorting directly would
7055 // be prohibitive, so we make a set of pointers and sort those.
7056 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007057 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7058 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007059 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007060 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007061 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007062 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007063 if (Cand->Function || Cand->IsSurrogate)
7064 Cands.push_back(Cand);
7065 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7066 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007067 }
7068 }
7069
John McCallad2587a2010-01-12 00:48:53 +00007070 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007071 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007072
John McCall0d1da222010-01-12 00:44:57 +00007073 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007074
John McCall12f97bc2010-01-08 04:41:39 +00007075 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007076 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007077 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007078 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7079 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007080
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007081 // Set an arbitrary limit on the number of candidate functions we'll spam
7082 // the user with. FIXME: This limit should depend on details of the
7083 // candidate list.
7084 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7085 break;
7086 }
7087 ++CandsShown;
7088
John McCalld3224162010-01-08 00:58:21 +00007089 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007090 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007091 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007092 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007093 else {
7094 assert(Cand->Viable &&
7095 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007096 // Generally we only see ambiguities including viable builtin
7097 // operators if overload resolution got screwed up by an
7098 // ambiguous user-defined conversion.
7099 //
7100 // FIXME: It's quite possible for different conversions to see
7101 // different ambiguities, though.
7102 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007103 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007104 ReportedAmbiguousConversions = true;
7105 }
John McCalld3224162010-01-08 00:58:21 +00007106
John McCall0d1da222010-01-12 00:44:57 +00007107 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007108 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007109 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007110 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007111
7112 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007113 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007114}
7115
Douglas Gregorb491ed32011-02-19 21:32:49 +00007116// [PossiblyAFunctionType] --> [Return]
7117// NonFunctionType --> NonFunctionType
7118// R (A) --> R(A)
7119// R (*)(A) --> R (A)
7120// R (&)(A) --> R (A)
7121// R (S::*)(A) --> R (A)
7122QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7123 QualType Ret = PossiblyAFunctionType;
7124 if (const PointerType *ToTypePtr =
7125 PossiblyAFunctionType->getAs<PointerType>())
7126 Ret = ToTypePtr->getPointeeType();
7127 else if (const ReferenceType *ToTypeRef =
7128 PossiblyAFunctionType->getAs<ReferenceType>())
7129 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007130 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007131 PossiblyAFunctionType->getAs<MemberPointerType>())
7132 Ret = MemTypePtr->getPointeeType();
7133 Ret =
7134 Context.getCanonicalType(Ret).getUnqualifiedType();
7135 return Ret;
7136}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007137
Douglas Gregorb491ed32011-02-19 21:32:49 +00007138// A helper class to help with address of function resolution
7139// - allows us to avoid passing around all those ugly parameters
7140class AddressOfFunctionResolver
7141{
7142 Sema& S;
7143 Expr* SourceExpr;
7144 const QualType& TargetType;
7145 QualType TargetFunctionType; // Extracted function type from target type
7146
7147 bool Complain;
7148 //DeclAccessPair& ResultFunctionAccessPair;
7149 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007150
Douglas Gregorb491ed32011-02-19 21:32:49 +00007151 bool TargetTypeIsNonStaticMemberFunction;
7152 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007153
Douglas Gregorb491ed32011-02-19 21:32:49 +00007154 OverloadExpr::FindResult OvlExprInfo;
7155 OverloadExpr *OvlExpr;
7156 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007157 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007158
Douglas Gregorb491ed32011-02-19 21:32:49 +00007159public:
7160 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7161 const QualType& TargetType, bool Complain)
7162 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7163 Complain(Complain), Context(S.getASTContext()),
7164 TargetTypeIsNonStaticMemberFunction(
7165 !!TargetType->getAs<MemberPointerType>()),
7166 FoundNonTemplateFunction(false),
7167 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7168 OvlExpr(OvlExprInfo.Expression)
7169 {
7170 ExtractUnqualifiedFunctionTypeFromTargetType();
7171
7172 if (!TargetFunctionType->isFunctionType()) {
7173 if (OvlExpr->hasExplicitTemplateArgs()) {
7174 DeclAccessPair dap;
7175 if( FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7176 OvlExpr, false, &dap) ) {
7177 Matches.push_back(std::make_pair(dap,Fn));
7178 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007179 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007180 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007181 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007182
7183 if (OvlExpr->hasExplicitTemplateArgs())
7184 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007185
Douglas Gregorb491ed32011-02-19 21:32:49 +00007186 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7187 // C++ [over.over]p4:
7188 // If more than one function is selected, [...]
7189 if (Matches.size() > 1) {
7190 if (FoundNonTemplateFunction)
7191 EliminateAllTemplateMatches();
7192 else
7193 EliminateAllExceptMostSpecializedTemplate();
7194 }
7195 }
7196 }
7197
7198private:
7199 bool isTargetTypeAFunction() const {
7200 return TargetFunctionType->isFunctionType();
7201 }
7202
7203 // [ToType] [Return]
7204
7205 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7206 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7207 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7208 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7209 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7210 }
7211
7212 // return true if any matching specializations were found
7213 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7214 const DeclAccessPair& CurAccessFunPair) {
7215 if (CXXMethodDecl *Method
7216 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7217 // Skip non-static function templates when converting to pointer, and
7218 // static when converting to member pointer.
7219 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7220 return false;
7221 }
7222 else if (TargetTypeIsNonStaticMemberFunction)
7223 return false;
7224
7225 // C++ [over.over]p2:
7226 // If the name is a function template, template argument deduction is
7227 // done (14.8.2.2), and if the argument deduction succeeds, the
7228 // resulting template argument list is used to generate a single
7229 // function template specialization, which is added to the set of
7230 // overloaded functions considered.
7231 FunctionDecl *Specialization = 0;
7232 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7233 if (Sema::TemplateDeductionResult Result
7234 = S.DeduceTemplateArguments(FunctionTemplate,
7235 &OvlExplicitTemplateArgs,
7236 TargetFunctionType, Specialization,
7237 Info)) {
7238 // FIXME: make a note of the failed deduction for diagnostics.
7239 (void)Result;
7240 return false;
7241 }
7242
7243 // Template argument deduction ensures that we have an exact match.
7244 // This function template specicalization works.
7245 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7246 assert(TargetFunctionType
7247 == Context.getCanonicalType(Specialization->getType()));
7248 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7249 return true;
7250 }
7251
7252 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7253 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007254 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007255 // Skip non-static functions when converting to pointer, and static
7256 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007257 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7258 return false;
7259 }
7260 else if (TargetTypeIsNonStaticMemberFunction)
7261 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007262
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007263 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007264 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007265 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7266 FunDecl->getType()) ||
7267 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007268 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007269 Matches.push_back(std::make_pair(CurAccessFunPair,
7270 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007271 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007272 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007273 }
Mike Stump11289f42009-09-09 15:08:12 +00007274 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007275
7276 return false;
7277 }
7278
7279 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7280 bool Ret = false;
7281
7282 // If the overload expression doesn't have the form of a pointer to
7283 // member, don't try to convert it to a pointer-to-member type.
7284 if (IsInvalidFormOfPointerToMemberFunction())
7285 return false;
7286
7287 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7288 E = OvlExpr->decls_end();
7289 I != E; ++I) {
7290 // Look through any using declarations to find the underlying function.
7291 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7292
7293 // C++ [over.over]p3:
7294 // Non-member functions and static member functions match
7295 // targets of type "pointer-to-function" or "reference-to-function."
7296 // Nonstatic member functions match targets of
7297 // type "pointer-to-member-function."
7298 // Note that according to DR 247, the containing class does not matter.
7299 if (FunctionTemplateDecl *FunctionTemplate
7300 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7301 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7302 Ret = true;
7303 }
7304 // If we have explicit template arguments supplied, skip non-templates.
7305 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7306 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7307 Ret = true;
7308 }
7309 assert(Ret || Matches.empty());
7310 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007311 }
7312
Douglas Gregorb491ed32011-02-19 21:32:49 +00007313 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007314 // [...] and any given function template specialization F1 is
7315 // eliminated if the set contains a second function template
7316 // specialization whose function template is more specialized
7317 // than the function template of F1 according to the partial
7318 // ordering rules of 14.5.5.2.
7319
7320 // The algorithm specified above is quadratic. We instead use a
7321 // two-pass algorithm (similar to the one used to identify the
7322 // best viable function in an overload set) that identifies the
7323 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007324
7325 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7326 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7327 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007328
John McCall58cc69d2010-01-27 01:50:18 +00007329 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007330 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7331 TPOC_Other, 0, SourceExpr->getLocStart(),
7332 S.PDiag(),
7333 S.PDiag(diag::err_addr_ovl_ambiguous)
7334 << Matches[0].second->getDeclName(),
7335 S.PDiag(diag::note_ovl_candidate)
7336 << (unsigned) oc_function_template,
7337 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007338
Douglas Gregorb491ed32011-02-19 21:32:49 +00007339 if (Result != MatchesCopy.end()) {
7340 // Make it the first and only element
7341 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7342 Matches[0].second = cast<FunctionDecl>(*Result);
7343 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007344 }
7345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007346
Douglas Gregorb491ed32011-02-19 21:32:49 +00007347 void EliminateAllTemplateMatches() {
7348 // [...] any function template specializations in the set are
7349 // eliminated if the set also contains a non-template function, [...]
7350 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7351 if (Matches[I].second->getPrimaryTemplate() == 0)
7352 ++I;
7353 else {
7354 Matches[I] = Matches[--N];
7355 Matches.set_size(N);
7356 }
7357 }
7358 }
7359
7360public:
7361 void ComplainNoMatchesFound() const {
7362 assert(Matches.empty());
7363 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7364 << OvlExpr->getName() << TargetFunctionType
7365 << OvlExpr->getSourceRange();
7366 S.NoteAllOverloadCandidates(OvlExpr);
7367 }
7368
7369 bool IsInvalidFormOfPointerToMemberFunction() const {
7370 return TargetTypeIsNonStaticMemberFunction &&
7371 !OvlExprInfo.HasFormOfMemberPointer;
7372 }
7373
7374 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7375 // TODO: Should we condition this on whether any functions might
7376 // have matched, or is it more appropriate to do that in callers?
7377 // TODO: a fixit wouldn't hurt.
7378 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7379 << TargetType << OvlExpr->getSourceRange();
7380 }
7381
7382 void ComplainOfInvalidConversion() const {
7383 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7384 << OvlExpr->getName() << TargetType;
7385 }
7386
7387 void ComplainMultipleMatchesFound() const {
7388 assert(Matches.size() > 1);
7389 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7390 << OvlExpr->getName()
7391 << OvlExpr->getSourceRange();
7392 S.NoteAllOverloadCandidates(OvlExpr);
7393 }
7394
7395 int getNumMatches() const { return Matches.size(); }
7396
7397 FunctionDecl* getMatchingFunctionDecl() const {
7398 if (Matches.size() != 1) return 0;
7399 return Matches[0].second;
7400 }
7401
7402 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7403 if (Matches.size() != 1) return 0;
7404 return &Matches[0].first;
7405 }
7406};
7407
7408/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7409/// an overloaded function (C++ [over.over]), where @p From is an
7410/// expression with overloaded function type and @p ToType is the type
7411/// we're trying to resolve to. For example:
7412///
7413/// @code
7414/// int f(double);
7415/// int f(int);
7416///
7417/// int (*pfd)(double) = f; // selects f(double)
7418/// @endcode
7419///
7420/// This routine returns the resulting FunctionDecl if it could be
7421/// resolved, and NULL otherwise. When @p Complain is true, this
7422/// routine will emit diagnostics if there is an error.
7423FunctionDecl *
7424Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7425 bool Complain,
7426 DeclAccessPair &FoundResult) {
7427
7428 assert(AddressOfExpr->getType() == Context.OverloadTy);
7429
7430 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7431 int NumMatches = Resolver.getNumMatches();
7432 FunctionDecl* Fn = 0;
7433 if ( NumMatches == 0 && Complain) {
7434 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7435 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7436 else
7437 Resolver.ComplainNoMatchesFound();
7438 }
7439 else if (NumMatches > 1 && Complain)
7440 Resolver.ComplainMultipleMatchesFound();
7441 else if (NumMatches == 1) {
7442 Fn = Resolver.getMatchingFunctionDecl();
7443 assert(Fn);
7444 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7445 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007446 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007447 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007448 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007449
7450 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007451}
7452
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007454/// resolve that overloaded function expression down to a single function.
7455///
7456/// This routine can only resolve template-ids that refer to a single function
7457/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007458/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007459/// as described in C++0x [temp.arg.explicit]p3.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007460FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From,
7461 bool Complain,
7462 DeclAccessPair* FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007463 // C++ [over.over]p1:
7464 // [...] [Note: any redundant set of parentheses surrounding the
7465 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007466 // C++ [over.over]p1:
7467 // [...] The overloaded function name can be preceded by the &
7468 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007469 if (From->getType() != Context.OverloadTy)
7470 return 0;
7471
John McCall8d08b9b2010-08-27 09:08:28 +00007472 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007473
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007474 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007475 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007476 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007477
7478 TemplateArgumentListInfo ExplicitTemplateArgs;
7479 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007480
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007481 // Look through all of the overloaded functions, searching for one
7482 // whose type matches exactly.
7483 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007484 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7485 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007486 // C++0x [temp.arg.explicit]p3:
7487 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007488 // where deduction is not done, if a template argument list is
7489 // specified and it, along with any default template arguments,
7490 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007491 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007492 FunctionTemplateDecl *FunctionTemplate
7493 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007494
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007495 // C++ [over.over]p2:
7496 // If the name is a function template, template argument deduction is
7497 // done (14.8.2.2), and if the argument deduction succeeds, the
7498 // resulting template argument list is used to generate a single
7499 // function template specialization, which is added to the set of
7500 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007501 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007502 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007503 if (TemplateDeductionResult Result
7504 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7505 Specialization, Info)) {
7506 // FIXME: make a note of the failed deduction for diagnostics.
7507 (void)Result;
7508 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509 }
7510
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007511 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007512 if (Matched) {
7513 if (FoundResult)
7514 *FoundResult = DeclAccessPair();
7515
7516 if (Complain) {
7517 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7518 << OvlExpr->getName();
7519 NoteAllOverloadCandidates(OvlExpr);
7520 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007521 return 0;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007522 }
7523
7524 if ((Matched = Specialization) && FoundResult)
7525 *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007527
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007528 return Matched;
7529}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007530
Douglas Gregor1beec452011-03-12 01:48:56 +00007531
7532
7533
7534// Resolve and fix an overloaded expression that
7535// can be resolved because it identifies a single function
7536// template specialization
7537// Last three arguments should only be supplied if Complain = true
7538ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
7539 Expr *SrcExpr, bool DoFunctionPointerConverion, bool Complain,
7540 const SourceRange& OpRangeForComplaining,
7541 QualType DestTypeForComplaining,
7542 unsigned DiagIDForComplaining ) {
7543
7544 assert(SrcExpr->getType() == Context.OverloadTy);
7545
7546 DeclAccessPair Found;
7547 Expr* SingleFunctionExpression = 0;
7548 if (FunctionDecl* Fn = ResolveSingleFunctionTemplateSpecialization(
7549 SrcExpr, false, // false -> Complain
7550 &Found)) {
7551 if (!DiagnoseUseOfDecl(Fn, SrcExpr->getSourceRange().getBegin())) {
7552 // mark the expression as resolved to Fn
7553 SingleFunctionExpression = FixOverloadedFunctionReference(SrcExpr,
7554 Found, Fn);
7555 if (DoFunctionPointerConverion)
7556 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression);
7557 }
7558 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007559 if (!SingleFunctionExpression) {
7560 if (Complain) {
7561 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
7562 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7563 << oe->getName() << DestTypeForComplaining << OpRangeForComplaining
7564 << oe->getQualifierLoc().getSourceRange();
7565 NoteAllOverloadCandidates(SrcExpr);
7566 }
7567 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00007568 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007569
Douglas Gregor1beec452011-03-12 01:48:56 +00007570 return SingleFunctionExpression;
7571}
7572
Douglas Gregorcabea402009-09-22 15:41:20 +00007573/// \brief Add a single candidate to the overload set.
7574static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007575 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007576 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007577 Expr **Args, unsigned NumArgs,
7578 OverloadCandidateSet &CandidateSet,
7579 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007580 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007581 if (isa<UsingShadowDecl>(Callee))
7582 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7583
Douglas Gregorcabea402009-09-22 15:41:20 +00007584 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007585 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007586 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007587 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007588 return;
John McCalld14a8642009-11-21 08:51:07 +00007589 }
7590
7591 if (FunctionTemplateDecl *FuncTemplate
7592 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007593 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7594 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007595 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007596 return;
7597 }
7598
7599 assert(false && "unhandled case in overloaded call candidate");
7600
7601 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007602}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007603
Douglas Gregorcabea402009-09-22 15:41:20 +00007604/// \brief Add the overload candidates named by callee and/or found by argument
7605/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007606void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007607 Expr **Args, unsigned NumArgs,
7608 OverloadCandidateSet &CandidateSet,
7609 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007610
7611#ifndef NDEBUG
7612 // Verify that ArgumentDependentLookup is consistent with the rules
7613 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007614 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007615 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7616 // and let Y be the lookup set produced by argument dependent
7617 // lookup (defined as follows). If X contains
7618 //
7619 // -- a declaration of a class member, or
7620 //
7621 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007622 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007623 //
7624 // -- a declaration that is neither a function or a function
7625 // template
7626 //
7627 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007628
John McCall57500772009-12-16 12:17:52 +00007629 if (ULE->requiresADL()) {
7630 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7631 E = ULE->decls_end(); I != E; ++I) {
7632 assert(!(*I)->getDeclContext()->isRecord());
7633 assert(isa<UsingShadowDecl>(*I) ||
7634 !(*I)->getDeclContext()->isFunctionOrMethod());
7635 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007636 }
7637 }
7638#endif
7639
John McCall57500772009-12-16 12:17:52 +00007640 // It would be nice to avoid this copy.
7641 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00007642 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00007643 if (ULE->hasExplicitTemplateArgs()) {
7644 ULE->copyTemplateArgumentsInto(TABuffer);
7645 ExplicitTemplateArgs = &TABuffer;
7646 }
7647
7648 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7649 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007650 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007651 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007652 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007653
John McCall57500772009-12-16 12:17:52 +00007654 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007655 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7656 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007657 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007658 CandidateSet,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007659 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007660}
John McCalld681c392009-12-16 08:11:27 +00007661
7662/// Attempts to recover from a call where no functions were found.
7663///
7664/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007665static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007666BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007667 UnresolvedLookupExpr *ULE,
7668 SourceLocation LParenLoc,
7669 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007670 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007671
7672 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00007673 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00007674
John McCall57500772009-12-16 12:17:52 +00007675 TemplateArgumentListInfo TABuffer;
7676 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7677 if (ULE->hasExplicitTemplateArgs()) {
7678 ULE->copyTemplateArgumentsInto(TABuffer);
7679 ExplicitTemplateArgs = &TABuffer;
7680 }
7681
John McCalld681c392009-12-16 08:11:27 +00007682 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7683 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007684 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007685 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007686
John McCall57500772009-12-16 12:17:52 +00007687 assert(!R.empty() && "lookup results empty despite recovery");
7688
7689 // Build an implicit member call if appropriate. Just drop the
7690 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007691 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007692 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007693 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7694 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007695 else if (ExplicitTemplateArgs)
7696 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7697 else
7698 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7699
7700 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007701 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007702
7703 // This shouldn't cause an infinite loop because we're giving it
7704 // an expression with non-empty lookup results, which should never
7705 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007706 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007707 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007708}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007709
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007710/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007711/// (which eventually refers to the declaration Func) and the call
7712/// arguments Args/NumArgs, attempt to resolve the function call down
7713/// to a specific function. If overload resolution succeeds, returns
7714/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007715/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007716/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007717ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007718Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007719 SourceLocation LParenLoc,
7720 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00007721 SourceLocation RParenLoc,
7722 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00007723#ifndef NDEBUG
7724 if (ULE->requiresADL()) {
7725 // To do ADL, we must have found an unqualified name.
7726 assert(!ULE->getQualifier() && "qualified name with ADL");
7727
7728 // We don't perform ADL for implicit declarations of builtins.
7729 // Verify that this was correctly set up.
7730 FunctionDecl *F;
7731 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7732 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7733 F->getBuiltinID() && F->isImplicit())
7734 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007735
John McCall57500772009-12-16 12:17:52 +00007736 // We don't perform ADL in C.
7737 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7738 }
7739#endif
7740
John McCallbc077cf2010-02-08 23:07:23 +00007741 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007742
John McCall57500772009-12-16 12:17:52 +00007743 // Add the functions denoted by the callee to the set of candidate
7744 // functions, including those from argument-dependent lookup.
7745 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007746
7747 // If we found nothing, try to recover.
7748 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7749 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007750 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007751 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007752 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007753
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007754 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007755 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007756 case OR_Success: {
7757 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00007758 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00007759 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007760 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7761 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007762 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00007763 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7764 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00007765 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007766
7767 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007768 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007769 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007770 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007771 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007772 break;
7773
7774 case OR_Ambiguous:
7775 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007776 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007777 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007778 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007779
7780 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007781 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007782 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7783 << Best->Function->isDeleted()
7784 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007785 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007786 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007787 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7788 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00007789 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007790 }
7791
Douglas Gregorb412e172010-07-25 18:17:45 +00007792 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007793 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007794}
7795
John McCall4c4c1df2010-01-26 03:27:55 +00007796static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007797 return Functions.size() > 1 ||
7798 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7799}
7800
Douglas Gregor084d8552009-03-13 23:49:33 +00007801/// \brief Create a unary operation that may resolve to an overloaded
7802/// operator.
7803///
7804/// \param OpLoc The location of the operator itself (e.g., '*').
7805///
7806/// \param OpcIn The UnaryOperator::Opcode that describes this
7807/// operator.
7808///
7809/// \param Functions The set of non-member functions that will be
7810/// considered by overload resolution. The caller needs to build this
7811/// set based on the context using, e.g.,
7812/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7813/// set should not contain any member functions; those will be added
7814/// by CreateOverloadedUnaryOp().
7815///
7816/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007817ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007818Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7819 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007820 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007821 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007822
7823 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7824 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7825 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007826 // TODO: provide better source location info.
7827 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007828
John McCalle26a8722010-12-04 08:14:53 +00007829 if (Input->getObjectKind() == OK_ObjCProperty)
7830 ConvertPropertyForRValue(Input);
7831
Douglas Gregor084d8552009-03-13 23:49:33 +00007832 Expr *Args[2] = { Input, 0 };
7833 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007834
Douglas Gregor084d8552009-03-13 23:49:33 +00007835 // For post-increment and post-decrement, add the implicit '0' as
7836 // the second argument, so that we know this is a post-increment or
7837 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007838 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007839 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007840 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7841 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007842 NumArgs = 2;
7843 }
7844
7845 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007846 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007847 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00007849 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007850 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007851 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007852
John McCall58cc69d2010-01-27 01:50:18 +00007853 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007854 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007855 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00007856 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007857 /*ADL*/ true, IsOverloaded(Fns),
7858 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007859 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00007860 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00007861 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007862 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007863 OpLoc));
7864 }
7865
7866 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007867 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007868
7869 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007870 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007871
7872 // Add operator candidates that are member functions.
7873 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7874
John McCall4c4c1df2010-01-26 03:27:55 +00007875 // Add candidates from ADL.
7876 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007877 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007878 /*ExplicitTemplateArgs*/ 0,
7879 CandidateSet);
7880
Douglas Gregor084d8552009-03-13 23:49:33 +00007881 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007882 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007883
7884 // Perform overload resolution.
7885 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007886 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007887 case OR_Success: {
7888 // We found a built-in operator or an overloaded operator.
7889 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007890
Douglas Gregor084d8552009-03-13 23:49:33 +00007891 if (FnDecl) {
7892 // We matched an overloaded operator. Build a call to that
7893 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007894
Chandler Carruth30141632011-02-25 19:41:05 +00007895 MarkDeclarationReferenced(OpLoc, FnDecl);
7896
Douglas Gregor084d8552009-03-13 23:49:33 +00007897 // Convert the arguments.
7898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007899 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007900
John McCall16df1e52010-03-30 21:47:33 +00007901 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7902 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007903 return ExprError();
7904 } else {
7905 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007906 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007907 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007908 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007909 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007910 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007911 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007912 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007913 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007914 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007915 }
7916
John McCall4fa0d5f2010-05-06 18:15:07 +00007917 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7918
John McCall7decc9e2010-11-18 06:31:45 +00007919 // Determine the result type.
7920 QualType ResultTy = FnDecl->getResultType();
7921 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7922 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007923
Douglas Gregor084d8552009-03-13 23:49:33 +00007924 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007925 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007926
Eli Friedman030eee42009-11-18 03:58:17 +00007927 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007928 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007929 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007930 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007931
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007932 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007933 FnDecl))
7934 return ExprError();
7935
John McCallb268a282010-08-23 23:25:46 +00007936 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007937 } else {
7938 // We matched a built-in operator. Convert the arguments, then
7939 // break out so that we will build the appropriate built-in
7940 // operator node.
7941 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007942 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007943 return ExprError();
7944
7945 break;
7946 }
7947 }
7948
7949 case OR_No_Viable_Function:
7950 // No viable function; fall through to handling this as a
7951 // built-in operator, which will produce an error message for us.
7952 break;
7953
7954 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007955 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007956 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007957 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007958 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007959 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7960 Args, NumArgs,
7961 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007962 return ExprError();
7963
7964 case OR_Deleted:
7965 Diag(OpLoc, diag::err_ovl_deleted_oper)
7966 << Best->Function->isDeleted()
7967 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007968 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregor084d8552009-03-13 23:49:33 +00007969 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007970 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007971 return ExprError();
7972 }
7973
7974 // Either we found no viable overloaded operator or we matched a
7975 // built-in operator. In either case, fall through to trying to
7976 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007977 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007978}
7979
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007980/// \brief Create a binary operation that may resolve to an overloaded
7981/// operator.
7982///
7983/// \param OpLoc The location of the operator itself (e.g., '+').
7984///
7985/// \param OpcIn The BinaryOperator::Opcode that describes this
7986/// operator.
7987///
7988/// \param Functions The set of non-member functions that will be
7989/// considered by overload resolution. The caller needs to build this
7990/// set based on the context using, e.g.,
7991/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7992/// set should not contain any member functions; those will be added
7993/// by CreateOverloadedBinOp().
7994///
7995/// \param LHS Left-hand argument.
7996/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007997ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007998Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007999 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008000 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008001 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008002 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008003 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008004
8005 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8006 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8007 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8008
8009 // If either side is type-dependent, create an appropriate dependent
8010 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008011 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008012 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008013 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008014 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008015 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008016 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008017 Context.DependentTy,
8018 VK_RValue, OK_Ordinary,
8019 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020
Douglas Gregor5287f092009-11-05 00:51:44 +00008021 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8022 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008023 VK_LValue,
8024 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008025 Context.DependentTy,
8026 Context.DependentTy,
8027 OpLoc));
8028 }
John McCall4c4c1df2010-01-26 03:27:55 +00008029
8030 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008031 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008032 // TODO: provide better source location info in DNLoc component.
8033 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008034 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008035 = UnresolvedLookupExpr::Create(Context, NamingClass,
8036 NestedNameSpecifierLoc(), OpNameInfo,
8037 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008038 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008039 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008040 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008041 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008042 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008043 OpLoc));
8044 }
8045
John McCalle26a8722010-12-04 08:14:53 +00008046 // Always do property rvalue conversions on the RHS.
8047 if (Args[1]->getObjectKind() == OK_ObjCProperty)
8048 ConvertPropertyForRValue(Args[1]);
8049
8050 // The LHS is more complicated.
8051 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8052
8053 // There's a tension for assignment operators between primitive
8054 // property assignment and the overloaded operators.
8055 if (BinaryOperator::isAssignmentOp(Opc)) {
8056 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8057
8058 // Is the property "logically" settable?
8059 bool Settable = (PRE->isExplicitProperty() ||
8060 PRE->getImplicitPropertySetter());
8061
8062 // To avoid gratuitously inventing semantics, use the primitive
8063 // unless it isn't. Thoughts in case we ever really care:
8064 // - If the property isn't logically settable, we have to
8065 // load and hope.
8066 // - If the property is settable and this is simple assignment,
8067 // we really should use the primitive.
8068 // - If the property is settable, then we could try overloading
8069 // on a generic lvalue of the appropriate type; if it works
8070 // out to a builtin candidate, we would do that same operation
8071 // on the property, and otherwise just error.
8072 if (Settable)
8073 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8074 }
8075
8076 ConvertPropertyForRValue(Args[0]);
8077 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008078
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008079 // If this is the assignment operator, we only perform overload resolution
8080 // if the left-hand side is a class or enumeration type. This is actually
8081 // a hack. The standard requires that we do overload resolution between the
8082 // various built-in candidates, but as DR507 points out, this can lead to
8083 // problems. So we do it this way, which pretty much follows what GCC does.
8084 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008085 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008086 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008087
John McCalle26a8722010-12-04 08:14:53 +00008088 // If this is the .* operator, which is not overloadable, just
8089 // create a built-in binary operator.
8090 if (Opc == BO_PtrMemD)
8091 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8092
Douglas Gregor084d8552009-03-13 23:49:33 +00008093 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008094 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008095
8096 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008097 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008098
8099 // Add operator candidates that are member functions.
8100 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8101
John McCall4c4c1df2010-01-26 03:27:55 +00008102 // Add candidates from ADL.
8103 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8104 Args, 2,
8105 /*ExplicitTemplateArgs*/ 0,
8106 CandidateSet);
8107
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008108 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008109 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008110
8111 // Perform overload resolution.
8112 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008113 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008114 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008115 // We found a built-in operator or an overloaded operator.
8116 FunctionDecl *FnDecl = Best->Function;
8117
8118 if (FnDecl) {
8119 // We matched an overloaded operator. Build a call to that
8120 // operator.
8121
Chandler Carruth30141632011-02-25 19:41:05 +00008122 MarkDeclarationReferenced(OpLoc, FnDecl);
8123
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008124 // Convert the arguments.
8125 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008126 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008127 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008128
Chandler Carruth8e543b32010-12-12 08:17:55 +00008129 ExprResult Arg1 =
8130 PerformCopyInitialization(
8131 InitializedEntity::InitializeParameter(Context,
8132 FnDecl->getParamDecl(0)),
8133 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008134 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008135 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008136
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008137 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008138 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008139 return ExprError();
8140
8141 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008142 } else {
8143 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008144 ExprResult Arg0 = PerformCopyInitialization(
8145 InitializedEntity::InitializeParameter(Context,
8146 FnDecl->getParamDecl(0)),
8147 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008148 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008149 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008150
Chandler Carruth8e543b32010-12-12 08:17:55 +00008151 ExprResult Arg1 =
8152 PerformCopyInitialization(
8153 InitializedEntity::InitializeParameter(Context,
8154 FnDecl->getParamDecl(1)),
8155 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008156 if (Arg1.isInvalid())
8157 return ExprError();
8158 Args[0] = LHS = Arg0.takeAs<Expr>();
8159 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008160 }
8161
John McCall4fa0d5f2010-05-06 18:15:07 +00008162 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8163
John McCall7decc9e2010-11-18 06:31:45 +00008164 // Determine the result type.
8165 QualType ResultTy = FnDecl->getResultType();
8166 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8167 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008168
8169 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00008170 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008171
John McCallb268a282010-08-23 23:25:46 +00008172 CXXOperatorCallExpr *TheCall =
8173 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008174 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008175
8176 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008177 FnDecl))
8178 return ExprError();
8179
John McCallb268a282010-08-23 23:25:46 +00008180 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008181 } else {
8182 // We matched a built-in operator. Convert the arguments, then
8183 // break out so that we will build the appropriate built-in
8184 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00008185 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008186 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00008187 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008188 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008189 return ExprError();
8190
8191 break;
8192 }
8193 }
8194
Douglas Gregor66950a32009-09-30 21:46:01 +00008195 case OR_No_Viable_Function: {
8196 // C++ [over.match.oper]p9:
8197 // If the operator is the operator , [...] and there are no
8198 // viable functions, then the operator is assumed to be the
8199 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008200 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008201 break;
8202
Chandler Carruth8e543b32010-12-12 08:17:55 +00008203 // For class as left operand for assignment or compound assigment
8204 // operator do not fall through to handling in built-in, but report that
8205 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008206 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008207 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008208 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008209 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8210 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008211 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008212 } else {
8213 // No viable function; try to create a built-in operation, which will
8214 // produce an error. Then, show the non-viable candidates.
8215 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008216 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008217 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008218 "C++ binary operator overloading is missing candidates!");
8219 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008220 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8221 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008222 return move(Result);
8223 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008224
8225 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008226 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008227 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008228 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008229 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008230 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8231 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008232 return ExprError();
8233
8234 case OR_Deleted:
8235 Diag(OpLoc, diag::err_ovl_deleted_oper)
8236 << Best->Function->isDeleted()
8237 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008238 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008239 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008240 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008241 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008242 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008243
Douglas Gregor66950a32009-09-30 21:46:01 +00008244 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008245 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008246}
8247
John McCalldadc5752010-08-24 06:29:42 +00008248ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008249Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8250 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008251 Expr *Base, Expr *Idx) {
8252 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008253 DeclarationName OpName =
8254 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8255
8256 // If either side is type-dependent, create an appropriate dependent
8257 // expression.
8258 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8259
John McCall58cc69d2010-01-27 01:50:18 +00008260 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008261 // CHECKME: no 'operator' keyword?
8262 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8263 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008264 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008265 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008266 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008267 /*ADL*/ true, /*Overloaded*/ false,
8268 UnresolvedSetIterator(),
8269 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008270 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008271
Sebastian Redladba46e2009-10-29 20:17:01 +00008272 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8273 Args, 2,
8274 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008275 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008276 RLoc));
8277 }
8278
John McCalle26a8722010-12-04 08:14:53 +00008279 if (Args[0]->getObjectKind() == OK_ObjCProperty)
8280 ConvertPropertyForRValue(Args[0]);
8281 if (Args[1]->getObjectKind() == OK_ObjCProperty)
8282 ConvertPropertyForRValue(Args[1]);
8283
Sebastian Redladba46e2009-10-29 20:17:01 +00008284 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008285 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008286
8287 // Subscript can only be overloaded as a member function.
8288
8289 // Add operator candidates that are member functions.
8290 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8291
8292 // Add builtin operator candidates.
8293 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8294
8295 // Perform overload resolution.
8296 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008297 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008298 case OR_Success: {
8299 // We found a built-in operator or an overloaded operator.
8300 FunctionDecl *FnDecl = Best->Function;
8301
8302 if (FnDecl) {
8303 // We matched an overloaded operator. Build a call to that
8304 // operator.
8305
Chandler Carruth30141632011-02-25 19:41:05 +00008306 MarkDeclarationReferenced(LLoc, FnDecl);
8307
John McCalla0296f72010-03-19 07:35:19 +00008308 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008309 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008310
Sebastian Redladba46e2009-10-29 20:17:01 +00008311 // Convert the arguments.
8312 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008313 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008314 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00008315 return ExprError();
8316
Anders Carlssona68e51e2010-01-29 18:37:50 +00008317 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008318 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008319 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008320 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008321 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008322 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008323 Owned(Args[1]));
8324 if (InputInit.isInvalid())
8325 return ExprError();
8326
8327 Args[1] = InputInit.takeAs<Expr>();
8328
Sebastian Redladba46e2009-10-29 20:17:01 +00008329 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008330 QualType ResultTy = FnDecl->getResultType();
8331 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8332 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008333
8334 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00008335 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008336
John McCallb268a282010-08-23 23:25:46 +00008337 CXXOperatorCallExpr *TheCall =
8338 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
8339 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008340 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008341
John McCallb268a282010-08-23 23:25:46 +00008342 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008343 FnDecl))
8344 return ExprError();
8345
John McCallb268a282010-08-23 23:25:46 +00008346 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008347 } else {
8348 // We matched a built-in operator. Convert the arguments, then
8349 // break out so that we will build the appropriate built-in
8350 // operator node.
8351 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008352 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00008353 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008354 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00008355 return ExprError();
8356
8357 break;
8358 }
8359 }
8360
8361 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008362 if (CandidateSet.empty())
8363 Diag(LLoc, diag::err_ovl_no_oper)
8364 << Args[0]->getType() << /*subscript*/ 0
8365 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8366 else
8367 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8368 << Args[0]->getType()
8369 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008370 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8371 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008372 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008373 }
8374
8375 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008376 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008377 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008378 << Args[0]->getType() << Args[1]->getType()
8379 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008380 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8381 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008382 return ExprError();
8383
8384 case OR_Deleted:
8385 Diag(LLoc, diag::err_ovl_deleted_oper)
8386 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008387 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00008388 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008389 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8390 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008391 return ExprError();
8392 }
8393
8394 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008395 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008396}
8397
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008398/// BuildCallToMemberFunction - Build a call to a member
8399/// function. MemExpr is the expression that refers to the member
8400/// function (and includes the object parameter), Args/NumArgs are the
8401/// arguments to the function call (not including the object
8402/// parameter). The caller needs to validate that the member
8403/// expression refers to a member function or an overloaded member
8404/// function.
John McCalldadc5752010-08-24 06:29:42 +00008405ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008406Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8407 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008408 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008409 // Dig out the member expression. This holds both the object
8410 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008411 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008412
John McCall10eae182009-11-30 22:42:35 +00008413 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008414 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008415 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008416 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008417 if (isa<MemberExpr>(NakedMemExpr)) {
8418 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008419 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008420 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008421 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008422 } else {
8423 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008424 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008425
John McCall6e9f8f62009-12-03 04:06:58 +00008426 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008427 Expr::Classification ObjectClassification
8428 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8429 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008430
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008431 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008432 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008433
John McCall2d74de92009-12-01 22:10:20 +00008434 // FIXME: avoid copy.
8435 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8436 if (UnresExpr->hasExplicitTemplateArgs()) {
8437 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8438 TemplateArgs = &TemplateArgsBuffer;
8439 }
8440
John McCall10eae182009-11-30 22:42:35 +00008441 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8442 E = UnresExpr->decls_end(); I != E; ++I) {
8443
John McCall6e9f8f62009-12-03 04:06:58 +00008444 NamedDecl *Func = *I;
8445 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8446 if (isa<UsingShadowDecl>(Func))
8447 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8448
Douglas Gregor02824322011-01-26 19:30:28 +00008449
Francois Pichet64225792011-01-18 05:04:39 +00008450 // Microsoft supports direct constructor calls.
8451 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8452 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8453 CandidateSet);
8454 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008455 // If explicit template arguments were provided, we can't call a
8456 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008457 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008458 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008459
John McCalla0296f72010-03-19 07:35:19 +00008460 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008461 ObjectClassification,
8462 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00008463 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008464 } else {
John McCall10eae182009-11-30 22:42:35 +00008465 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008466 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008467 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00008468 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008469 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008470 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008471 }
Mike Stump11289f42009-09-09 15:08:12 +00008472
John McCall10eae182009-11-30 22:42:35 +00008473 DeclarationName DeclName = UnresExpr->getMemberName();
8474
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008475 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008476 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008477 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008478 case OR_Success:
8479 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00008480 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00008481 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008482 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008483 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008484 break;
8485
8486 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008487 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008488 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008489 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008490 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008491 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008492 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008493
8494 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008495 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008496 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008497 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008498 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008499 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008500
8501 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008502 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008503 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008504 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008505 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008506 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008507 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008508 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008509 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008510 }
8511
John McCall16df1e52010-03-30 21:47:33 +00008512 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008513
John McCall2d74de92009-12-01 22:10:20 +00008514 // If overload resolution picked a static member, build a
8515 // non-member call based on that function.
8516 if (Method->isStatic()) {
8517 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8518 Args, NumArgs, RParenLoc);
8519 }
8520
John McCall10eae182009-11-30 22:42:35 +00008521 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008522 }
8523
John McCall7decc9e2010-11-18 06:31:45 +00008524 QualType ResultType = Method->getResultType();
8525 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8526 ResultType = ResultType.getNonLValueExprType(Context);
8527
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008528 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008529 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00008530 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008531 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008532
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008533 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008534 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008535 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008536 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008537
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008538 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008539 // We only need to do this if there was actually an overload; otherwise
8540 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008541 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008542 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008543 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8544 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008545 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008546 MemExpr->setBase(ObjectArg);
8547
8548 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008549 const FunctionProtoType *Proto =
8550 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008551 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008552 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008553 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008554
John McCallb268a282010-08-23 23:25:46 +00008555 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008556 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008557
John McCallb268a282010-08-23 23:25:46 +00008558 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008559}
8560
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008561/// BuildCallToObjectOfClassType - Build a call to an object of class
8562/// type (C++ [over.call.object]), which can end up invoking an
8563/// overloaded function call operator (@c operator()) or performing a
8564/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008565ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008566Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008567 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008568 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008569 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008570 if (Object->getObjectKind() == OK_ObjCProperty)
8571 ConvertPropertyForRValue(Object);
8572
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008573 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008574 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008575
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008576 // C++ [over.call.object]p1:
8577 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008578 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008579 // candidate functions includes at least the function call
8580 // operators of T. The function call operators of T are obtained by
8581 // ordinary lookup of the name operator() in the context of
8582 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008583 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008584 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008585
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008586 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008587 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008588 << Object->getSourceRange()))
8589 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008590
John McCall27b18f82009-11-17 02:14:36 +00008591 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8592 LookupQualifiedName(R, Record->getDecl());
8593 R.suppressDiagnostics();
8594
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008595 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008596 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008597 AddMethodCandidate(Oper.getPair(), Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00008598 Object->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008599 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008601
Douglas Gregorab7897a2008-11-19 22:57:39 +00008602 // C++ [over.call.object]p2:
8603 // In addition, for each conversion function declared in T of the
8604 // form
8605 //
8606 // operator conversion-type-id () cv-qualifier;
8607 //
8608 // where cv-qualifier is the same cv-qualification as, or a
8609 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008610 // denotes the type "pointer to function of (P1,...,Pn) returning
8611 // R", or the type "reference to pointer to function of
8612 // (P1,...,Pn) returning R", or the type "reference to function
8613 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008614 // is also considered as a candidate function. Similarly,
8615 // surrogate call functions are added to the set of candidate
8616 // functions for each conversion function declared in an
8617 // accessible base class provided the function is not hidden
8618 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008619 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008620 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008621 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008622 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008623 NamedDecl *D = *I;
8624 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8625 if (isa<UsingShadowDecl>(D))
8626 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008627
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008628 // Skip over templated conversion functions; they aren't
8629 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008630 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008631 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008632
John McCall6e9f8f62009-12-03 04:06:58 +00008633 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008634
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008635 // Strip the reference type (if any) and then the pointer type (if
8636 // any) to get down to what might be a function type.
8637 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8638 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8639 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008640
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008641 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008642 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00008643 Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008644 }
Mike Stump11289f42009-09-09 15:08:12 +00008645
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008646 // Perform overload resolution.
8647 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008648 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8649 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008650 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008651 // Overload resolution succeeded; we'll build the appropriate call
8652 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008653 break;
8654
8655 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008656 if (CandidateSet.empty())
8657 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8658 << Object->getType() << /*call*/ 1
8659 << Object->getSourceRange();
8660 else
8661 Diag(Object->getSourceRange().getBegin(),
8662 diag::err_ovl_no_viable_object_call)
8663 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008664 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008665 break;
8666
8667 case OR_Ambiguous:
8668 Diag(Object->getSourceRange().getBegin(),
8669 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008670 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008671 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008672 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008673
8674 case OR_Deleted:
8675 Diag(Object->getSourceRange().getBegin(),
8676 diag::err_ovl_deleted_object_call)
8677 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008678 << Object->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008679 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008680 << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008681 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008682 break;
Mike Stump11289f42009-09-09 15:08:12 +00008683 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008684
Douglas Gregorb412e172010-07-25 18:17:45 +00008685 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008686 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008687
Douglas Gregorab7897a2008-11-19 22:57:39 +00008688 if (Best->Function == 0) {
8689 // Since there is no function declaration, this is one of the
8690 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008691 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008692 = cast<CXXConversionDecl>(
8693 Best->Conversions[0].UserDefined.ConversionFunction);
8694
John McCalla0296f72010-03-19 07:35:19 +00008695 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008696 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008697
Douglas Gregorab7897a2008-11-19 22:57:39 +00008698 // We selected one of the surrogate functions that converts the
8699 // object parameter to a function pointer. Perform the conversion
8700 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008701
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008702 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008703 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008704 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8705 if (Call.isInvalid())
8706 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008707
Douglas Gregor668443e2011-01-20 00:18:04 +00008708 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008709 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008710 }
8711
Chandler Carruth30141632011-02-25 19:41:05 +00008712 MarkDeclarationReferenced(LParenLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00008713 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008714 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008715
Douglas Gregorab7897a2008-11-19 22:57:39 +00008716 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8717 // that calls this method, using Object for the implicit object
8718 // parameter and passing along the remaining arguments.
8719 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008720 const FunctionProtoType *Proto =
8721 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008722
8723 unsigned NumArgsInProto = Proto->getNumArgs();
8724 unsigned NumArgsToCheck = NumArgs;
8725
8726 // Build the full argument list for the method call (the
8727 // implicit object parameter is placed at the beginning of the
8728 // list).
8729 Expr **MethodArgs;
8730 if (NumArgs < NumArgsInProto) {
8731 NumArgsToCheck = NumArgsInProto;
8732 MethodArgs = new Expr*[NumArgsInProto + 1];
8733 } else {
8734 MethodArgs = new Expr*[NumArgs + 1];
8735 }
8736 MethodArgs[0] = Object;
8737 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8738 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008739
John McCall7decc9e2010-11-18 06:31:45 +00008740 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008741
8742 // Once we've built TheCall, all of the expressions are properly
8743 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008744 QualType ResultTy = Method->getResultType();
8745 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8746 ResultTy = ResultTy.getNonLValueExprType(Context);
8747
John McCallb268a282010-08-23 23:25:46 +00008748 CXXOperatorCallExpr *TheCall =
8749 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8750 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008751 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008752 delete [] MethodArgs;
8753
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008754 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008755 Method))
8756 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008757
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008758 // We may have default arguments. If so, we need to allocate more
8759 // slots in the call for them.
8760 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008761 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008762 else if (NumArgs > NumArgsInProto)
8763 NumArgsToCheck = NumArgsInProto;
8764
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008765 bool IsError = false;
8766
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008767 // Initialize the implicit object parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008768 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008769 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008770 TheCall->setArg(0, Object);
8771
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008772
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008773 // Check the argument types.
8774 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008775 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008776 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008777 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008778
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008779 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008780
John McCalldadc5752010-08-24 06:29:42 +00008781 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008782 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008783 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008784 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008785 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008786
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008787 IsError |= InputInit.isInvalid();
8788 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008789 } else {
John McCalldadc5752010-08-24 06:29:42 +00008790 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008791 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8792 if (DefArg.isInvalid()) {
8793 IsError = true;
8794 break;
8795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008796
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008797 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008798 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008799
8800 TheCall->setArg(i + 1, Arg);
8801 }
8802
8803 // If this is a variadic call, handle args passed through "...".
8804 if (Proto->isVariadic()) {
8805 // Promote the arguments (C99 6.5.2.2p7).
8806 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8807 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008808 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008809 TheCall->setArg(i + 1, Arg);
8810 }
8811 }
8812
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008813 if (IsError) return true;
8814
John McCallb268a282010-08-23 23:25:46 +00008815 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008816 return true;
8817
John McCalle172be52010-08-24 06:09:16 +00008818 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008819}
8820
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008821/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008822/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008823/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008824ExprResult
John McCallb268a282010-08-23 23:25:46 +00008825Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008826 assert(Base->getType()->isRecordType() &&
8827 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008828
John McCalle26a8722010-12-04 08:14:53 +00008829 if (Base->getObjectKind() == OK_ObjCProperty)
8830 ConvertPropertyForRValue(Base);
8831
John McCallbc077cf2010-02-08 23:07:23 +00008832 SourceLocation Loc = Base->getExprLoc();
8833
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008834 // C++ [over.ref]p1:
8835 //
8836 // [...] An expression x->m is interpreted as (x.operator->())->m
8837 // for a class object x of type T if T::operator->() exists and if
8838 // the operator is selected as the best match function by the
8839 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008840 DeclarationName OpName =
8841 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008842 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008843 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008844
John McCallbc077cf2010-02-08 23:07:23 +00008845 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008846 PDiag(diag::err_typecheck_incomplete_tag)
8847 << Base->getSourceRange()))
8848 return ExprError();
8849
John McCall27b18f82009-11-17 02:14:36 +00008850 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8851 LookupQualifiedName(R, BaseRecord->getDecl());
8852 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008853
8854 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008855 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00008856 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8857 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008858 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008859
8860 // Perform overload resolution.
8861 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008862 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008863 case OR_Success:
8864 // Overload resolution succeeded; we'll build the call below.
8865 break;
8866
8867 case OR_No_Viable_Function:
8868 if (CandidateSet.empty())
8869 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008870 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008871 else
8872 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008873 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008874 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008875 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008876
8877 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008878 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8879 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008880 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008881 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008882
8883 case OR_Deleted:
8884 Diag(OpLoc, diag::err_ovl_deleted_oper)
8885 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008886 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008887 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008888 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008889 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008890 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008891 }
8892
Chandler Carruth30141632011-02-25 19:41:05 +00008893 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00008894 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008895 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008896
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008897 // Convert the object parameter.
8898 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008899 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8900 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008901 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008902
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008903 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008904 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008905
John McCall7decc9e2010-11-18 06:31:45 +00008906 QualType ResultTy = Method->getResultType();
8907 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8908 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008909 CXXOperatorCallExpr *TheCall =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008910 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008911 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008912
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008913 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008914 Method))
8915 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008916 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008917}
8918
Douglas Gregorcd695e52008-11-10 20:40:00 +00008919/// FixOverloadedFunctionReference - E is an expression that refers to
8920/// a C++ overloaded function (possibly with some parentheses and
8921/// perhaps a '&' around it). We have resolved the overloaded function
8922/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008923/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008924Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008925 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008926 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008927 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8928 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008929 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008930 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008931
Douglas Gregor51c538b2009-11-20 19:42:02 +00008932 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008933 }
8934
Douglas Gregor51c538b2009-11-20 19:42:02 +00008935 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008936 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8937 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008938 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008939 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008940 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008941 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008942 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008943 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008944
8945 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00008946 ICE->getCastKind(),
8947 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008948 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008949 }
8950
Douglas Gregor51c538b2009-11-20 19:42:02 +00008951 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008952 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008953 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008954 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8955 if (Method->isStatic()) {
8956 // Do nothing: static member functions aren't any different
8957 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008958 } else {
John McCalle66edc12009-11-24 19:00:30 +00008959 // Fix the sub expression, which really has to be an
8960 // UnresolvedLookupExpr holding an overloaded member function
8961 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008962 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8963 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008964 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008965 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008966
John McCalld14a8642009-11-21 08:51:07 +00008967 assert(isa<DeclRefExpr>(SubExpr)
8968 && "fixed to something other than a decl ref");
8969 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8970 && "fixed to a member ref with no nested name qualifier");
8971
8972 // We have taken the address of a pointer to member
8973 // function. Perform the computation here so that we get the
8974 // appropriate pointer to member type.
8975 QualType ClassType
8976 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8977 QualType MemPtrType
8978 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8979
John McCall7decc9e2010-11-18 06:31:45 +00008980 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8981 VK_RValue, OK_Ordinary,
8982 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008983 }
8984 }
John McCall16df1e52010-03-30 21:47:33 +00008985 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8986 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008987 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008988 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008989
John McCalle3027922010-08-25 11:45:40 +00008990 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008991 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008992 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008993 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008994 }
John McCalld14a8642009-11-21 08:51:07 +00008995
8996 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008997 // FIXME: avoid copy.
8998 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008999 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009000 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9001 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009002 }
9003
John McCalld14a8642009-11-21 08:51:07 +00009004 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009005 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009006 Fn,
9007 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009008 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009009 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00009010 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009011 }
9012
John McCall10eae182009-11-30 22:42:35 +00009013 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009014 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009015 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9016 if (MemExpr->hasExplicitTemplateArgs()) {
9017 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9018 TemplateArgs = &TemplateArgsBuffer;
9019 }
John McCall6b51f282009-11-23 01:53:49 +00009020
John McCall2d74de92009-12-01 22:10:20 +00009021 Expr *Base;
9022
John McCall7decc9e2010-11-18 06:31:45 +00009023 // If we're filling in a static method where we used to have an
9024 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009025 if (MemExpr->isImplicitAccess()) {
9026 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9027 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009028 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009029 Fn,
9030 MemExpr->getMemberLoc(),
9031 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009032 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00009033 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009034 } else {
9035 SourceLocation Loc = MemExpr->getMemberLoc();
9036 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009037 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009038 Base = new (Context) CXXThisExpr(Loc,
9039 MemExpr->getBaseType(),
9040 /*isImplicit=*/true);
9041 }
John McCall2d74de92009-12-01 22:10:20 +00009042 } else
John McCallc3007a22010-10-26 07:05:15 +00009043 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009044
9045 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009046 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009047 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009048 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009049 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009050 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009051 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009052 Fn->getType(),
9053 cast<CXXMethodDecl>(Fn)->isStatic()
9054 ? VK_LValue : VK_RValue,
9055 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009056 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009057
John McCallc3007a22010-10-26 07:05:15 +00009058 llvm_unreachable("Invalid reference to overloaded function");
9059 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009060}
9061
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009062ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009063 DeclAccessPair Found,
9064 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009065 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009066}
9067
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009068} // end namespace clang