blob: 5b444c14d6fc2e5676f73686d353f9ccd9319463 [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;
Douglas Gregor980fb162010-04-29 18:24:40 +00001061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062
Chandler Carruthffce2452011-03-29 08:08:18 +00001063 // Check if the "from" expression is taking the address of an overloaded
1064 // function and recompute the FromType accordingly. Take advantage of the
1065 // fact that non-static member functions *must* have such an address-of
1066 // expression.
1067 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1068 if (Method && !Method->isStatic()) {
1069 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1070 "Non-unary operator on non-static member address");
1071 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1072 == UO_AddrOf &&
1073 "Non-address-of operator on non-static member address");
1074 const Type *ClassType
1075 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1076 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001077 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1078 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1079 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001080 "Non-address-of operator for overloaded function expression");
1081 FromType = S.Context.getPointerType(FromType);
1082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083
Douglas Gregor980fb162010-04-29 18:24:40 +00001084 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001085 assert(S.Context.hasSameType(
1086 FromType,
1087 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001088 } else {
1089 return false;
1090 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001093 // An lvalue (3.10) of a non-function, non-array type T can be
1094 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001095 bool argIsLValue = From->isLValue();
1096 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001097 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001098 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100
1101 // If T is a non-class type, the type of the rvalue is the
1102 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001103 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1104 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001105 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001106 } else if (FromType->isArrayType()) {
1107 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001108 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001109
1110 // An lvalue or rvalue of type "array of N T" or "array of unknown
1111 // bound of T" can be converted to an rvalue of type "pointer to
1112 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001113 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001114
John McCall5c32be02010-08-24 20:38:10 +00001115 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001116 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001117 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001118
1119 // For the purpose of ranking in overload resolution
1120 // (13.3.3.1.1), this conversion is considered an
1121 // array-to-pointer conversion followed by a qualification
1122 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001123 SCS.Second = ICK_Identity;
1124 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001125 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001126 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127 }
John McCall086a4642010-11-24 05:12:34 +00001128 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001129 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001130 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001131
1132 // An lvalue of function type T can be converted to an rvalue of
1133 // type "pointer to T." The result is a pointer to the
1134 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001135 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001136 } else {
1137 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001138 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001139 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001140 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001141
1142 // The second conversion can be an integral promotion, floating
1143 // point promotion, integral conversion, floating point conversion,
1144 // floating-integral conversion, pointer conversion,
1145 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001146 // For overloading in C, this can also be a "compatible-type"
1147 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001148 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001149 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001150 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001151 // The unqualified versions of the types are the same: there's no
1152 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001153 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001154 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001155 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001156 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001157 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001158 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001159 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001160 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001161 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001162 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001163 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001164 SCS.Second = ICK_Complex_Promotion;
1165 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001166 } else if (ToType->isBooleanType() &&
1167 (FromType->isArithmeticType() ||
1168 FromType->isAnyPointerType() ||
1169 FromType->isBlockPointerType() ||
1170 FromType->isMemberPointerType() ||
1171 FromType->isNullPtrType())) {
1172 // Boolean conversions (C++ 4.12).
1173 SCS.Second = ICK_Boolean_Conversion;
1174 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001175 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001176 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001177 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001178 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001179 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001180 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001181 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001182 SCS.Second = ICK_Complex_Conversion;
1183 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001184 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1185 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001186 // Complex-real conversions (C99 6.3.1.7)
1187 SCS.Second = ICK_Complex_Real;
1188 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001189 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001190 // Floating point conversions (C++ 4.8).
1191 SCS.Second = ICK_Floating_Conversion;
1192 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001193 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001194 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001195 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001196 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001197 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001198 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001199 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001200 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1201 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001202 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1203 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001204 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001205 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001206 SCS.IncompatibleObjC = IncompatibleObjC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001207 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001208 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001209 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001210 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001211 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001212 SCS.Second = SecondICK;
1213 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001214 } else if (!S.getLangOptions().CPlusPlus &&
1215 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001216 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001217 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001218 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001219 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001220 // Treat a conversion that strips "noreturn" as an identity conversion.
1221 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001222 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1223 InOverloadResolution,
1224 SCS, CStyle)) {
1225 SCS.Second = ICK_TransparentUnionConversion;
1226 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001227 } else {
1228 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001229 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001230 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001231 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001232
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001233 QualType CanonFrom;
1234 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001236 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001237 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001238 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001239 CanonFrom = S.Context.getCanonicalType(FromType);
1240 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001241 } else {
1242 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001243 SCS.Third = ICK_Identity;
1244
Mike Stump11289f42009-09-09 15:08:12 +00001245 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001246 // [...] Any difference in top-level cv-qualification is
1247 // subsumed by the initialization itself and does not constitute
1248 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001249 CanonFrom = S.Context.getCanonicalType(FromType);
1250 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001252 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001253 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1254 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001255 FromType = ToType;
1256 CanonFrom = CanonTo;
1257 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001259 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001260
1261 // If we have not converted the argument type to the parameter type,
1262 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001263 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001264 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001265
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001266 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001267}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001268
1269static bool
1270IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1271 QualType &ToType,
1272 bool InOverloadResolution,
1273 StandardConversionSequence &SCS,
1274 bool CStyle) {
1275
1276 const RecordType *UT = ToType->getAsUnionType();
1277 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1278 return false;
1279 // The field to initialize within the transparent union.
1280 RecordDecl *UD = UT->getDecl();
1281 // It's compatible if the expression matches any of the fields.
1282 for (RecordDecl::field_iterator it = UD->field_begin(),
1283 itend = UD->field_end();
1284 it != itend; ++it) {
1285 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, CStyle)) {
1286 ToType = it->getType();
1287 return true;
1288 }
1289 }
1290 return false;
1291}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001292
1293/// IsIntegralPromotion - Determines whether the conversion from the
1294/// expression From (whose potentially-adjusted type is FromType) to
1295/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1296/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001297bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001298 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001299 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001300 if (!To) {
1301 return false;
1302 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001303
1304 // An rvalue of type char, signed char, unsigned char, short int, or
1305 // unsigned short int can be converted to an rvalue of type int if
1306 // int can represent all the values of the source type; otherwise,
1307 // the source rvalue can be converted to an rvalue of type unsigned
1308 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001309 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1310 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001311 if (// We can promote any signed, promotable integer type to an int
1312 (FromType->isSignedIntegerType() ||
1313 // We can promote any unsigned integer type whose size is
1314 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001315 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001316 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001317 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001318 }
1319
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001320 return To->getKind() == BuiltinType::UInt;
1321 }
1322
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001323 // C++0x [conv.prom]p3:
1324 // A prvalue of an unscoped enumeration type whose underlying type is not
1325 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1326 // following types that can represent all the values of the enumeration
1327 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1328 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001329 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001330 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001331 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332 // with lowest integer conversion rank (4.13) greater than the rank of long
1333 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001334 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001335 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1336 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1337 // provided for a scoped enumeration.
1338 if (FromEnumType->getDecl()->isScoped())
1339 return false;
1340
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001341 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001342 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001343 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001344 return Context.hasSameUnqualifiedType(ToType,
1345 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001346 }
John McCall56774992009-12-09 09:09:27 +00001347
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001348 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001349 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1350 // to an rvalue a prvalue of the first of the following types that can
1351 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001352 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001354 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001356 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001358 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001359 // Determine whether the type we're converting from is signed or
1360 // unsigned.
1361 bool FromIsSigned;
1362 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
John McCall56774992009-12-09 09:09:27 +00001364 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1365 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001366
1367 // The types we'll try to promote to, in the appropriate
1368 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001369 QualType PromoteTypes[6] = {
1370 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001371 Context.LongTy, Context.UnsignedLongTy ,
1372 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001373 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001374 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001375 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1376 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001377 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001378 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1379 // We found the type that we can promote to. If this is the
1380 // type we wanted, we have a promotion. Otherwise, no
1381 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001382 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001383 }
1384 }
1385 }
1386
1387 // An rvalue for an integral bit-field (9.6) can be converted to an
1388 // rvalue of type int if int can represent all the values of the
1389 // bit-field; otherwise, it can be converted to unsigned int if
1390 // unsigned int can represent all the values of the bit-field. If
1391 // the bit-field is larger yet, no integral promotion applies to
1392 // it. If the bit-field has an enumerated type, it is treated as any
1393 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001394 // FIXME: We should delay checking of bit-fields until we actually perform the
1395 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001396 using llvm::APSInt;
1397 if (From)
1398 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001399 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001400 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001401 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1402 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1403 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001405 // Are we promoting to an int from a bitfield that fits in an int?
1406 if (BitWidth < ToSize ||
1407 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1408 return To->getKind() == BuiltinType::Int;
1409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001411 // Are we promoting to an unsigned int from an unsigned bitfield
1412 // that fits into an unsigned int?
1413 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1414 return To->getKind() == BuiltinType::UInt;
1415 }
Mike Stump11289f42009-09-09 15:08:12 +00001416
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001417 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001418 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001419 }
Mike Stump11289f42009-09-09 15:08:12 +00001420
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421 // An rvalue of type bool can be converted to an rvalue of type int,
1422 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001423 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001425 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001426
1427 return false;
1428}
1429
1430/// IsFloatingPointPromotion - Determines whether the conversion from
1431/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1432/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001433bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001434 /// An rvalue of type float can be converted to an rvalue of type
1435 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001436 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1437 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001438 if (FromBuiltin->getKind() == BuiltinType::Float &&
1439 ToBuiltin->getKind() == BuiltinType::Double)
1440 return true;
1441
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001442 // C99 6.3.1.5p1:
1443 // When a float is promoted to double or long double, or a
1444 // double is promoted to long double [...].
1445 if (!getLangOptions().CPlusPlus &&
1446 (FromBuiltin->getKind() == BuiltinType::Float ||
1447 FromBuiltin->getKind() == BuiltinType::Double) &&
1448 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1449 return true;
1450 }
1451
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001452 return false;
1453}
1454
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001455/// \brief Determine if a conversion is a complex promotion.
1456///
1457/// A complex promotion is defined as a complex -> complex conversion
1458/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001459/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001460bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001461 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001462 if (!FromComplex)
1463 return false;
1464
John McCall9dd450b2009-09-21 23:43:11 +00001465 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001466 if (!ToComplex)
1467 return false;
1468
1469 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001470 ToComplex->getElementType()) ||
1471 IsIntegralPromotion(0, FromComplex->getElementType(),
1472 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001473}
1474
Douglas Gregor237f96c2008-11-26 23:31:11 +00001475/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1476/// the pointer type FromPtr to a pointer to type ToPointee, with the
1477/// same type qualifiers as FromPtr has on its pointee type. ToType,
1478/// if non-empty, will be a pointer to ToType that may or may not have
1479/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001480static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001481BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001482 QualType ToPointee, QualType ToType,
1483 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001484 assert((FromPtr->getTypeClass() == Type::Pointer ||
1485 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1486 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001488 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1489 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1490 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001491
1492 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001493 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001494 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001495 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001496
1497 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001498 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001499 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001500 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001501 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001502
1503 // Build a pointer to ToPointee. It has the right qualifiers
1504 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001505 if (isa<ObjCObjectPointerType>(ToType))
1506 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001507 return Context.getPointerType(ToPointee);
1508 }
1509
1510 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001511 QualType QualifiedCanonToPointee
1512 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001513
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001514 if (isa<ObjCObjectPointerType>(ToType))
1515 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1516 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001517}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518
Mike Stump11289f42009-09-09 15:08:12 +00001519static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001520 bool InOverloadResolution,
1521 ASTContext &Context) {
1522 // Handle value-dependent integral null pointer constants correctly.
1523 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1524 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001525 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001526 return !InOverloadResolution;
1527
Douglas Gregor56751b52009-09-25 04:25:58 +00001528 return Expr->isNullPointerConstant(Context,
1529 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1530 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001531}
Mike Stump11289f42009-09-09 15:08:12 +00001532
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533/// IsPointerConversion - Determines whether the conversion of the
1534/// expression From, which has the (possibly adjusted) type FromType,
1535/// can be converted to the type ToType via a pointer conversion (C++
1536/// 4.10). If so, returns true and places the converted type (that
1537/// might differ from ToType in its cv-qualifiers at some level) into
1538/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001539///
Douglas Gregora29dc052008-11-27 01:19:21 +00001540/// This routine also supports conversions to and from block pointers
1541/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1542/// pointers to interfaces. FIXME: Once we've determined the
1543/// appropriate overloading rules for Objective-C, we may want to
1544/// split the Objective-C checks into a different routine; however,
1545/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001546/// conversions, so for now they live here. IncompatibleObjC will be
1547/// set if the conversion is an allowed Objective-C conversion that
1548/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001550 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001551 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001552 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001553 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001554 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1555 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001556 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001557
Mike Stump11289f42009-09-09 15:08:12 +00001558 // Conversion from a null pointer constant to any Objective-C pointer type.
1559 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001560 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001561 ConvertedType = ToType;
1562 return true;
1563 }
1564
Douglas Gregor231d1c62008-11-27 00:15:41 +00001565 // Blocks: Block pointers can be converted to void*.
1566 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001567 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001568 ConvertedType = ToType;
1569 return true;
1570 }
1571 // Blocks: A null pointer constant can be converted to a block
1572 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001573 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001574 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001575 ConvertedType = ToType;
1576 return true;
1577 }
1578
Sebastian Redl576fd422009-05-10 18:38:11 +00001579 // If the left-hand-side is nullptr_t, the right side can be a null
1580 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001581 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001582 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001583 ConvertedType = ToType;
1584 return true;
1585 }
1586
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001587 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001588 if (!ToTypePtr)
1589 return false;
1590
1591 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001592 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593 ConvertedType = ToType;
1594 return true;
1595 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001596
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001598 // , including objective-c pointers.
1599 QualType ToPointeeType = ToTypePtr->getPointeeType();
1600 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001601 ConvertedType = BuildSimilarlyQualifiedPointerType(
1602 FromType->getAs<ObjCObjectPointerType>(),
1603 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001604 ToType, Context);
1605 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001606 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001607 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001608 if (!FromTypePtr)
1609 return false;
1610
1611 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001612
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001613 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001614 // pointer conversion, so don't do all of the work below.
1615 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1616 return false;
1617
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001618 // An rvalue of type "pointer to cv T," where T is an object type,
1619 // can be converted to an rvalue of type "pointer to cv void" (C++
1620 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001621 if (FromPointeeType->isIncompleteOrObjectType() &&
1622 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001623 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001624 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001625 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626 return true;
1627 }
1628
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001629 // When we're overloading in C, we allow a special kind of pointer
1630 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001631 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001632 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001633 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001634 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001635 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001636 return true;
1637 }
1638
Douglas Gregor5c407d92008-10-23 00:40:37 +00001639 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001640 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001641 // An rvalue of type "pointer to cv D," where D is a class type,
1642 // can be converted to an rvalue of type "pointer to cv B," where
1643 // B is a base class (clause 10) of D. If B is an inaccessible
1644 // (clause 11) or ambiguous (10.2) base class of D, a program that
1645 // necessitates this conversion is ill-formed. The result of the
1646 // conversion is a pointer to the base class sub-object of the
1647 // derived class object. The null pointer value is converted to
1648 // the null pointer value of the destination type.
1649 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001650 // Note that we do not check for ambiguity or inaccessibility
1651 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001652 if (getLangOptions().CPlusPlus &&
1653 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001654 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001655 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001656 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001657 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001658 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001659 ToType, Context);
1660 return true;
1661 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001662
Douglas Gregora119f102008-12-19 19:13:09 +00001663 return false;
1664}
1665
1666/// isObjCPointerConversion - Determines whether this is an
1667/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1668/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001669bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001670 QualType& ConvertedType,
1671 bool &IncompatibleObjC) {
1672 if (!getLangOptions().ObjC1)
1673 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
Steve Naroff7cae42b2009-07-10 23:34:53 +00001675 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001676 const ObjCObjectPointerType* ToObjCPtr =
1677 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001678 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001679 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001680
Steve Naroff7cae42b2009-07-10 23:34:53 +00001681 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001682 // If the pointee types are the same (ignoring qualifications),
1683 // then this is not a pointer conversion.
1684 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1685 FromObjCPtr->getPointeeType()))
1686 return false;
1687
Steve Naroff1329fa02009-07-15 18:40:39 +00001688 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001689 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001690 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001691 ConvertedType = ToType;
1692 return true;
1693 }
1694 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001695 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001696 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001697 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001698 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001699 ConvertedType = ToType;
1700 return true;
1701 }
1702 // Objective C++: We're able to convert from a pointer to an
1703 // interface to a pointer to a different interface.
1704 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001705 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1706 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1707 if (getLangOptions().CPlusPlus && LHS && RHS &&
1708 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1709 FromObjCPtr->getPointeeType()))
1710 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001711 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001712 ToObjCPtr->getPointeeType(),
1713 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001714 return true;
1715 }
1716
1717 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1718 // Okay: this is some kind of implicit downcast of Objective-C
1719 // interfaces, which is permitted. However, we're going to
1720 // complain about it.
1721 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001722 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001723 ToObjCPtr->getPointeeType(),
1724 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001725 return true;
1726 }
Mike Stump11289f42009-09-09 15:08:12 +00001727 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001728 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001729 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001730 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001731 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001732 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001733 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001734 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001735 // to a block pointer type.
1736 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1737 ConvertedType = ToType;
1738 return true;
1739 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001740 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001742 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001743 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001745 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001746 ConvertedType = ToType;
1747 return true;
1748 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001749 else
Douglas Gregora119f102008-12-19 19:13:09 +00001750 return false;
1751
Douglas Gregor033f56d2008-12-23 00:53:59 +00001752 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001753 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001754 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001755 else if (const BlockPointerType *FromBlockPtr =
1756 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001757 FromPointeeType = FromBlockPtr->getPointeeType();
1758 else
Douglas Gregora119f102008-12-19 19:13:09 +00001759 return false;
1760
Douglas Gregora119f102008-12-19 19:13:09 +00001761 // If we have pointers to pointers, recursively check whether this
1762 // is an Objective-C conversion.
1763 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1764 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1765 IncompatibleObjC)) {
1766 // We always complain about this conversion.
1767 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001768 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001769 return true;
1770 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001771 // Allow conversion of pointee being objective-c pointer to another one;
1772 // as in I* to id.
1773 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1774 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1775 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1776 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001777 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001778 return true;
1779 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001780
Douglas Gregor033f56d2008-12-23 00:53:59 +00001781 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001782 // differences in the argument and result types are in Objective-C
1783 // pointer conversions. If so, we permit the conversion (but
1784 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001785 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001786 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001787 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001788 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001789 if (FromFunctionType && ToFunctionType) {
1790 // If the function types are exactly the same, this isn't an
1791 // Objective-C pointer conversion.
1792 if (Context.getCanonicalType(FromPointeeType)
1793 == Context.getCanonicalType(ToPointeeType))
1794 return false;
1795
1796 // Perform the quick checks that will tell us whether these
1797 // function types are obviously different.
1798 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1799 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1800 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1801 return false;
1802
1803 bool HasObjCConversion = false;
1804 if (Context.getCanonicalType(FromFunctionType->getResultType())
1805 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1806 // Okay, the types match exactly. Nothing to do.
1807 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1808 ToFunctionType->getResultType(),
1809 ConvertedType, IncompatibleObjC)) {
1810 // Okay, we have an Objective-C pointer conversion.
1811 HasObjCConversion = true;
1812 } else {
1813 // Function types are too different. Abort.
1814 return false;
1815 }
Mike Stump11289f42009-09-09 15:08:12 +00001816
Douglas Gregora119f102008-12-19 19:13:09 +00001817 // Check argument types.
1818 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1819 ArgIdx != NumArgs; ++ArgIdx) {
1820 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1821 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1822 if (Context.getCanonicalType(FromArgType)
1823 == Context.getCanonicalType(ToArgType)) {
1824 // Okay, the types match exactly. Nothing to do.
1825 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1826 ConvertedType, IncompatibleObjC)) {
1827 // Okay, we have an Objective-C pointer conversion.
1828 HasObjCConversion = true;
1829 } else {
1830 // Argument types are too different. Abort.
1831 return false;
1832 }
1833 }
1834
1835 if (HasObjCConversion) {
1836 // We had an Objective-C conversion. Allow this pointer
1837 // conversion, but complain about it.
1838 ConvertedType = ToType;
1839 IncompatibleObjC = true;
1840 return true;
1841 }
1842 }
1843
Sebastian Redl72b597d2009-01-25 19:43:20 +00001844 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001845}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001847bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1848 QualType& ConvertedType) {
1849 QualType ToPointeeType;
1850 if (const BlockPointerType *ToBlockPtr =
1851 ToType->getAs<BlockPointerType>())
1852 ToPointeeType = ToBlockPtr->getPointeeType();
1853 else
1854 return false;
1855
1856 QualType FromPointeeType;
1857 if (const BlockPointerType *FromBlockPtr =
1858 FromType->getAs<BlockPointerType>())
1859 FromPointeeType = FromBlockPtr->getPointeeType();
1860 else
1861 return false;
1862 // We have pointer to blocks, check whether the only
1863 // differences in the argument and result types are in Objective-C
1864 // pointer conversions. If so, we permit the conversion.
1865
1866 const FunctionProtoType *FromFunctionType
1867 = FromPointeeType->getAs<FunctionProtoType>();
1868 const FunctionProtoType *ToFunctionType
1869 = ToPointeeType->getAs<FunctionProtoType>();
1870
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001871 if (!FromFunctionType || !ToFunctionType)
1872 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001873
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001874 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001875 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001876
1877 // Perform the quick checks that will tell us whether these
1878 // function types are obviously different.
1879 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1880 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1881 return false;
1882
1883 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1884 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1885 if (FromEInfo != ToEInfo)
1886 return false;
1887
1888 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00001889 if (Context.hasSameType(FromFunctionType->getResultType(),
1890 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001891 // Okay, the types match exactly. Nothing to do.
1892 } else {
1893 QualType RHS = FromFunctionType->getResultType();
1894 QualType LHS = ToFunctionType->getResultType();
1895 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1896 !RHS.hasQualifiers() && LHS.hasQualifiers())
1897 LHS = LHS.getUnqualifiedType();
1898
1899 if (Context.hasSameType(RHS,LHS)) {
1900 // OK exact match.
1901 } else if (isObjCPointerConversion(RHS, LHS,
1902 ConvertedType, IncompatibleObjC)) {
1903 if (IncompatibleObjC)
1904 return false;
1905 // Okay, we have an Objective-C pointer conversion.
1906 }
1907 else
1908 return false;
1909 }
1910
1911 // Check argument types.
1912 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1913 ArgIdx != NumArgs; ++ArgIdx) {
1914 IncompatibleObjC = false;
1915 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1916 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1917 if (Context.hasSameType(FromArgType, ToArgType)) {
1918 // Okay, the types match exactly. Nothing to do.
1919 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1920 ConvertedType, IncompatibleObjC)) {
1921 if (IncompatibleObjC)
1922 return false;
1923 // Okay, we have an Objective-C pointer conversion.
1924 } else
1925 // Argument types are too different. Abort.
1926 return false;
1927 }
1928 ConvertedType = ToType;
1929 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001930}
1931
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001932/// FunctionArgTypesAreEqual - This routine checks two function proto types
1933/// for equlity of their argument types. Caller has already checked that
1934/// they have same number of arguments. This routine assumes that Objective-C
1935/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001936bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00001937 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001938 if (!getLangOptions().ObjC1)
1939 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1940 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001942 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1943 N = NewType->arg_type_begin(),
1944 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1945 QualType ToType = (*O);
1946 QualType FromType = (*N);
1947 if (ToType != FromType) {
1948 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1949 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001950 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1951 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1952 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1953 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001954 continue;
1955 }
John McCall8b07ec22010-05-15 11:32:37 +00001956 else if (const ObjCObjectPointerType *PTTo =
1957 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00001959 FromType->getAs<ObjCObjectPointerType>())
1960 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1961 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001964 }
1965 }
1966 return true;
1967}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968
Douglas Gregor39c16d42008-10-24 04:54:22 +00001969/// CheckPointerConversion - Check the pointer conversion from the
1970/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001971/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001972/// conversions for which IsPointerConversion has already returned
1973/// true. It returns true and produces a diagnostic if there was an
1974/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001975bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001976 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001977 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001978 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001979 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001980 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001981
John McCall8cb679e2010-11-15 09:13:47 +00001982 Kind = CK_BitCast;
1983
Douglas Gregor4038cf42010-06-08 17:35:15 +00001984 if (CXXBoolLiteralExpr* LitBool
1985 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001986 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Chandler Carruth477a9992011-03-01 03:29:37 +00001987 DiagRuntimeBehavior(LitBool->getExprLoc(), From,
1988 PDiag(diag::warn_init_pointer_from_false) << ToType);
Douglas Gregor4038cf42010-06-08 17:35:15 +00001989
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001990 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1991 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001992 QualType FromPointeeType = FromPtrType->getPointeeType(),
1993 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001994
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001995 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1996 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001997 // We must have a derived-to-base conversion. Check an
1998 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001999 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2000 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002001 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002002 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002003 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002005 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002006 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002007 }
2008 }
Mike Stump11289f42009-09-09 15:08:12 +00002009 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00002010 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002011 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00002012 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002013 // Objective-C++ conversions are always okay.
2014 // FIXME: We should have a different class of conversions for the
2015 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002016 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002017 return false;
John McCall8cb679e2010-11-15 09:13:47 +00002018 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002019 }
John McCall8cb679e2010-11-15 09:13:47 +00002020
2021 // We shouldn't fall into this case unless it's valid for other
2022 // reasons.
2023 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2024 Kind = CK_NullToPointer;
2025
Douglas Gregor39c16d42008-10-24 04:54:22 +00002026 return false;
2027}
2028
Sebastian Redl72b597d2009-01-25 19:43:20 +00002029/// IsMemberPointerConversion - Determines whether the conversion of the
2030/// expression From, which has the (possibly adjusted) type FromType, can be
2031/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2032/// If so, returns true and places the converted type (that might differ from
2033/// ToType in its cv-qualifiers at some level) into ConvertedType.
2034bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002035 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002036 bool InOverloadResolution,
2037 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002038 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002039 if (!ToTypePtr)
2040 return false;
2041
2042 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002043 if (From->isNullPointerConstant(Context,
2044 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2045 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002046 ConvertedType = ToType;
2047 return true;
2048 }
2049
2050 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002051 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002052 if (!FromTypePtr)
2053 return false;
2054
2055 // A pointer to member of B can be converted to a pointer to member of D,
2056 // where D is derived from B (C++ 4.11p2).
2057 QualType FromClass(FromTypePtr->getClass(), 0);
2058 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002059
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002060 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2061 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2062 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002063 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2064 ToClass.getTypePtr());
2065 return true;
2066 }
2067
2068 return false;
2069}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002070
Sebastian Redl72b597d2009-01-25 19:43:20 +00002071/// CheckMemberPointerConversion - Check the member pointer conversion from the
2072/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002073/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002074/// for which IsMemberPointerConversion has already returned true. It returns
2075/// true and produces a diagnostic if there was an error, or returns false
2076/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002077bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002078 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002079 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002080 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002081 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002082 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002083 if (!FromPtrType) {
2084 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002086 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002087 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002088 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002089 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002090 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002091
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002092 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002093 assert(ToPtrType && "No member pointer cast has a target type "
2094 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002095
Sebastian Redled8f2002009-01-28 18:33:18 +00002096 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2097 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002098
Sebastian Redled8f2002009-01-28 18:33:18 +00002099 // FIXME: What about dependent types?
2100 assert(FromClass->isRecordType() && "Pointer into non-class.");
2101 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002102
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002103 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002104 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002105 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2106 assert(DerivationOkay &&
2107 "Should not have been called if derivation isn't OK.");
2108 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002109
Sebastian Redled8f2002009-01-28 18:33:18 +00002110 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2111 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002112 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2113 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2114 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2115 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002116 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002117
Douglas Gregor89ee6822009-02-28 01:32:25 +00002118 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002119 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2120 << FromClass << ToClass << QualType(VBase, 0)
2121 << From->getSourceRange();
2122 return true;
2123 }
2124
John McCall5b0829a2010-02-10 09:31:12 +00002125 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002126 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2127 Paths.front(),
2128 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002129
Anders Carlssond7923c62009-08-22 23:33:40 +00002130 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002131 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002132 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002133 return false;
2134}
2135
Douglas Gregor9a657932008-10-21 23:43:52 +00002136/// IsQualificationConversion - Determines whether the conversion from
2137/// an rvalue of type FromType to ToType is a qualification conversion
2138/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00002139bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002140Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor58281352011-01-27 00:58:17 +00002141 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002142 FromType = Context.getCanonicalType(FromType);
2143 ToType = Context.getCanonicalType(ToType);
2144
2145 // If FromType and ToType are the same type, this is not a
2146 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002147 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002148 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002149
Douglas Gregor9a657932008-10-21 23:43:52 +00002150 // (C++ 4.4p4):
2151 // A conversion can add cv-qualifiers at levels other than the first
2152 // in multi-level pointers, subject to the following rules: [...]
2153 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002154 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002155 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002156 // Within each iteration of the loop, we check the qualifiers to
2157 // determine if this still looks like a qualification
2158 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002159 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002160 // until there are no more pointers or pointers-to-members left to
2161 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002162 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002163
2164 // -- for every j > 0, if const is in cv 1,j then const is in cv
2165 // 2,j, and similarly for volatile.
Douglas Gregor58281352011-01-27 00:58:17 +00002166 if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
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 // -- if the cv 1,j and cv 2,j are different, then const is in
2170 // every cv for 0 < k < j.
Douglas Gregor58281352011-01-27 00:58:17 +00002171 if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002172 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002173 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002174
Douglas Gregor9a657932008-10-21 23:43:52 +00002175 // Keep track of whether all prior cv-qualifiers in the "to" type
2176 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002177 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002178 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002179 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002180
2181 // We are left with FromType and ToType being the pointee types
2182 // after unwrapping the original FromType and ToType the same number
2183 // of types. If we unwrapped any pointers, and if FromType and
2184 // ToType have the same unqualified type (since we checked
2185 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002186 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002187}
2188
Douglas Gregor576e98c2009-01-30 23:27:23 +00002189/// Determines whether there is a user-defined conversion sequence
2190/// (C++ [over.ics.user]) that converts expression From to the type
2191/// ToType. If such a conversion exists, User will contain the
2192/// user-defined conversion sequence that performs such a conversion
2193/// and this routine will return true. Otherwise, this routine returns
2194/// false and User is unspecified.
2195///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002196/// \param AllowExplicit true if the conversion should consider C++0x
2197/// "explicit" conversion functions as well as non-explicit conversion
2198/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002199static OverloadingResult
2200IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2201 UserDefinedConversionSequence& User,
2202 OverloadCandidateSet& CandidateSet,
2203 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002204 // Whether we will only visit constructors.
2205 bool ConstructorsOnly = false;
2206
2207 // If the type we are conversion to is a class type, enumerate its
2208 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002209 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002210 // C++ [over.match.ctor]p1:
2211 // When objects of class type are direct-initialized (8.5), or
2212 // copy-initialized from an expression of the same or a
2213 // derived class type (8.5), overload resolution selects the
2214 // constructor. [...] For copy-initialization, the candidate
2215 // functions are all the converting constructors (12.3.1) of
2216 // that class. The argument list is the expression-list within
2217 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002218 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002219 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002220 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002221 ConstructorsOnly = true;
2222
John McCall5c32be02010-08-24 20:38:10 +00002223 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002224 // We're not going to find any constructors.
2225 } else if (CXXRecordDecl *ToRecordDecl
2226 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002227 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002228 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002229 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002230 NamedDecl *D = *Con;
2231 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2232
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002233 // Find the constructor (which may be a template).
2234 CXXConstructorDecl *Constructor = 0;
2235 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002236 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002237 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002238 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002239 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2240 else
John McCalla0296f72010-03-19 07:35:19 +00002241 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002243 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002244 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002245 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002246 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2247 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002248 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002249 /*SuppressUserConversions=*/
2250 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002251 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002252 // Allow one user-defined conversion when user specifies a
2253 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002254 S.AddOverloadCandidate(Constructor, FoundDecl,
2255 &From, 1, CandidateSet,
2256 /*SuppressUserConversions=*/
2257 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002258 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002259 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002260 }
2261 }
2262
Douglas Gregor5ab11652010-04-17 22:01:05 +00002263 // Enumerate conversion functions, if we're allowed to.
2264 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002265 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2266 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002267 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002268 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002269 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002270 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002271 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2272 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002273 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002274 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002275 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002276 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002277 DeclAccessPair FoundDecl = I.getPair();
2278 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002279 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2280 if (isa<UsingShadowDecl>(D))
2281 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2282
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002283 CXXConversionDecl *Conv;
2284 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002285 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2286 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002287 else
John McCallda4458e2010-03-31 01:36:47 +00002288 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002289
2290 if (AllowExplicit || !Conv->isExplicit()) {
2291 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002292 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2293 ActingContext, From, ToType,
2294 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002295 else
John McCall5c32be02010-08-24 20:38:10 +00002296 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2297 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002298 }
2299 }
2300 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002301 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002302
2303 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002304 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002305 case OR_Success:
2306 // Record the standard conversion we used and the conversion function.
2307 if (CXXConstructorDecl *Constructor
2308 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002309 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2310
John McCall5c32be02010-08-24 20:38:10 +00002311 // C++ [over.ics.user]p1:
2312 // If the user-defined conversion is specified by a
2313 // constructor (12.3.1), the initial standard conversion
2314 // sequence converts the source type to the type required by
2315 // the argument of the constructor.
2316 //
2317 QualType ThisType = Constructor->getThisType(S.Context);
2318 if (Best->Conversions[0].isEllipsis())
2319 User.EllipsisConversion = true;
2320 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002321 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002322 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002323 }
John McCall5c32be02010-08-24 20:38:10 +00002324 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002325 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002326 User.After.setAsIdentityConversion();
2327 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2328 User.After.setAllToTypes(ToType);
2329 return OR_Success;
2330 } else if (CXXConversionDecl *Conversion
2331 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002332 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2333
John McCall5c32be02010-08-24 20:38:10 +00002334 // C++ [over.ics.user]p1:
2335 //
2336 // [...] If the user-defined conversion is specified by a
2337 // conversion function (12.3.2), the initial standard
2338 // conversion sequence converts the source type to the
2339 // implicit object parameter of the conversion function.
2340 User.Before = Best->Conversions[0].Standard;
2341 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002342 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002343 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002344
John McCall5c32be02010-08-24 20:38:10 +00002345 // C++ [over.ics.user]p2:
2346 // The second standard conversion sequence converts the
2347 // result of the user-defined conversion to the target type
2348 // for the sequence. Since an implicit conversion sequence
2349 // is an initialization, the special rules for
2350 // initialization by user-defined conversion apply when
2351 // selecting the best user-defined conversion for a
2352 // user-defined conversion sequence (see 13.3.3 and
2353 // 13.3.3.1).
2354 User.After = Best->FinalConversion;
2355 return OR_Success;
2356 } else {
2357 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002358 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002359 }
2360
John McCall5c32be02010-08-24 20:38:10 +00002361 case OR_No_Viable_Function:
2362 return OR_No_Viable_Function;
2363 case OR_Deleted:
2364 // No conversion here! We're done.
2365 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002366
John McCall5c32be02010-08-24 20:38:10 +00002367 case OR_Ambiguous:
2368 return OR_Ambiguous;
2369 }
2370
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002371 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002372}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002373
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002374bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002375Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002376 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002377 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002378 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002379 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002380 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002381 if (OvResult == OR_Ambiguous)
2382 Diag(From->getSourceRange().getBegin(),
2383 diag::err_typecheck_ambiguous_condition)
2384 << From->getType() << ToType << From->getSourceRange();
2385 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2386 Diag(From->getSourceRange().getBegin(),
2387 diag::err_typecheck_nonviable_condition)
2388 << From->getType() << ToType << From->getSourceRange();
2389 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002390 return false;
John McCall5c32be02010-08-24 20:38:10 +00002391 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002393}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002394
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002395/// CompareImplicitConversionSequences - Compare two implicit
2396/// conversion sequences to determine whether one is better than the
2397/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002398static ImplicitConversionSequence::CompareKind
2399CompareImplicitConversionSequences(Sema &S,
2400 const ImplicitConversionSequence& ICS1,
2401 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002402{
2403 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2404 // conversion sequences (as defined in 13.3.3.1)
2405 // -- a standard conversion sequence (13.3.3.1.1) is a better
2406 // conversion sequence than a user-defined conversion sequence or
2407 // an ellipsis conversion sequence, and
2408 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2409 // conversion sequence than an ellipsis conversion sequence
2410 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002411 //
John McCall0d1da222010-01-12 00:44:57 +00002412 // C++0x [over.best.ics]p10:
2413 // For the purpose of ranking implicit conversion sequences as
2414 // described in 13.3.3.2, the ambiguous conversion sequence is
2415 // treated as a user-defined sequence that is indistinguishable
2416 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002417 if (ICS1.getKindRank() < ICS2.getKindRank())
2418 return ImplicitConversionSequence::Better;
2419 else if (ICS2.getKindRank() < ICS1.getKindRank())
2420 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002421
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002422 // The following checks require both conversion sequences to be of
2423 // the same kind.
2424 if (ICS1.getKind() != ICS2.getKind())
2425 return ImplicitConversionSequence::Indistinguishable;
2426
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002427 // Two implicit conversion sequences of the same form are
2428 // indistinguishable conversion sequences unless one of the
2429 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002430 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002431 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002432 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002433 // User-defined conversion sequence U1 is a better conversion
2434 // sequence than another user-defined conversion sequence U2 if
2435 // they contain the same user-defined conversion function or
2436 // constructor and if the second standard conversion sequence of
2437 // U1 is better than the second standard conversion sequence of
2438 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002439 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002440 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002441 return CompareStandardConversionSequences(S,
2442 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002443 ICS2.UserDefined.After);
2444 }
2445
2446 return ImplicitConversionSequence::Indistinguishable;
2447}
2448
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002449static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2450 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2451 Qualifiers Quals;
2452 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002453 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002456 return Context.hasSameUnqualifiedType(T1, T2);
2457}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002459// Per 13.3.3.2p3, compare the given standard conversion sequences to
2460// determine if one is a proper subset of the other.
2461static ImplicitConversionSequence::CompareKind
2462compareStandardConversionSubsets(ASTContext &Context,
2463 const StandardConversionSequence& SCS1,
2464 const StandardConversionSequence& SCS2) {
2465 ImplicitConversionSequence::CompareKind Result
2466 = ImplicitConversionSequence::Indistinguishable;
2467
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002469 // any non-identity conversion sequence
2470 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2471 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2472 return ImplicitConversionSequence::Better;
2473 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2474 return ImplicitConversionSequence::Worse;
2475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002476
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002477 if (SCS1.Second != SCS2.Second) {
2478 if (SCS1.Second == ICK_Identity)
2479 Result = ImplicitConversionSequence::Better;
2480 else if (SCS2.Second == ICK_Identity)
2481 Result = ImplicitConversionSequence::Worse;
2482 else
2483 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002484 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002485 return ImplicitConversionSequence::Indistinguishable;
2486
2487 if (SCS1.Third == SCS2.Third) {
2488 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2489 : ImplicitConversionSequence::Indistinguishable;
2490 }
2491
2492 if (SCS1.Third == ICK_Identity)
2493 return Result == ImplicitConversionSequence::Worse
2494 ? ImplicitConversionSequence::Indistinguishable
2495 : ImplicitConversionSequence::Better;
2496
2497 if (SCS2.Third == ICK_Identity)
2498 return Result == ImplicitConversionSequence::Better
2499 ? ImplicitConversionSequence::Indistinguishable
2500 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002501
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002502 return ImplicitConversionSequence::Indistinguishable;
2503}
2504
Douglas Gregore696ebb2011-01-26 14:52:12 +00002505/// \brief Determine whether one of the given reference bindings is better
2506/// than the other based on what kind of bindings they are.
2507static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2508 const StandardConversionSequence &SCS2) {
2509 // C++0x [over.ics.rank]p3b4:
2510 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2511 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002512 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002513 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002515 // reference*.
2516 //
2517 // FIXME: Rvalue references. We're going rogue with the above edits,
2518 // because the semantics in the current C++0x working paper (N3225 at the
2519 // time of this writing) break the standard definition of std::forward
2520 // and std::reference_wrapper when dealing with references to functions.
2521 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002522 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2523 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2524 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002525
Douglas Gregore696ebb2011-01-26 14:52:12 +00002526 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2527 SCS2.IsLvalueReference) ||
2528 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2529 !SCS2.IsLvalueReference);
2530}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002531
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002532/// CompareStandardConversionSequences - Compare two standard
2533/// conversion sequences to determine whether one is better than the
2534/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002535static ImplicitConversionSequence::CompareKind
2536CompareStandardConversionSequences(Sema &S,
2537 const StandardConversionSequence& SCS1,
2538 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002539{
2540 // Standard conversion sequence S1 is a better conversion sequence
2541 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2542
2543 // -- S1 is a proper subsequence of S2 (comparing the conversion
2544 // sequences in the canonical form defined by 13.3.3.1.1,
2545 // excluding any Lvalue Transformation; the identity conversion
2546 // sequence is considered to be a subsequence of any
2547 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002548 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002549 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002550 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002551
2552 // -- the rank of S1 is better than the rank of S2 (by the rules
2553 // defined below), or, if not that,
2554 ImplicitConversionRank Rank1 = SCS1.getRank();
2555 ImplicitConversionRank Rank2 = SCS2.getRank();
2556 if (Rank1 < Rank2)
2557 return ImplicitConversionSequence::Better;
2558 else if (Rank2 < Rank1)
2559 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002560
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002561 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2562 // are indistinguishable unless one of the following rules
2563 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002564
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002565 // A conversion that is not a conversion of a pointer, or
2566 // pointer to member, to bool is better than another conversion
2567 // that is such a conversion.
2568 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2569 return SCS2.isPointerConversionToBool()
2570 ? ImplicitConversionSequence::Better
2571 : ImplicitConversionSequence::Worse;
2572
Douglas Gregor5c407d92008-10-23 00:40:37 +00002573 // C++ [over.ics.rank]p4b2:
2574 //
2575 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002576 // conversion of B* to A* is better than conversion of B* to
2577 // void*, and conversion of A* to void* is better than conversion
2578 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002579 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002580 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002581 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002582 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002583 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2584 // Exactly one of the conversion sequences is a conversion to
2585 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002586 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2587 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002588 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2589 // Neither conversion sequence converts to a void pointer; compare
2590 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002591 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002592 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002593 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002594 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2595 // Both conversion sequences are conversions to void
2596 // pointers. Compare the source types to determine if there's an
2597 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002598 QualType FromType1 = SCS1.getFromType();
2599 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002600
2601 // Adjust the types we're converting from via the array-to-pointer
2602 // conversion, if we need to.
2603 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002604 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002605 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002606 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002607
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002608 QualType FromPointee1
2609 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2610 QualType FromPointee2
2611 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002612
John McCall5c32be02010-08-24 20:38:10 +00002613 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002614 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002615 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002616 return ImplicitConversionSequence::Worse;
2617
2618 // Objective-C++: If one interface is more specific than the
2619 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002620 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2621 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002622 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002623 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002624 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002625 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002626 return ImplicitConversionSequence::Worse;
2627 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002628 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002629
2630 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2631 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002632 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002633 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002634 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002635
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002636 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002637 // Check for a better reference binding based on the kind of bindings.
2638 if (isBetterReferenceBindingKind(SCS1, SCS2))
2639 return ImplicitConversionSequence::Better;
2640 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2641 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002642
Sebastian Redlb28b4072009-03-22 23:49:27 +00002643 // C++ [over.ics.rank]p3b4:
2644 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2645 // which the references refer are the same type except for
2646 // top-level cv-qualifiers, and the type to which the reference
2647 // initialized by S2 refers is more cv-qualified than the type
2648 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002649 QualType T1 = SCS1.getToType(2);
2650 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002651 T1 = S.Context.getCanonicalType(T1);
2652 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002653 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002654 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2655 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002656 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002657 // If the type is an array type, promote the element qualifiers to the
2658 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002659 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002660 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002661 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002662 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002663 if (T2.isMoreQualifiedThan(T1))
2664 return ImplicitConversionSequence::Better;
2665 else if (T1.isMoreQualifiedThan(T2))
2666 return ImplicitConversionSequence::Worse;
2667 }
2668 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002669
2670 return ImplicitConversionSequence::Indistinguishable;
2671}
2672
2673/// CompareQualificationConversions - Compares two standard conversion
2674/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002675/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2676ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002677CompareQualificationConversions(Sema &S,
2678 const StandardConversionSequence& SCS1,
2679 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002680 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002681 // -- S1 and S2 differ only in their qualification conversion and
2682 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2683 // cv-qualification signature of type T1 is a proper subset of
2684 // the cv-qualification signature of type T2, and S1 is not the
2685 // deprecated string literal array-to-pointer conversion (4.2).
2686 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2687 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2688 return ImplicitConversionSequence::Indistinguishable;
2689
2690 // FIXME: the example in the standard doesn't use a qualification
2691 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002692 QualType T1 = SCS1.getToType(2);
2693 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002694 T1 = S.Context.getCanonicalType(T1);
2695 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002696 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002697 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2698 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002699
2700 // If the types are the same, we won't learn anything by unwrapped
2701 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002702 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002703 return ImplicitConversionSequence::Indistinguishable;
2704
Chandler Carruth607f38e2009-12-29 07:16:59 +00002705 // If the type is an array type, promote the element qualifiers to the type
2706 // for comparison.
2707 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002708 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002709 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002710 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002711
Mike Stump11289f42009-09-09 15:08:12 +00002712 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002713 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002714 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002715 // Within each iteration of the loop, we check the qualifiers to
2716 // determine if this still looks like a qualification
2717 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002718 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002719 // until there are no more pointers or pointers-to-members left
2720 // to unwrap. This essentially mimics what
2721 // IsQualificationConversion does, but here we're checking for a
2722 // strict subset of qualifiers.
2723 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2724 // The qualifiers are the same, so this doesn't tell us anything
2725 // about how the sequences rank.
2726 ;
2727 else if (T2.isMoreQualifiedThan(T1)) {
2728 // T1 has fewer qualifiers, so it could be the better sequence.
2729 if (Result == ImplicitConversionSequence::Worse)
2730 // Neither has qualifiers that are a subset of the other's
2731 // qualifiers.
2732 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002733
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002734 Result = ImplicitConversionSequence::Better;
2735 } else if (T1.isMoreQualifiedThan(T2)) {
2736 // T2 has fewer qualifiers, so it could be the better sequence.
2737 if (Result == ImplicitConversionSequence::Better)
2738 // Neither has qualifiers that are a subset of the other's
2739 // qualifiers.
2740 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002741
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002742 Result = ImplicitConversionSequence::Worse;
2743 } else {
2744 // Qualifiers are disjoint.
2745 return ImplicitConversionSequence::Indistinguishable;
2746 }
2747
2748 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002749 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002750 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002751 }
2752
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002753 // Check that the winning standard conversion sequence isn't using
2754 // the deprecated string literal array to pointer conversion.
2755 switch (Result) {
2756 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002757 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002758 Result = ImplicitConversionSequence::Indistinguishable;
2759 break;
2760
2761 case ImplicitConversionSequence::Indistinguishable:
2762 break;
2763
2764 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002765 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002766 Result = ImplicitConversionSequence::Indistinguishable;
2767 break;
2768 }
2769
2770 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002771}
2772
Douglas Gregor5c407d92008-10-23 00:40:37 +00002773/// CompareDerivedToBaseConversions - Compares two standard conversion
2774/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002775/// various kinds of derived-to-base conversions (C++
2776/// [over.ics.rank]p4b3). As part of these checks, we also look at
2777/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002778ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002779CompareDerivedToBaseConversions(Sema &S,
2780 const StandardConversionSequence& SCS1,
2781 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002782 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002783 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002784 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002785 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002786
2787 // Adjust the types we're converting from via the array-to-pointer
2788 // conversion, if we need to.
2789 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002790 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002791 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002792 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002793
2794 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002795 FromType1 = S.Context.getCanonicalType(FromType1);
2796 ToType1 = S.Context.getCanonicalType(ToType1);
2797 FromType2 = S.Context.getCanonicalType(FromType2);
2798 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002799
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002800 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002801 //
2802 // If class B is derived directly or indirectly from class A and
2803 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002804 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002805 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002806 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002807 SCS2.Second == ICK_Pointer_Conversion &&
2808 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2809 FromType1->isPointerType() && FromType2->isPointerType() &&
2810 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002811 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002812 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002813 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002814 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002815 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002816 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002817 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002818 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002819
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002820 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002821 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002822 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002823 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002824 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002825 return ImplicitConversionSequence::Worse;
2826 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002827
2828 // -- conversion of B* to A* is better than conversion of C* to A*,
2829 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002830 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002831 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002832 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002833 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00002834 }
2835 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2836 SCS2.Second == ICK_Pointer_Conversion) {
2837 const ObjCObjectPointerType *FromPtr1
2838 = FromType1->getAs<ObjCObjectPointerType>();
2839 const ObjCObjectPointerType *FromPtr2
2840 = FromType2->getAs<ObjCObjectPointerType>();
2841 const ObjCObjectPointerType *ToPtr1
2842 = ToType1->getAs<ObjCObjectPointerType>();
2843 const ObjCObjectPointerType *ToPtr2
2844 = ToType2->getAs<ObjCObjectPointerType>();
2845
2846 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2847 // Apply the same conversion ranking rules for Objective-C pointer types
2848 // that we do for C++ pointers to class types. However, we employ the
2849 // Objective-C pseudo-subtyping relationship used for assignment of
2850 // Objective-C pointer types.
2851 bool FromAssignLeft
2852 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2853 bool FromAssignRight
2854 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2855 bool ToAssignLeft
2856 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2857 bool ToAssignRight
2858 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2859
2860 // A conversion to an a non-id object pointer type or qualified 'id'
2861 // type is better than a conversion to 'id'.
2862 if (ToPtr1->isObjCIdType() &&
2863 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2864 return ImplicitConversionSequence::Worse;
2865 if (ToPtr2->isObjCIdType() &&
2866 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2867 return ImplicitConversionSequence::Better;
2868
2869 // A conversion to a non-id object pointer type is better than a
2870 // conversion to a qualified 'id' type
2871 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2872 return ImplicitConversionSequence::Worse;
2873 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2874 return ImplicitConversionSequence::Better;
2875
2876 // A conversion to an a non-Class object pointer type or qualified 'Class'
2877 // type is better than a conversion to 'Class'.
2878 if (ToPtr1->isObjCClassType() &&
2879 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2880 return ImplicitConversionSequence::Worse;
2881 if (ToPtr2->isObjCClassType() &&
2882 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2883 return ImplicitConversionSequence::Better;
2884
2885 // A conversion to a non-Class object pointer type is better than a
2886 // conversion to a qualified 'Class' type.
2887 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2888 return ImplicitConversionSequence::Worse;
2889 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2890 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00002891
Douglas Gregor058d3de2011-01-31 18:51:41 +00002892 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2893 if (S.Context.hasSameType(FromType1, FromType2) &&
2894 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2895 (ToAssignLeft != ToAssignRight))
2896 return ToAssignLeft? ImplicitConversionSequence::Worse
2897 : ImplicitConversionSequence::Better;
2898
2899 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2900 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2901 (FromAssignLeft != FromAssignRight))
2902 return FromAssignLeft? ImplicitConversionSequence::Better
2903 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002904 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002905 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00002906
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002907 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002908 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2909 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2910 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002912 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002914 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002916 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002918 ToType2->getAs<MemberPointerType>();
2919 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2920 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2921 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2922 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2923 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2924 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2925 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2926 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002927 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002928 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002929 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002930 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002931 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002932 return ImplicitConversionSequence::Better;
2933 }
2934 // conversion of B::* to C::* is better than conversion of A::* to C::*
2935 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002936 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002937 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002938 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002939 return ImplicitConversionSequence::Worse;
2940 }
2941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942
Douglas Gregor5ab11652010-04-17 22:01:05 +00002943 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002944 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002945 // -- binding of an expression of type C to a reference of type
2946 // B& is better than binding an expression of type C to a
2947 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002948 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2949 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2950 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002951 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002952 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002953 return ImplicitConversionSequence::Worse;
2954 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002955
Douglas Gregor2fe98832008-11-03 19:09:14 +00002956 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002957 // -- binding of an expression of type B to a reference of type
2958 // A& is better than binding an expression of type C to a
2959 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002960 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2961 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2962 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002963 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002964 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002965 return ImplicitConversionSequence::Worse;
2966 }
2967 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002968
Douglas Gregor5c407d92008-10-23 00:40:37 +00002969 return ImplicitConversionSequence::Indistinguishable;
2970}
2971
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002972/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2973/// determine whether they are reference-related,
2974/// reference-compatible, reference-compatible with added
2975/// qualification, or incompatible, for use in C++ initialization by
2976/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2977/// type, and the first type (T1) is the pointee type of the reference
2978/// type being initialized.
2979Sema::ReferenceCompareResult
2980Sema::CompareReferenceRelationship(SourceLocation Loc,
2981 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002982 bool &DerivedToBase,
2983 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002984 assert(!OrigT1->isReferenceType() &&
2985 "T1 must be the pointee type of the reference type");
2986 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2987
2988 QualType T1 = Context.getCanonicalType(OrigT1);
2989 QualType T2 = Context.getCanonicalType(OrigT2);
2990 Qualifiers T1Quals, T2Quals;
2991 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2992 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2993
2994 // C++ [dcl.init.ref]p4:
2995 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2996 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2997 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002998 DerivedToBase = false;
2999 ObjCConversion = false;
3000 if (UnqualT1 == UnqualT2) {
3001 // Nothing to do.
3002 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003003 IsDerivedFrom(UnqualT2, UnqualT1))
3004 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003005 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3006 UnqualT2->isObjCObjectOrInterfaceType() &&
3007 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3008 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003009 else
3010 return Ref_Incompatible;
3011
3012 // At this point, we know that T1 and T2 are reference-related (at
3013 // least).
3014
3015 // If the type is an array type, promote the element qualifiers to the type
3016 // for comparison.
3017 if (isa<ArrayType>(T1) && T1Quals)
3018 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3019 if (isa<ArrayType>(T2) && T2Quals)
3020 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3021
3022 // C++ [dcl.init.ref]p4:
3023 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3024 // reference-related to T2 and cv1 is the same cv-qualification
3025 // as, or greater cv-qualification than, cv2. For purposes of
3026 // overload resolution, cases for which cv1 is greater
3027 // cv-qualification than cv2 are identified as
3028 // reference-compatible with added qualification (see 13.3.3.2).
3029 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
3030 return Ref_Compatible;
3031 else if (T1.isMoreQualifiedThan(T2))
3032 return Ref_Compatible_With_Added_Qualification;
3033 else
3034 return Ref_Related;
3035}
3036
Douglas Gregor836a7e82010-08-11 02:15:33 +00003037/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003038/// with DeclType. Return true if something definite is found.
3039static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003040FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3041 QualType DeclType, SourceLocation DeclLoc,
3042 Expr *Init, QualType T2, bool AllowRvalues,
3043 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003044 assert(T2->isRecordType() && "Can only find conversions of record types.");
3045 CXXRecordDecl *T2RecordDecl
3046 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3047
3048 OverloadCandidateSet CandidateSet(DeclLoc);
3049 const UnresolvedSetImpl *Conversions
3050 = T2RecordDecl->getVisibleConversionFunctions();
3051 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3052 E = Conversions->end(); I != E; ++I) {
3053 NamedDecl *D = *I;
3054 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3055 if (isa<UsingShadowDecl>(D))
3056 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3057
3058 FunctionTemplateDecl *ConvTemplate
3059 = dyn_cast<FunctionTemplateDecl>(D);
3060 CXXConversionDecl *Conv;
3061 if (ConvTemplate)
3062 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3063 else
3064 Conv = cast<CXXConversionDecl>(D);
3065
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003066 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003067 // explicit conversions, skip it.
3068 if (!AllowExplicit && Conv->isExplicit())
3069 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070
Douglas Gregor836a7e82010-08-11 02:15:33 +00003071 if (AllowRvalues) {
3072 bool DerivedToBase = false;
3073 bool ObjCConversion = false;
3074 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003075 S.CompareReferenceRelationship(
3076 DeclLoc,
3077 Conv->getConversionType().getNonReferenceType()
3078 .getUnqualifiedType(),
3079 DeclType.getNonReferenceType().getUnqualifiedType(),
3080 DerivedToBase, ObjCConversion) ==
3081 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003082 continue;
3083 } else {
3084 // If the conversion function doesn't return a reference type,
3085 // it can't be considered for this conversion. An rvalue reference
3086 // is only acceptable if its referencee is a function type.
3087
3088 const ReferenceType *RefType =
3089 Conv->getConversionType()->getAs<ReferenceType>();
3090 if (!RefType ||
3091 (!RefType->isLValueReferenceType() &&
3092 !RefType->getPointeeType()->isFunctionType()))
3093 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095
Douglas Gregor836a7e82010-08-11 02:15:33 +00003096 if (ConvTemplate)
3097 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003098 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003099 else
3100 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003101 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003102 }
3103
3104 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003105 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003106 case OR_Success:
3107 // C++ [over.ics.ref]p1:
3108 //
3109 // [...] If the parameter binds directly to the result of
3110 // applying a conversion function to the argument
3111 // expression, the implicit conversion sequence is a
3112 // user-defined conversion sequence (13.3.3.1.2), with the
3113 // second standard conversion sequence either an identity
3114 // conversion or, if the conversion function returns an
3115 // entity of a type that is a derived class of the parameter
3116 // type, a derived-to-base Conversion.
3117 if (!Best->FinalConversion.DirectBinding)
3118 return false;
3119
Chandler Carruth30141632011-02-25 19:41:05 +00003120 if (Best->Function)
3121 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003122 ICS.setUserDefined();
3123 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3124 ICS.UserDefined.After = Best->FinalConversion;
3125 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003126 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003127 ICS.UserDefined.EllipsisConversion = false;
3128 assert(ICS.UserDefined.After.ReferenceBinding &&
3129 ICS.UserDefined.After.DirectBinding &&
3130 "Expected a direct reference binding!");
3131 return true;
3132
3133 case OR_Ambiguous:
3134 ICS.setAmbiguous();
3135 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3136 Cand != CandidateSet.end(); ++Cand)
3137 if (Cand->Viable)
3138 ICS.Ambiguous.addConversion(Cand->Function);
3139 return true;
3140
3141 case OR_No_Viable_Function:
3142 case OR_Deleted:
3143 // There was no suitable conversion, or we found a deleted
3144 // conversion; continue with other checks.
3145 return false;
3146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003147
Eric Christopheraba9fb22010-06-30 18:36:32 +00003148 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003149}
3150
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003151/// \brief Compute an implicit conversion sequence for reference
3152/// initialization.
3153static ImplicitConversionSequence
3154TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3155 SourceLocation DeclLoc,
3156 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003157 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003158 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3159
3160 // Most paths end in a failed conversion.
3161 ImplicitConversionSequence ICS;
3162 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3163
3164 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3165 QualType T2 = Init->getType();
3166
3167 // If the initializer is the address of an overloaded function, try
3168 // to resolve the overloaded function. If all goes well, T2 is the
3169 // type of the resulting function.
3170 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3171 DeclAccessPair Found;
3172 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3173 false, Found))
3174 T2 = Fn->getType();
3175 }
3176
3177 // Compute some basic properties of the types and the initializer.
3178 bool isRValRef = DeclType->isRValueReferenceType();
3179 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003180 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003181 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003182 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003183 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3184 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003185
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003186
Sebastian Redld92badf2010-06-30 18:13:39 +00003187 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003188 // A reference to type "cv1 T1" is initialized by an expression
3189 // of type "cv2 T2" as follows:
3190
Sebastian Redld92badf2010-06-30 18:13:39 +00003191 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003192 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003193 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3194 // reference-compatible with "cv2 T2," or
3195 //
3196 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3197 if (InitCategory.isLValue() &&
3198 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003199 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003200 // When a parameter of reference type binds directly (8.5.3)
3201 // to an argument expression, the implicit conversion sequence
3202 // is the identity conversion, unless the argument expression
3203 // has a type that is a derived class of the parameter type,
3204 // in which case the implicit conversion sequence is a
3205 // derived-to-base Conversion (13.3.3.1).
3206 ICS.setStandard();
3207 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003208 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3209 : ObjCConversion? ICK_Compatible_Conversion
3210 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003211 ICS.Standard.Third = ICK_Identity;
3212 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3213 ICS.Standard.setToType(0, T2);
3214 ICS.Standard.setToType(1, T1);
3215 ICS.Standard.setToType(2, T1);
3216 ICS.Standard.ReferenceBinding = true;
3217 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003218 ICS.Standard.IsLvalueReference = !isRValRef;
3219 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3220 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003221 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003222 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003223
Sebastian Redld92badf2010-06-30 18:13:39 +00003224 // Nothing more to do: the inaccessibility/ambiguity check for
3225 // derived-to-base conversions is suppressed when we're
3226 // computing the implicit conversion sequence (C++
3227 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003228 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003229 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003230
Sebastian Redld92badf2010-06-30 18:13:39 +00003231 // -- has a class type (i.e., T2 is a class type), where T1 is
3232 // not reference-related to T2, and can be implicitly
3233 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3234 // is reference-compatible with "cv3 T3" 92) (this
3235 // conversion is selected by enumerating the applicable
3236 // conversion functions (13.3.1.6) and choosing the best
3237 // one through overload resolution (13.3)),
3238 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003240 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003241 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3242 Init, T2, /*AllowRvalues=*/false,
3243 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003244 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003245 }
3246 }
3247
Sebastian Redld92badf2010-06-30 18:13:39 +00003248 // -- Otherwise, the reference shall be an lvalue reference to a
3249 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003250 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003252 // We actually handle one oddity of C++ [over.ics.ref] at this
3253 // point, which is that, due to p2 (which short-circuits reference
3254 // binding by only attempting a simple conversion for non-direct
3255 // bindings) and p3's strange wording, we allow a const volatile
3256 // reference to bind to an rvalue. Hence the check for the presence
3257 // of "const" rather than checking for "const" being the only
3258 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003259 // This is also the point where rvalue references and lvalue inits no longer
3260 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003261 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003262 return ICS;
3263
Douglas Gregorf143cd52011-01-24 16:14:37 +00003264 // -- If the initializer expression
3265 //
3266 // -- is an xvalue, class prvalue, array prvalue or function
3267 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3268 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3269 (InitCategory.isXValue() ||
3270 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3271 (InitCategory.isLValue() && T2->isFunctionType()))) {
3272 ICS.setStandard();
3273 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003275 : ObjCConversion? ICK_Compatible_Conversion
3276 : ICK_Identity;
3277 ICS.Standard.Third = ICK_Identity;
3278 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3279 ICS.Standard.setToType(0, T2);
3280 ICS.Standard.setToType(1, T1);
3281 ICS.Standard.setToType(2, T1);
3282 ICS.Standard.ReferenceBinding = true;
3283 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3284 // binding unless we're binding to a class prvalue.
3285 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3286 // allow the use of rvalue references in C++98/03 for the benefit of
3287 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288 ICS.Standard.DirectBinding =
3289 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003290 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003291 ICS.Standard.IsLvalueReference = !isRValRef;
3292 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003293 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003294 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003295 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003296 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003298
Douglas Gregorf143cd52011-01-24 16:14:37 +00003299 // -- has a class type (i.e., T2 is a class type), where T1 is not
3300 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003301 // an xvalue, class prvalue, or function lvalue of type
3302 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003303 // "cv3 T3",
3304 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003305 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003306 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003307 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003308 // class subobject).
3309 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003310 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003311 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3312 Init, T2, /*AllowRvalues=*/true,
3313 AllowExplicit)) {
3314 // In the second case, if the reference is an rvalue reference
3315 // and the second standard conversion sequence of the
3316 // user-defined conversion sequence includes an lvalue-to-rvalue
3317 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003319 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3320 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3321
Douglas Gregor95273c32011-01-21 16:36:05 +00003322 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003323 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003324
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003325 // -- Otherwise, a temporary of type "cv1 T1" is created and
3326 // initialized from the initializer expression using the
3327 // rules for a non-reference copy initialization (8.5). The
3328 // reference is then bound to the temporary. If T1 is
3329 // reference-related to T2, cv1 must be the same
3330 // cv-qualification as, or greater cv-qualification than,
3331 // cv2; otherwise, the program is ill-formed.
3332 if (RefRelationship == Sema::Ref_Related) {
3333 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3334 // we would be reference-compatible or reference-compatible with
3335 // added qualification. But that wasn't the case, so the reference
3336 // initialization fails.
3337 return ICS;
3338 }
3339
3340 // If at least one of the types is a class type, the types are not
3341 // related, and we aren't allowed any user conversions, the
3342 // reference binding fails. This case is important for breaking
3343 // recursion, since TryImplicitConversion below will attempt to
3344 // create a temporary through the use of a copy constructor.
3345 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3346 (T1->isRecordType() || T2->isRecordType()))
3347 return ICS;
3348
Douglas Gregorcba72b12011-01-21 05:18:22 +00003349 // If T1 is reference-related to T2 and the reference is an rvalue
3350 // reference, the initializer expression shall not be an lvalue.
3351 if (RefRelationship >= Sema::Ref_Related &&
3352 isRValRef && Init->Classify(S.Context).isLValue())
3353 return ICS;
3354
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003355 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003356 // When a parameter of reference type is not bound directly to
3357 // an argument expression, the conversion sequence is the one
3358 // required to convert the argument expression to the
3359 // underlying type of the reference according to
3360 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3361 // to copy-initializing a temporary of the underlying type with
3362 // the argument expression. Any difference in top-level
3363 // cv-qualification is subsumed by the initialization itself
3364 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003365 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3366 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003367 /*InOverloadResolution=*/false,
3368 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003369
3370 // Of course, that's still a reference binding.
3371 if (ICS.isStandard()) {
3372 ICS.Standard.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 } else if (ICS.isUserDefined()) {
3378 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003379 ICS.Standard.IsLvalueReference = !isRValRef;
3380 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3381 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003382 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003383 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003384
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003385 return ICS;
3386}
3387
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003388/// TryCopyInitialization - Try to copy-initialize a value of type
3389/// ToType from the expression From. Return the implicit conversion
3390/// sequence required to pass this argument, which may be a bad
3391/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003392/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003393/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003394static ImplicitConversionSequence
3395TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003396 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003397 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003398 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003399 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003400 /*FIXME:*/From->getLocStart(),
3401 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003402 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003403
John McCall5c32be02010-08-24 20:38:10 +00003404 return TryImplicitConversion(S, From, ToType,
3405 SuppressUserConversions,
3406 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003407 InOverloadResolution,
3408 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003409}
3410
Douglas Gregor436424c2008-11-18 23:14:02 +00003411/// TryObjectArgumentInitialization - Try to initialize the object
3412/// parameter of the given member function (@c Method) from the
3413/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003414static ImplicitConversionSequence
3415TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003416 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003417 CXXMethodDecl *Method,
3418 CXXRecordDecl *ActingContext) {
3419 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003420 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3421 // const volatile object.
3422 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3423 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003424 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003425
3426 // Set up the conversion sequence as a "bad" conversion, to allow us
3427 // to exit early.
3428 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003429
3430 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003431 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003432 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003433 FromType = PT->getPointeeType();
3434
Douglas Gregor02824322011-01-26 19:30:28 +00003435 // When we had a pointer, it's implicitly dereferenced, so we
3436 // better have an lvalue.
3437 assert(FromClassification.isLValue());
3438 }
3439
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003440 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003441
Douglas Gregor02824322011-01-26 19:30:28 +00003442 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003443 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003444 // parameter is
3445 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003446 // - "lvalue reference to cv X" for functions declared without a
3447 // ref-qualifier or with the & ref-qualifier
3448 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003449 // ref-qualifier
3450 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003452 // cv-qualification on the member function declaration.
3453 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003455 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003456 // (C++ [over.match.funcs]p5). We perform a simplified version of
3457 // reference binding here, that allows class rvalues to bind to
3458 // non-constant references.
3459
Douglas Gregor02824322011-01-26 19:30:28 +00003460 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003461 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003462 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003463 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003464 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003465 ICS.setBad(BadConversionSequence::bad_qualifiers,
3466 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003467 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003468 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003469
3470 // Check that we have either the same type or a derived type. It
3471 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003472 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003473 ImplicitConversionKind SecondKind;
3474 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3475 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003476 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003477 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003478 else {
John McCall65eb8792010-02-25 01:37:24 +00003479 ICS.setBad(BadConversionSequence::unrelated_class,
3480 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003481 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003482 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003483
Douglas Gregor02824322011-01-26 19:30:28 +00003484 // Check the ref-qualifier.
3485 switch (Method->getRefQualifier()) {
3486 case RQ_None:
3487 // Do nothing; we don't care about lvalueness or rvalueness.
3488 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Douglas Gregor02824322011-01-26 19:30:28 +00003490 case RQ_LValue:
3491 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3492 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003494 ImplicitParamType);
3495 return ICS;
3496 }
3497 break;
3498
3499 case RQ_RValue:
3500 if (!FromClassification.isRValue()) {
3501 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003503 ImplicitParamType);
3504 return ICS;
3505 }
3506 break;
3507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508
Douglas Gregor436424c2008-11-18 23:14:02 +00003509 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003510 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003511 ICS.Standard.setAsIdentityConversion();
3512 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003513 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003514 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003515 ICS.Standard.ReferenceBinding = true;
3516 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003518 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003519 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3520 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3521 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003522 return ICS;
3523}
3524
3525/// PerformObjectArgumentInitialization - Perform initialization of
3526/// the implicit object parameter for the given Method with the given
3527/// expression.
3528bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529Sema::PerformObjectArgumentInitialization(Expr *&From,
3530 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003531 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003532 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003533 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003534 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003535 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003536
Douglas Gregor02824322011-01-26 19:30:28 +00003537 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003538 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003539 FromRecordType = PT->getPointeeType();
3540 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003541 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003542 } else {
3543 FromRecordType = From->getType();
3544 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003545 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003546 }
3547
John McCall6e9f8f62009-12-03 04:06:58 +00003548 // Note that we always use the true parent context when performing
3549 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003550 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003551 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3552 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003553 if (ICS.isBad()) {
3554 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3555 Qualifiers FromQs = FromRecordType.getQualifiers();
3556 Qualifiers ToQs = DestType.getQualifiers();
3557 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3558 if (CVR) {
3559 Diag(From->getSourceRange().getBegin(),
3560 diag::err_member_function_call_bad_cvr)
3561 << Method->getDeclName() << FromRecordType << (CVR - 1)
3562 << From->getSourceRange();
3563 Diag(Method->getLocation(), diag::note_previous_decl)
3564 << Method->getDeclName();
3565 return true;
3566 }
3567 }
3568
Douglas Gregor436424c2008-11-18 23:14:02 +00003569 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003570 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003571 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003572 }
Mike Stump11289f42009-09-09 15:08:12 +00003573
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003574 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003575 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003576
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003577 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003578 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003579 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003580 return false;
3581}
3582
Douglas Gregor5fb53972009-01-14 15:45:31 +00003583/// TryContextuallyConvertToBool - Attempt to contextually convert the
3584/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003585static ImplicitConversionSequence
3586TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003587 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003588 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003589 // FIXME: Are these flags correct?
3590 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003591 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003592 /*InOverloadResolution=*/false,
3593 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003594}
3595
3596/// PerformContextuallyConvertToBool - Perform a contextual conversion
3597/// of the expression From to bool (C++0x [conv]p3).
3598bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003599 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003600 if (!ICS.isBad())
3601 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Fariborz Jahanian76197412009-11-18 18:26:29 +00003603 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003604 return Diag(From->getSourceRange().getBegin(),
3605 diag::err_typecheck_bool_condition)
3606 << From->getType() << From->getSourceRange();
3607 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003608}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003610/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3611/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003612static ImplicitConversionSequence
3613TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3614 QualType Ty = S.Context.getObjCIdType();
3615 return TryImplicitConversion(S, From, Ty,
3616 // FIXME: Are these flags correct?
3617 /*SuppressUserConversions=*/false,
3618 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003619 /*InOverloadResolution=*/false,
3620 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003621}
John McCall5c32be02010-08-24 20:38:10 +00003622
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003623/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3624/// of the expression From to 'id'.
3625bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003626 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003627 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003628 if (!ICS.isBad())
3629 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3630 return true;
3631}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003632
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003633/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003634/// enumeration type.
3635///
3636/// This routine will attempt to convert an expression of class type to an
3637/// integral or enumeration type, if that class type only has a single
3638/// conversion to an integral or enumeration type.
3639///
Douglas Gregor4799d032010-06-30 00:20:43 +00003640/// \param Loc The source location of the construct that requires the
3641/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003642///
Douglas Gregor4799d032010-06-30 00:20:43 +00003643/// \param FromE The expression we're converting from.
3644///
3645/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3646/// have integral or enumeration type.
3647///
3648/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3649/// incomplete class type.
3650///
3651/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3652/// explicit conversion function (because no implicit conversion functions
3653/// were available). This is a recovery mode.
3654///
3655/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3656/// showing which conversion was picked.
3657///
3658/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3659/// conversion function that could convert to integral or enumeration type.
3660///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003661/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003662/// usable conversion function.
3663///
3664/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3665/// function, which may be an extension in this case.
3666///
3667/// \returns The expression, converted to an integral or enumeration type if
3668/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669ExprResult
John McCallb268a282010-08-23 23:25:46 +00003670Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003671 const PartialDiagnostic &NotIntDiag,
3672 const PartialDiagnostic &IncompleteDiag,
3673 const PartialDiagnostic &ExplicitConvDiag,
3674 const PartialDiagnostic &ExplicitConvNote,
3675 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003676 const PartialDiagnostic &AmbigNote,
3677 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003678 // We can't perform any more checking for type-dependent expressions.
3679 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003680 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003682 // If the expression already has integral or enumeration type, we're golden.
3683 QualType T = From->getType();
3684 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003685 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003686
3687 // FIXME: Check for missing '()' if T is a function type?
3688
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003689 // 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 +00003690 // expression of integral or enumeration type.
3691 const RecordType *RecordTy = T->getAs<RecordType>();
3692 if (!RecordTy || !getLangOptions().CPlusPlus) {
3693 Diag(Loc, NotIntDiag)
3694 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003695 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003698 // We must have a complete class type.
3699 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003700 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003702 // Look for a conversion to an integral or enumeration type.
3703 UnresolvedSet<4> ViableConversions;
3704 UnresolvedSet<4> ExplicitConversions;
3705 const UnresolvedSetImpl *Conversions
3706 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003707
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003708 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709 E = Conversions->end();
3710 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003711 ++I) {
3712 if (CXXConversionDecl *Conversion
3713 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3714 if (Conversion->getConversionType().getNonReferenceType()
3715 ->isIntegralOrEnumerationType()) {
3716 if (Conversion->isExplicit())
3717 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3718 else
3719 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3720 }
3721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003723 switch (ViableConversions.size()) {
3724 case 0:
3725 if (ExplicitConversions.size() == 1) {
3726 DeclAccessPair Found = ExplicitConversions[0];
3727 CXXConversionDecl *Conversion
3728 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003730 // The user probably meant to invoke the given explicit
3731 // conversion; use it.
3732 QualType ConvTy
3733 = Conversion->getConversionType().getNonReferenceType();
3734 std::string TypeStr;
3735 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003737 Diag(Loc, ExplicitConvDiag)
3738 << T << ConvTy
3739 << FixItHint::CreateInsertion(From->getLocStart(),
3740 "static_cast<" + TypeStr + ">(")
3741 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3742 ")");
3743 Diag(Conversion->getLocation(), ExplicitConvNote)
3744 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
3746 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003747 // explicit conversion function.
3748 if (isSFINAEContext())
3749 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003751 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003752 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3753 if (Result.isInvalid())
3754 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
Douglas Gregor668443e2011-01-20 00:18:04 +00003756 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003757 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003759 // We'll complain below about a non-integral condition type.
3760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003762 case 1: {
3763 // Apply this conversion.
3764 DeclAccessPair Found = ViableConversions[0];
3765 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003766
Douglas Gregor4799d032010-06-30 00:20:43 +00003767 CXXConversionDecl *Conversion
3768 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3769 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00003771 if (ConvDiag.getDiagID()) {
3772 if (isSFINAEContext())
3773 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774
Douglas Gregor4799d032010-06-30 00:20:43 +00003775 Diag(Loc, ConvDiag)
3776 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778
Douglas Gregor668443e2011-01-20 00:18:04 +00003779 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003780 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003781 if (Result.isInvalid())
3782 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003783
Douglas Gregor668443e2011-01-20 00:18:04 +00003784 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003785 break;
3786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003788 default:
3789 Diag(Loc, AmbigDiag)
3790 << T << From->getSourceRange();
3791 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3792 CXXConversionDecl *Conv
3793 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3794 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3795 Diag(Conv->getLocation(), AmbigNote)
3796 << ConvTy->isEnumeralType() << ConvTy;
3797 }
John McCallb268a282010-08-23 23:25:46 +00003798 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800
Douglas Gregor5823da32010-06-29 23:25:20 +00003801 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003802 Diag(Loc, NotIntDiag)
3803 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003804
John McCallb268a282010-08-23 23:25:46 +00003805 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003806}
3807
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003808/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003809/// candidate functions, using the given function call arguments. If
3810/// @p SuppressUserConversions, then don't allow user-defined
3811/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003812///
3813/// \para PartialOverloading true if we are performing "partial" overloading
3814/// based on an incomplete set of function arguments. This feature is used by
3815/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003816void
3817Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003818 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003819 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003820 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003821 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003822 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003823 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003824 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003825 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003826 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003827 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003828
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003829 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003830 if (!isa<CXXConstructorDecl>(Method)) {
3831 // If we get here, it's because we're calling a member function
3832 // that is named without a member access expression (e.g.,
3833 // "this->f") that was either written explicitly or created
3834 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003835 // function, e.g., X::f(). We use an empty type for the implied
3836 // object argument (C++ [over.call.func]p3), and the acting context
3837 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003838 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00003840 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003841 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003842 return;
3843 }
3844 // We treat a constructor like a non-member function, since its object
3845 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003846 }
3847
Douglas Gregorff7028a2009-11-13 23:59:09 +00003848 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003849 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003850
Douglas Gregor27381f32009-11-23 12:27:39 +00003851 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003852 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003853
Douglas Gregorffe14e32009-11-14 01:20:54 +00003854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3855 // C++ [class.copy]p3:
3856 // A member function template is never instantiated to perform the copy
3857 // of a class object to an object of its class type.
3858 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003859 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003860 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003861 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3862 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003863 return;
3864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003865
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003866 // Add this candidate
3867 CandidateSet.push_back(OverloadCandidate());
3868 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003869 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003870 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003871 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003872 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003873 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003874 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003875
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003876 unsigned NumArgsInProto = Proto->getNumArgs();
3877
3878 // (C++ 13.3.2p2): A candidate function having fewer than m
3879 // parameters is viable only if it has an ellipsis in its parameter
3880 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00003882 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003883 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003884 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003885 return;
3886 }
3887
3888 // (C++ 13.3.2p2): A candidate function having more than m parameters
3889 // is viable only if the (m+1)st parameter has a default argument
3890 // (8.3.6). For the purposes of overload resolution, the
3891 // parameter list is truncated on the right, so that there are
3892 // exactly m parameters.
3893 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003894 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003895 // Not enough arguments.
3896 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003897 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003898 return;
3899 }
3900
3901 // Determine the implicit conversion sequences for each of the
3902 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003903 Candidate.Conversions.resize(NumArgs);
3904 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3905 if (ArgIdx < NumArgsInProto) {
3906 // (C++ 13.3.2p3): for F to be a viable function, there shall
3907 // exist for each argument an implicit conversion sequence
3908 // (13.3.3.1) that converts that argument to the corresponding
3909 // parameter of F.
3910 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003911 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003912 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003914 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003915 if (Candidate.Conversions[ArgIdx].isBad()) {
3916 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003917 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003918 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003919 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003920 } else {
3921 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3922 // argument for which there is no corresponding parameter is
3923 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003924 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003925 }
3926 }
3927}
3928
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003929/// \brief Add all of the function declarations in the given function set to
3930/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003931void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003932 Expr **Args, unsigned NumArgs,
3933 OverloadCandidateSet& CandidateSet,
3934 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003935 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003936 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3937 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003938 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003939 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003940 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003941 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003943 CandidateSet, SuppressUserConversions);
3944 else
John McCalla0296f72010-03-19 07:35:19 +00003945 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003946 SuppressUserConversions);
3947 } else {
John McCalla0296f72010-03-19 07:35:19 +00003948 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003949 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3950 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003951 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003952 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003953 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00003955 Args[0]->Classify(Context),
3956 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003957 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003958 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003959 else
John McCalla0296f72010-03-19 07:35:19 +00003960 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003961 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003962 Args, NumArgs, CandidateSet,
3963 SuppressUserConversions);
3964 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003965 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003966}
3967
John McCallf0f1cf02009-11-17 07:50:12 +00003968/// AddMethodCandidate - Adds a named decl (which is some kind of
3969/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003970void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003971 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003972 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00003973 Expr **Args, unsigned NumArgs,
3974 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003975 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003976 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003977 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003978
3979 if (isa<UsingShadowDecl>(Decl))
3980 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981
John McCallf0f1cf02009-11-17 07:50:12 +00003982 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3983 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3984 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003985 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3986 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003987 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003988 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003989 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003990 } else {
John McCalla0296f72010-03-19 07:35:19 +00003991 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00003992 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003993 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003994 }
3995}
3996
Douglas Gregor436424c2008-11-18 23:14:02 +00003997/// AddMethodCandidate - Adds the given C++ member function to the set
3998/// of candidate functions, using the given function call arguments
3999/// and the object argument (@c Object). For example, in a call
4000/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4001/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4002/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004003/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004004void
John McCalla0296f72010-03-19 07:35:19 +00004005Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004006 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004007 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004008 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004009 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004010 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004011 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004012 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004013 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004014 assert(!isa<CXXConstructorDecl>(Method) &&
4015 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004016
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004017 if (!CandidateSet.isNewCandidate(Method))
4018 return;
4019
Douglas Gregor27381f32009-11-23 12:27:39 +00004020 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004021 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004022
Douglas Gregor436424c2008-11-18 23:14:02 +00004023 // Add this candidate
4024 CandidateSet.push_back(OverloadCandidate());
4025 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004026 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004027 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004028 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004029 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004030 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004031
4032 unsigned NumArgsInProto = Proto->getNumArgs();
4033
4034 // (C++ 13.3.2p2): A candidate function having fewer than m
4035 // parameters is viable only if it has an ellipsis in its parameter
4036 // list (8.3.5).
4037 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4038 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004039 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004040 return;
4041 }
4042
4043 // (C++ 13.3.2p2): A candidate function having more than m parameters
4044 // is viable only if the (m+1)st parameter has a default argument
4045 // (8.3.6). For the purposes of overload resolution, the
4046 // parameter list is truncated on the right, so that there are
4047 // exactly m parameters.
4048 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4049 if (NumArgs < MinRequiredArgs) {
4050 // Not enough arguments.
4051 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004052 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004053 return;
4054 }
4055
4056 Candidate.Viable = true;
4057 Candidate.Conversions.resize(NumArgs + 1);
4058
John McCall6e9f8f62009-12-03 04:06:58 +00004059 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004060 // The implicit object argument is ignored.
4061 Candidate.IgnoreObjectArgument = true;
4062 else {
4063 // Determine the implicit conversion sequence for the object
4064 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004065 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004066 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4067 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004068 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004069 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004070 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004071 return;
4072 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004073 }
4074
4075 // Determine the implicit conversion sequences for each of the
4076 // arguments.
4077 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4078 if (ArgIdx < NumArgsInProto) {
4079 // (C++ 13.3.2p3): for F to be a viable function, there shall
4080 // exist for each argument an implicit conversion sequence
4081 // (13.3.3.1) that converts that argument to the corresponding
4082 // parameter of F.
4083 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004084 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004085 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004086 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00004087 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00004088 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004089 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004090 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004091 break;
4092 }
4093 } else {
4094 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4095 // argument for which there is no corresponding parameter is
4096 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004097 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004098 }
4099 }
4100}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101
Douglas Gregor97628d62009-08-21 00:16:32 +00004102/// \brief Add a C++ member function template as a candidate to the candidate
4103/// set, using template argument deduction to produce an appropriate member
4104/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004105void
Douglas Gregor97628d62009-08-21 00:16:32 +00004106Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004107 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004108 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004109 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004110 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004111 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004112 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004113 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004114 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004115 if (!CandidateSet.isNewCandidate(MethodTmpl))
4116 return;
4117
Douglas Gregor97628d62009-08-21 00:16:32 +00004118 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004119 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004120 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004121 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004122 // candidate functions in the usual way.113) A given name can refer to one
4123 // or more function templates and also to a set of overloaded non-template
4124 // functions. In such a case, the candidate functions generated from each
4125 // function template are combined with the set of non-template candidate
4126 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004127 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004128 FunctionDecl *Specialization = 0;
4129 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004130 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004131 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004132 CandidateSet.push_back(OverloadCandidate());
4133 OverloadCandidate &Candidate = CandidateSet.back();
4134 Candidate.FoundDecl = FoundDecl;
4135 Candidate.Function = MethodTmpl->getTemplatedDecl();
4136 Candidate.Viable = false;
4137 Candidate.FailureKind = ovl_fail_bad_deduction;
4138 Candidate.IsSurrogate = false;
4139 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004140 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004142 Info);
4143 return;
4144 }
Mike Stump11289f42009-09-09 15:08:12 +00004145
Douglas Gregor97628d62009-08-21 00:16:32 +00004146 // Add the function template specialization produced by template argument
4147 // deduction as a candidate.
4148 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004149 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004150 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004151 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004152 ActingContext, ObjectType, ObjectClassification,
4153 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004154}
4155
Douglas Gregor05155d82009-08-21 23:19:43 +00004156/// \brief Add a C++ function template specialization as a candidate
4157/// in the candidate set, using template argument deduction to produce
4158/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004159void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004160Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004161 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004162 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004163 Expr **Args, unsigned NumArgs,
4164 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004165 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004166 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4167 return;
4168
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004169 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004170 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004171 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004172 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004173 // candidate functions in the usual way.113) A given name can refer to one
4174 // or more function templates and also to a set of overloaded non-template
4175 // functions. In such a case, the candidate functions generated from each
4176 // function template are combined with the set of non-template candidate
4177 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004178 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004179 FunctionDecl *Specialization = 0;
4180 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004181 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004182 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004183 CandidateSet.push_back(OverloadCandidate());
4184 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004185 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004186 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4187 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004188 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004189 Candidate.IsSurrogate = false;
4190 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004191 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004193 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004194 return;
4195 }
Mike Stump11289f42009-09-09 15:08:12 +00004196
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004197 // Add the function template specialization produced by template argument
4198 // deduction as a candidate.
4199 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004200 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004201 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004202}
Mike Stump11289f42009-09-09 15:08:12 +00004203
Douglas Gregora1f013e2008-11-07 22:36:19 +00004204/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004205/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004206/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004207/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004208/// (which may or may not be the same type as the type that the
4209/// conversion function produces).
4210void
4211Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004212 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004213 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004214 Expr *From, QualType ToType,
4215 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004216 assert(!Conversion->getDescribedFunctionTemplate() &&
4217 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004218 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004219 if (!CandidateSet.isNewCandidate(Conversion))
4220 return;
4221
Douglas Gregor27381f32009-11-23 12:27:39 +00004222 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004223 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004224
Douglas Gregora1f013e2008-11-07 22:36:19 +00004225 // Add this candidate
4226 CandidateSet.push_back(OverloadCandidate());
4227 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004228 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004229 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004230 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004231 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004232 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004233 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004234 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004235 Candidate.Viable = true;
4236 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004237 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004238
Douglas Gregor6affc782010-08-19 15:37:02 +00004239 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240 // For conversion functions, the function is considered to be a member of
4241 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004242 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004243 //
4244 // Determine the implicit conversion sequence for the implicit
4245 // object parameter.
4246 QualType ImplicitParamType = From->getType();
4247 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4248 ImplicitParamType = FromPtrType->getPointeeType();
4249 CXXRecordDecl *ConversionContext
4250 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004251
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004252 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253 = TryObjectArgumentInitialization(*this, From->getType(),
4254 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004255 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004256
John McCall0d1da222010-01-12 00:44:57 +00004257 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004258 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004259 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004260 return;
4261 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004262
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004264 // derived to base as such conversions are given Conversion Rank. They only
4265 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4266 QualType FromCanon
4267 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4268 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4269 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4270 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004271 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004272 return;
4273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004274
Douglas Gregora1f013e2008-11-07 22:36:19 +00004275 // To determine what the conversion from the result of calling the
4276 // conversion function to the type we're eventually trying to
4277 // convert to (ToType), we need to synthesize a call to the
4278 // conversion function and attempt copy initialization from it. This
4279 // makes sure that we get the right semantics with respect to
4280 // lvalues/rvalues and the type. Fortunately, we can allocate this
4281 // call on the stack and we don't need its arguments to be
4282 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004283 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004284 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004285 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4286 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004287 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004288 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004289
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004290 QualType CallResultType
4291 = Conversion->getConversionType().getNonLValueExprType(Context);
4292 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4293 Candidate.Viable = false;
4294 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4295 return;
4296 }
4297
John McCall7decc9e2010-11-18 06:31:45 +00004298 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4299
Mike Stump11289f42009-09-09 15:08:12 +00004300 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004301 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4302 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004303 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004304 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004305 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004306 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004307 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004308 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004309
John McCall0d1da222010-01-12 00:44:57 +00004310 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004311 case ImplicitConversionSequence::StandardConversion:
4312 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004314 // C++ [over.ics.user]p3:
4315 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004317 // shall have exact match rank.
4318 if (Conversion->getPrimaryTemplate() &&
4319 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4320 Candidate.Viable = false;
4321 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregorcba72b12011-01-21 05:18:22 +00004324 // C++0x [dcl.init.ref]p5:
4325 // In the second case, if the reference is an rvalue reference and
4326 // the second standard conversion sequence of the user-defined
4327 // conversion sequence includes an lvalue-to-rvalue conversion, the
4328 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004330 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4331 Candidate.Viable = false;
4332 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4333 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004334 break;
4335
4336 case ImplicitConversionSequence::BadConversion:
4337 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004338 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004339 break;
4340
4341 default:
Mike Stump11289f42009-09-09 15:08:12 +00004342 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004343 "Can only end up with a standard conversion sequence or failure");
4344 }
4345}
4346
Douglas Gregor05155d82009-08-21 23:19:43 +00004347/// \brief Adds a conversion function template specialization
4348/// candidate to the overload set, using template argument deduction
4349/// to deduce the template arguments of the conversion function
4350/// template from the type that we are converting to (C++
4351/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004352void
Douglas Gregor05155d82009-08-21 23:19:43 +00004353Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004354 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004355 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004356 Expr *From, QualType ToType,
4357 OverloadCandidateSet &CandidateSet) {
4358 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4359 "Only conversion function templates permitted here");
4360
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004361 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4362 return;
4363
John McCallbc077cf2010-02-08 23:07:23 +00004364 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004365 CXXConversionDecl *Specialization = 0;
4366 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004367 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004368 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004369 CandidateSet.push_back(OverloadCandidate());
4370 OverloadCandidate &Candidate = CandidateSet.back();
4371 Candidate.FoundDecl = FoundDecl;
4372 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4373 Candidate.Viable = false;
4374 Candidate.FailureKind = ovl_fail_bad_deduction;
4375 Candidate.IsSurrogate = false;
4376 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004377 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004379 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004380 return;
4381 }
Mike Stump11289f42009-09-09 15:08:12 +00004382
Douglas Gregor05155d82009-08-21 23:19:43 +00004383 // Add the conversion function template specialization produced by
4384 // template argument deduction as a candidate.
4385 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004386 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004387 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004388}
4389
Douglas Gregorab7897a2008-11-19 22:57:39 +00004390/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4391/// converts the given @c Object to a function pointer via the
4392/// conversion function @c Conversion, and then attempts to call it
4393/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4394/// the type of function that we'll eventually be calling.
4395void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004396 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004397 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004398 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004399 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004400 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004401 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004402 if (!CandidateSet.isNewCandidate(Conversion))
4403 return;
4404
Douglas Gregor27381f32009-11-23 12:27:39 +00004405 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004406 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004407
Douglas Gregorab7897a2008-11-19 22:57:39 +00004408 CandidateSet.push_back(OverloadCandidate());
4409 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004410 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004411 Candidate.Function = 0;
4412 Candidate.Surrogate = Conversion;
4413 Candidate.Viable = true;
4414 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004415 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004416 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004417 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004418
4419 // Determine the implicit conversion sequence for the implicit
4420 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004421 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004423 Object->Classify(Context),
4424 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004425 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004426 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004427 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004428 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004429 return;
4430 }
4431
4432 // The first conversion is actually a user-defined conversion whose
4433 // first conversion is ObjectInit's standard conversion (which is
4434 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004435 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004436 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004437 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004438 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004440 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004441 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004442 = Candidate.Conversions[0].UserDefined.Before;
4443 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4444
Mike Stump11289f42009-09-09 15:08:12 +00004445 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004446 unsigned NumArgsInProto = Proto->getNumArgs();
4447
4448 // (C++ 13.3.2p2): A candidate function having fewer than m
4449 // parameters is viable only if it has an ellipsis in its parameter
4450 // list (8.3.5).
4451 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4452 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004453 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004454 return;
4455 }
4456
4457 // Function types don't have any default arguments, so just check if
4458 // we have enough arguments.
4459 if (NumArgs < NumArgsInProto) {
4460 // Not enough arguments.
4461 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004462 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004463 return;
4464 }
4465
4466 // Determine the implicit conversion sequences for each of the
4467 // arguments.
4468 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4469 if (ArgIdx < NumArgsInProto) {
4470 // (C++ 13.3.2p3): for F to be a viable function, there shall
4471 // exist for each argument an implicit conversion sequence
4472 // (13.3.3.1) that converts that argument to the corresponding
4473 // parameter of F.
4474 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004475 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004476 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004477 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004478 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004479 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004480 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004481 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004482 break;
4483 }
4484 } else {
4485 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4486 // argument for which there is no corresponding parameter is
4487 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004488 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004489 }
4490 }
4491}
4492
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004493/// \brief Add overload candidates for overloaded operators that are
4494/// member functions.
4495///
4496/// Add the overloaded operator candidates that are member functions
4497/// for the operator Op that was used in an operator expression such
4498/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4499/// CandidateSet will store the added overload candidates. (C++
4500/// [over.match.oper]).
4501void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4502 SourceLocation OpLoc,
4503 Expr **Args, unsigned NumArgs,
4504 OverloadCandidateSet& CandidateSet,
4505 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004506 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4507
4508 // C++ [over.match.oper]p3:
4509 // For a unary operator @ with an operand of a type whose
4510 // cv-unqualified version is T1, and for a binary operator @ with
4511 // a left operand of a type whose cv-unqualified version is T1 and
4512 // a right operand of a type whose cv-unqualified version is T2,
4513 // three sets of candidate functions, designated member
4514 // candidates, non-member candidates and built-in candidates, are
4515 // constructed as follows:
4516 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004517
4518 // -- If T1 is a class type, the set of member candidates is the
4519 // result of the qualified lookup of T1::operator@
4520 // (13.3.1.1.1); otherwise, the set of member candidates is
4521 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004522 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004523 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004524 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004525 return;
Mike Stump11289f42009-09-09 15:08:12 +00004526
John McCall27b18f82009-11-17 02:14:36 +00004527 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4528 LookupQualifiedName(Operators, T1Rec->getDecl());
4529 Operators.suppressDiagnostics();
4530
Mike Stump11289f42009-09-09 15:08:12 +00004531 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004532 OperEnd = Operators.end();
4533 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004534 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004535 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004536 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004537 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004538 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004539 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004540}
4541
Douglas Gregora11693b2008-11-12 17:17:38 +00004542/// AddBuiltinCandidate - Add a candidate for a built-in
4543/// operator. ResultTy and ParamTys are the result and parameter types
4544/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004545/// arguments being passed to the candidate. IsAssignmentOperator
4546/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004547/// operator. NumContextualBoolArguments is the number of arguments
4548/// (at the beginning of the argument list) that will be contextually
4549/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004550void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004551 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004552 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004553 bool IsAssignmentOperator,
4554 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004555 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004556 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004557
Douglas Gregora11693b2008-11-12 17:17:38 +00004558 // Add this candidate
4559 CandidateSet.push_back(OverloadCandidate());
4560 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004561 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004562 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004563 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004564 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004565 Candidate.BuiltinTypes.ResultTy = ResultTy;
4566 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4567 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4568
4569 // Determine the implicit conversion sequences for each of the
4570 // arguments.
4571 Candidate.Viable = true;
4572 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004573 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004574 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004575 // C++ [over.match.oper]p4:
4576 // For the built-in assignment operators, conversions of the
4577 // left operand are restricted as follows:
4578 // -- no temporaries are introduced to hold the left operand, and
4579 // -- no user-defined conversions are applied to the left
4580 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004581 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004582 //
4583 // We block these conversions by turning off user-defined
4584 // conversions, since that is the only way that initialization of
4585 // a reference to a non-class type can occur from something that
4586 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004587 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004588 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004589 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004590 Candidate.Conversions[ArgIdx]
4591 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004592 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004593 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004594 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004595 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004596 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004597 }
John McCall0d1da222010-01-12 00:44:57 +00004598 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004599 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004600 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004601 break;
4602 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004603 }
4604}
4605
4606/// BuiltinCandidateTypeSet - A set of types that will be used for the
4607/// candidate operator functions for built-in operators (C++
4608/// [over.built]). The types are separated into pointer types and
4609/// enumeration types.
4610class BuiltinCandidateTypeSet {
4611 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004612 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004613
4614 /// PointerTypes - The set of pointer types that will be used in the
4615 /// built-in candidates.
4616 TypeSet PointerTypes;
4617
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004618 /// MemberPointerTypes - The set of member pointer types that will be
4619 /// used in the built-in candidates.
4620 TypeSet MemberPointerTypes;
4621
Douglas Gregora11693b2008-11-12 17:17:38 +00004622 /// EnumerationTypes - The set of enumeration types that will be
4623 /// used in the built-in candidates.
4624 TypeSet EnumerationTypes;
4625
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004627 /// candidates.
4628 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004629
4630 /// \brief A flag indicating non-record types are viable candidates
4631 bool HasNonRecordTypes;
4632
4633 /// \brief A flag indicating whether either arithmetic or enumeration types
4634 /// were present in the candidate set.
4635 bool HasArithmeticOrEnumeralTypes;
4636
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004637 /// Sema - The semantic analysis instance where we are building the
4638 /// candidate type set.
4639 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004640
Douglas Gregora11693b2008-11-12 17:17:38 +00004641 /// Context - The AST context in which we will build the type sets.
4642 ASTContext &Context;
4643
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004644 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4645 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004646 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004647
4648public:
4649 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004650 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004651
Mike Stump11289f42009-09-09 15:08:12 +00004652 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004653 : HasNonRecordTypes(false),
4654 HasArithmeticOrEnumeralTypes(false),
4655 SemaRef(SemaRef),
4656 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004657
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004659 SourceLocation Loc,
4660 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004661 bool AllowExplicitConversions,
4662 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004663
4664 /// pointer_begin - First pointer type found;
4665 iterator pointer_begin() { return PointerTypes.begin(); }
4666
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004667 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004668 iterator pointer_end() { return PointerTypes.end(); }
4669
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004670 /// member_pointer_begin - First member pointer type found;
4671 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4672
4673 /// member_pointer_end - Past the last member pointer type found;
4674 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4675
Douglas Gregora11693b2008-11-12 17:17:38 +00004676 /// enumeration_begin - First enumeration type found;
4677 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4678
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004679 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004680 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004681
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004682 iterator vector_begin() { return VectorTypes.begin(); }
4683 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004684
4685 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4686 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004687};
4688
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004689/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004690/// the set of pointer types along with any more-qualified variants of
4691/// that type. For example, if @p Ty is "int const *", this routine
4692/// will add "int const *", "int const volatile *", "int const
4693/// restrict *", and "int const volatile restrict *" to the set of
4694/// pointer types. Returns true if the add of @p Ty itself succeeded,
4695/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004696///
4697/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004698bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004699BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4700 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004701
Douglas Gregora11693b2008-11-12 17:17:38 +00004702 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004703 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004704 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004706 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004707 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004708 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004709 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004710 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004711 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004712 buildObjCPtr = true;
4713 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004714 else
4715 assert(false && "type was not a pointer type!");
4716 }
4717 else
4718 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719
Sebastian Redl4990a632009-11-18 20:39:26 +00004720 // Don't add qualified variants of arrays. For one, they're not allowed
4721 // (the qualifier would sink to the element type), and for another, the
4722 // only overload situation where it matters is subscript or pointer +- int,
4723 // and those shouldn't have qualifier variants anyway.
4724 if (PointeeTy->isArrayType())
4725 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004726 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004727 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004728 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004729 bool hasVolatile = VisibleQuals.hasVolatile();
4730 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
John McCall8ccfcb52009-09-24 19:53:00 +00004732 // Iterate through all strict supersets of BaseCVR.
4733 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4734 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004735 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4736 // in the types.
4737 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4738 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004739 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004740 if (!buildObjCPtr)
4741 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4742 else
4743 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004744 }
4745
4746 return true;
4747}
4748
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004749/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4750/// to the set of pointer types along with any more-qualified variants of
4751/// that type. For example, if @p Ty is "int const *", this routine
4752/// will add "int const *", "int const volatile *", "int const
4753/// restrict *", and "int const volatile restrict *" to the set of
4754/// pointer types. Returns true if the add of @p Ty itself succeeded,
4755/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004756///
4757/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004758bool
4759BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4760 QualType Ty) {
4761 // Insert this type.
4762 if (!MemberPointerTypes.insert(Ty))
4763 return false;
4764
John McCall8ccfcb52009-09-24 19:53:00 +00004765 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4766 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004767
John McCall8ccfcb52009-09-24 19:53:00 +00004768 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004769 // Don't add qualified variants of arrays. For one, they're not allowed
4770 // (the qualifier would sink to the element type), and for another, the
4771 // only overload situation where it matters is subscript or pointer +- int,
4772 // and those shouldn't have qualifier variants anyway.
4773 if (PointeeTy->isArrayType())
4774 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004775 const Type *ClassTy = PointerTy->getClass();
4776
4777 // Iterate through all strict supersets of the pointee type's CVR
4778 // qualifiers.
4779 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4780 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4781 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782
John McCall8ccfcb52009-09-24 19:53:00 +00004783 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004784 MemberPointerTypes.insert(
4785 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004786 }
4787
4788 return true;
4789}
4790
Douglas Gregora11693b2008-11-12 17:17:38 +00004791/// AddTypesConvertedFrom - Add each of the types to which the type @p
4792/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004793/// primarily interested in pointer types and enumeration types. We also
4794/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004795/// AllowUserConversions is true if we should look at the conversion
4796/// functions of a class type, and AllowExplicitConversions if we
4797/// should also include the explicit conversion functions of a class
4798/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004799void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004800BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004801 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004802 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004803 bool AllowExplicitConversions,
4804 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004805 // Only deal with canonical types.
4806 Ty = Context.getCanonicalType(Ty);
4807
4808 // Look through reference types; they aren't part of the type of an
4809 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004810 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004811 Ty = RefTy->getPointeeType();
4812
John McCall33ddac02011-01-19 10:06:00 +00004813 // If we're dealing with an array type, decay to the pointer.
4814 if (Ty->isArrayType())
4815 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4816
4817 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004818 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004819
Chandler Carruth00a38332010-12-13 01:44:01 +00004820 // Flag if we ever add a non-record type.
4821 const RecordType *TyRec = Ty->getAs<RecordType>();
4822 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4823
Chandler Carruth00a38332010-12-13 01:44:01 +00004824 // Flag if we encounter an arithmetic type.
4825 HasArithmeticOrEnumeralTypes =
4826 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4827
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004828 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4829 PointerTypes.insert(Ty);
4830 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004831 // Insert our type, and its more-qualified variants, into the set
4832 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004833 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004834 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004835 } else if (Ty->isMemberPointerType()) {
4836 // Member pointers are far easier, since the pointee can't be converted.
4837 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4838 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004839 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004840 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004841 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004842 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004843 // We treat vector types as arithmetic types in many contexts as an
4844 // extension.
4845 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004846 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004847 } else if (AllowUserConversions && TyRec) {
4848 // No conversion functions in incomplete types.
4849 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4850 return;
Mike Stump11289f42009-09-09 15:08:12 +00004851
Chandler Carruth00a38332010-12-13 01:44:01 +00004852 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4853 const UnresolvedSetImpl *Conversions
4854 = ClassDecl->getVisibleConversionFunctions();
4855 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4856 E = Conversions->end(); I != E; ++I) {
4857 NamedDecl *D = I.getDecl();
4858 if (isa<UsingShadowDecl>(D))
4859 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004860
Chandler Carruth00a38332010-12-13 01:44:01 +00004861 // Skip conversion function templates; they don't tell us anything
4862 // about which builtin types we can convert to.
4863 if (isa<FunctionTemplateDecl>(D))
4864 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004865
Chandler Carruth00a38332010-12-13 01:44:01 +00004866 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4867 if (AllowExplicitConversions || !Conv->isExplicit()) {
4868 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4869 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004870 }
4871 }
4872 }
4873}
4874
Douglas Gregor84605ae2009-08-24 13:43:27 +00004875/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4876/// the volatile- and non-volatile-qualified assignment operators for the
4877/// given type to the candidate set.
4878static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4879 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004880 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004881 unsigned NumArgs,
4882 OverloadCandidateSet &CandidateSet) {
4883 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004884
Douglas Gregor84605ae2009-08-24 13:43:27 +00004885 // T& operator=(T&, T)
4886 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4887 ParamTypes[1] = T;
4888 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4889 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004890
Douglas Gregor84605ae2009-08-24 13:43:27 +00004891 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4892 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004893 ParamTypes[0]
4894 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004895 ParamTypes[1] = T;
4896 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004897 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004898 }
4899}
Mike Stump11289f42009-09-09 15:08:12 +00004900
Sebastian Redl1054fae2009-10-25 17:03:50 +00004901/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4902/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004903static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4904 Qualifiers VRQuals;
4905 const RecordType *TyRec;
4906 if (const MemberPointerType *RHSMPType =
4907 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004908 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004909 else
4910 TyRec = ArgExpr->getType()->getAs<RecordType>();
4911 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004912 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004913 VRQuals.addVolatile();
4914 VRQuals.addRestrict();
4915 return VRQuals;
4916 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004918 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004919 if (!ClassDecl->hasDefinition())
4920 return VRQuals;
4921
John McCallad371252010-01-20 00:46:10 +00004922 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004923 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
John McCallad371252010-01-20 00:46:10 +00004925 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004926 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004927 NamedDecl *D = I.getDecl();
4928 if (isa<UsingShadowDecl>(D))
4929 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4930 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004931 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4932 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4933 CanTy = ResTypeRef->getPointeeType();
4934 // Need to go down the pointer/mempointer chain and add qualifiers
4935 // as see them.
4936 bool done = false;
4937 while (!done) {
4938 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4939 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004941 CanTy->getAs<MemberPointerType>())
4942 CanTy = ResTypeMPtr->getPointeeType();
4943 else
4944 done = true;
4945 if (CanTy.isVolatileQualified())
4946 VRQuals.addVolatile();
4947 if (CanTy.isRestrictQualified())
4948 VRQuals.addRestrict();
4949 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4950 return VRQuals;
4951 }
4952 }
4953 }
4954 return VRQuals;
4955}
John McCall52872982010-11-13 05:51:15 +00004956
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004957namespace {
John McCall52872982010-11-13 05:51:15 +00004958
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004959/// \brief Helper class to manage the addition of builtin operator overload
4960/// candidates. It provides shared state and utility methods used throughout
4961/// the process, as well as a helper method to add each group of builtin
4962/// operator overloads from the standard to a candidate set.
4963class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004964 // Common instance state available to all overload candidate addition methods.
4965 Sema &S;
4966 Expr **Args;
4967 unsigned NumArgs;
4968 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004969 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004970 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4971 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004972
Chandler Carruthc6586e52010-12-12 10:35:00 +00004973 // Define some constants used to index and iterate over the arithemetic types
4974 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004975 // The "promoted arithmetic types" are the arithmetic
4976 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004977 static const unsigned FirstIntegralType = 3;
4978 static const unsigned LastIntegralType = 18;
4979 static const unsigned FirstPromotedIntegralType = 3,
4980 LastPromotedIntegralType = 9;
4981 static const unsigned FirstPromotedArithmeticType = 0,
4982 LastPromotedArithmeticType = 9;
4983 static const unsigned NumArithmeticTypes = 18;
4984
Chandler Carruthc6586e52010-12-12 10:35:00 +00004985 /// \brief Get the canonical type for a given arithmetic type index.
4986 CanQualType getArithmeticType(unsigned index) {
4987 assert(index < NumArithmeticTypes);
4988 static CanQualType ASTContext::* const
4989 ArithmeticTypes[NumArithmeticTypes] = {
4990 // Start of promoted types.
4991 &ASTContext::FloatTy,
4992 &ASTContext::DoubleTy,
4993 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004994
Chandler Carruthc6586e52010-12-12 10:35:00 +00004995 // Start of integral types.
4996 &ASTContext::IntTy,
4997 &ASTContext::LongTy,
4998 &ASTContext::LongLongTy,
4999 &ASTContext::UnsignedIntTy,
5000 &ASTContext::UnsignedLongTy,
5001 &ASTContext::UnsignedLongLongTy,
5002 // End of promoted types.
5003
5004 &ASTContext::BoolTy,
5005 &ASTContext::CharTy,
5006 &ASTContext::WCharTy,
5007 &ASTContext::Char16Ty,
5008 &ASTContext::Char32Ty,
5009 &ASTContext::SignedCharTy,
5010 &ASTContext::ShortTy,
5011 &ASTContext::UnsignedCharTy,
5012 &ASTContext::UnsignedShortTy,
5013 // End of integral types.
5014 // FIXME: What about complex?
5015 };
5016 return S.Context.*ArithmeticTypes[index];
5017 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005018
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005019 /// \brief Gets the canonical type resulting from the usual arithemetic
5020 /// converions for the given arithmetic types.
5021 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5022 // Accelerator table for performing the usual arithmetic conversions.
5023 // The rules are basically:
5024 // - if either is floating-point, use the wider floating-point
5025 // - if same signedness, use the higher rank
5026 // - if same size, use unsigned of the higher rank
5027 // - use the larger type
5028 // These rules, together with the axiom that higher ranks are
5029 // never smaller, are sufficient to precompute all of these results
5030 // *except* when dealing with signed types of higher rank.
5031 // (we could precompute SLL x UI for all known platforms, but it's
5032 // better not to make any assumptions).
5033 enum PromotedType {
5034 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5035 };
5036 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5037 [LastPromotedArithmeticType] = {
5038 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5039 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5040 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5041 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5042 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5043 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5044 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5045 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5046 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5047 };
5048
5049 assert(L < LastPromotedArithmeticType);
5050 assert(R < LastPromotedArithmeticType);
5051 int Idx = ConversionsTable[L][R];
5052
5053 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005054 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005055
5056 // Slow path: we need to compare widths.
5057 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005058 CanQualType LT = getArithmeticType(L),
5059 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005060 unsigned LW = S.Context.getIntWidth(LT),
5061 RW = S.Context.getIntWidth(RT);
5062
5063 // If they're different widths, use the signed type.
5064 if (LW > RW) return LT;
5065 else if (LW < RW) return RT;
5066
5067 // Otherwise, use the unsigned type of the signed type's rank.
5068 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5069 assert(L == SLL || R == SLL);
5070 return S.Context.UnsignedLongLongTy;
5071 }
5072
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005073 /// \brief Helper method to factor out the common pattern of adding overloads
5074 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005075 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5076 bool HasVolatile) {
5077 QualType ParamTypes[2] = {
5078 S.Context.getLValueReferenceType(CandidateTy),
5079 S.Context.IntTy
5080 };
5081
5082 // Non-volatile version.
5083 if (NumArgs == 1)
5084 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5085 else
5086 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5087
5088 // Use a heuristic to reduce number of builtin candidates in the set:
5089 // add volatile version only if there are conversions to a volatile type.
5090 if (HasVolatile) {
5091 ParamTypes[0] =
5092 S.Context.getLValueReferenceType(
5093 S.Context.getVolatileType(CandidateTy));
5094 if (NumArgs == 1)
5095 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5096 else
5097 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5098 }
5099 }
5100
5101public:
5102 BuiltinOperatorOverloadBuilder(
5103 Sema &S, Expr **Args, unsigned NumArgs,
5104 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005105 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005106 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5107 OverloadCandidateSet &CandidateSet)
5108 : S(S), Args(Args), NumArgs(NumArgs),
5109 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005110 HasArithmeticOrEnumeralCandidateType(
5111 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005112 CandidateTypes(CandidateTypes),
5113 CandidateSet(CandidateSet) {
5114 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005115 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005116 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005117 assert(getArithmeticType(LastPromotedIntegralType - 1)
5118 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005119 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005120 assert(getArithmeticType(FirstPromotedArithmeticType)
5121 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005122 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005123 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5124 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005125 "Invalid last promoted arithmetic type");
5126 }
5127
5128 // C++ [over.built]p3:
5129 //
5130 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5131 // is either volatile or empty, there exist candidate operator
5132 // functions of the form
5133 //
5134 // VQ T& operator++(VQ T&);
5135 // T operator++(VQ T&, int);
5136 //
5137 // C++ [over.built]p4:
5138 //
5139 // For every pair (T, VQ), where T is an arithmetic type other
5140 // than bool, and VQ is either volatile or empty, there exist
5141 // candidate operator functions of the form
5142 //
5143 // VQ T& operator--(VQ T&);
5144 // T operator--(VQ T&, int);
5145 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005146 if (!HasArithmeticOrEnumeralCandidateType)
5147 return;
5148
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005149 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5150 Arith < NumArithmeticTypes; ++Arith) {
5151 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005152 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005153 VisibleTypeConversionsQuals.hasVolatile());
5154 }
5155 }
5156
5157 // C++ [over.built]p5:
5158 //
5159 // For every pair (T, VQ), where T is a cv-qualified or
5160 // cv-unqualified object type, and VQ is either volatile or
5161 // empty, there exist candidate operator functions of the form
5162 //
5163 // T*VQ& operator++(T*VQ&);
5164 // T*VQ& operator--(T*VQ&);
5165 // T* operator++(T*VQ&, int);
5166 // T* operator--(T*VQ&, int);
5167 void addPlusPlusMinusMinusPointerOverloads() {
5168 for (BuiltinCandidateTypeSet::iterator
5169 Ptr = CandidateTypes[0].pointer_begin(),
5170 PtrEnd = CandidateTypes[0].pointer_end();
5171 Ptr != PtrEnd; ++Ptr) {
5172 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005173 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005174 continue;
5175
5176 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5177 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5178 VisibleTypeConversionsQuals.hasVolatile()));
5179 }
5180 }
5181
5182 // C++ [over.built]p6:
5183 // For every cv-qualified or cv-unqualified object type T, there
5184 // exist candidate operator functions of the form
5185 //
5186 // T& operator*(T*);
5187 //
5188 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005190 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005191 // T& operator*(T*);
5192 void addUnaryStarPointerOverloads() {
5193 for (BuiltinCandidateTypeSet::iterator
5194 Ptr = CandidateTypes[0].pointer_begin(),
5195 PtrEnd = CandidateTypes[0].pointer_end();
5196 Ptr != PtrEnd; ++Ptr) {
5197 QualType ParamTy = *Ptr;
5198 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005199 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5200 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005201
Douglas Gregor02824322011-01-26 19:30:28 +00005202 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5203 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5204 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005205
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005206 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5207 &ParamTy, Args, 1, CandidateSet);
5208 }
5209 }
5210
5211 // C++ [over.built]p9:
5212 // For every promoted arithmetic type T, there exist candidate
5213 // operator functions of the form
5214 //
5215 // T operator+(T);
5216 // T operator-(T);
5217 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005218 if (!HasArithmeticOrEnumeralCandidateType)
5219 return;
5220
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005221 for (unsigned Arith = FirstPromotedArithmeticType;
5222 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005223 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005224 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5225 }
5226
5227 // Extension: We also add these operators for vector types.
5228 for (BuiltinCandidateTypeSet::iterator
5229 Vec = CandidateTypes[0].vector_begin(),
5230 VecEnd = CandidateTypes[0].vector_end();
5231 Vec != VecEnd; ++Vec) {
5232 QualType VecTy = *Vec;
5233 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5234 }
5235 }
5236
5237 // C++ [over.built]p8:
5238 // For every type T, there exist candidate operator functions of
5239 // the form
5240 //
5241 // T* operator+(T*);
5242 void addUnaryPlusPointerOverloads() {
5243 for (BuiltinCandidateTypeSet::iterator
5244 Ptr = CandidateTypes[0].pointer_begin(),
5245 PtrEnd = CandidateTypes[0].pointer_end();
5246 Ptr != PtrEnd; ++Ptr) {
5247 QualType ParamTy = *Ptr;
5248 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5249 }
5250 }
5251
5252 // C++ [over.built]p10:
5253 // For every promoted integral type T, there exist candidate
5254 // operator functions of the form
5255 //
5256 // T operator~(T);
5257 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005258 if (!HasArithmeticOrEnumeralCandidateType)
5259 return;
5260
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005261 for (unsigned Int = FirstPromotedIntegralType;
5262 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005263 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005264 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5265 }
5266
5267 // Extension: We also add this operator for vector types.
5268 for (BuiltinCandidateTypeSet::iterator
5269 Vec = CandidateTypes[0].vector_begin(),
5270 VecEnd = CandidateTypes[0].vector_end();
5271 Vec != VecEnd; ++Vec) {
5272 QualType VecTy = *Vec;
5273 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5274 }
5275 }
5276
5277 // C++ [over.match.oper]p16:
5278 // For every pointer to member type T, there exist candidate operator
5279 // functions of the form
5280 //
5281 // bool operator==(T,T);
5282 // bool operator!=(T,T);
5283 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5284 /// Set of (canonical) types that we've already handled.
5285 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5286
5287 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5288 for (BuiltinCandidateTypeSet::iterator
5289 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5290 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5291 MemPtr != MemPtrEnd;
5292 ++MemPtr) {
5293 // Don't add the same builtin candidate twice.
5294 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5295 continue;
5296
5297 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5298 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5299 CandidateSet);
5300 }
5301 }
5302 }
5303
5304 // C++ [over.built]p15:
5305 //
5306 // For every pointer or enumeration type T, there exist
5307 // candidate operator functions of the form
5308 //
5309 // bool operator<(T, T);
5310 // bool operator>(T, T);
5311 // bool operator<=(T, T);
5312 // bool operator>=(T, T);
5313 // bool operator==(T, T);
5314 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005315 void addRelationalPointerOrEnumeralOverloads() {
5316 // C++ [over.built]p1:
5317 // If there is a user-written candidate with the same name and parameter
5318 // types as a built-in candidate operator function, the built-in operator
5319 // function is hidden and is not included in the set of candidate
5320 // functions.
5321 //
5322 // The text is actually in a note, but if we don't implement it then we end
5323 // up with ambiguities when the user provides an overloaded operator for
5324 // an enumeration type. Note that only enumeration types have this problem,
5325 // so we track which enumeration types we've seen operators for. Also, the
5326 // only other overloaded operator with enumeration argumenst, operator=,
5327 // cannot be overloaded for enumeration types, so this is the only place
5328 // where we must suppress candidates like this.
5329 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5330 UserDefinedBinaryOperators;
5331
5332 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5333 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5334 CandidateTypes[ArgIdx].enumeration_end()) {
5335 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5336 CEnd = CandidateSet.end();
5337 C != CEnd; ++C) {
5338 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5339 continue;
5340
5341 QualType FirstParamType =
5342 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5343 QualType SecondParamType =
5344 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5345
5346 // Skip if either parameter isn't of enumeral type.
5347 if (!FirstParamType->isEnumeralType() ||
5348 !SecondParamType->isEnumeralType())
5349 continue;
5350
5351 // Add this operator to the set of known user-defined operators.
5352 UserDefinedBinaryOperators.insert(
5353 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5354 S.Context.getCanonicalType(SecondParamType)));
5355 }
5356 }
5357 }
5358
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005359 /// Set of (canonical) types that we've already handled.
5360 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5361
5362 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5363 for (BuiltinCandidateTypeSet::iterator
5364 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5365 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5366 Ptr != PtrEnd; ++Ptr) {
5367 // Don't add the same builtin candidate twice.
5368 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5369 continue;
5370
5371 QualType ParamTypes[2] = { *Ptr, *Ptr };
5372 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5373 CandidateSet);
5374 }
5375 for (BuiltinCandidateTypeSet::iterator
5376 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5377 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5378 Enum != EnumEnd; ++Enum) {
5379 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5380
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005381 // Don't add the same builtin candidate twice, or if a user defined
5382 // candidate exists.
5383 if (!AddedTypes.insert(CanonType) ||
5384 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5385 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005386 continue;
5387
5388 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005389 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5390 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005391 }
5392 }
5393 }
5394
5395 // C++ [over.built]p13:
5396 //
5397 // For every cv-qualified or cv-unqualified object type T
5398 // there exist candidate operator functions of the form
5399 //
5400 // T* operator+(T*, ptrdiff_t);
5401 // T& operator[](T*, ptrdiff_t); [BELOW]
5402 // T* operator-(T*, ptrdiff_t);
5403 // T* operator+(ptrdiff_t, T*);
5404 // T& operator[](ptrdiff_t, T*); [BELOW]
5405 //
5406 // C++ [over.built]p14:
5407 //
5408 // For every T, where T is a pointer to object type, there
5409 // exist candidate operator functions of the form
5410 //
5411 // ptrdiff_t operator-(T, T);
5412 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5413 /// Set of (canonical) types that we've already handled.
5414 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5415
5416 for (int Arg = 0; Arg < 2; ++Arg) {
5417 QualType AsymetricParamTypes[2] = {
5418 S.Context.getPointerDiffType(),
5419 S.Context.getPointerDiffType(),
5420 };
5421 for (BuiltinCandidateTypeSet::iterator
5422 Ptr = CandidateTypes[Arg].pointer_begin(),
5423 PtrEnd = CandidateTypes[Arg].pointer_end();
5424 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005425 QualType PointeeTy = (*Ptr)->getPointeeType();
5426 if (!PointeeTy->isObjectType())
5427 continue;
5428
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005429 AsymetricParamTypes[Arg] = *Ptr;
5430 if (Arg == 0 || Op == OO_Plus) {
5431 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5432 // T* operator+(ptrdiff_t, T*);
5433 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5434 CandidateSet);
5435 }
5436 if (Op == OO_Minus) {
5437 // ptrdiff_t operator-(T, T);
5438 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5439 continue;
5440
5441 QualType ParamTypes[2] = { *Ptr, *Ptr };
5442 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5443 Args, 2, CandidateSet);
5444 }
5445 }
5446 }
5447 }
5448
5449 // C++ [over.built]p12:
5450 //
5451 // For every pair of promoted arithmetic types L and R, there
5452 // exist candidate operator functions of the form
5453 //
5454 // LR operator*(L, R);
5455 // LR operator/(L, R);
5456 // LR operator+(L, R);
5457 // LR operator-(L, R);
5458 // bool operator<(L, R);
5459 // bool operator>(L, R);
5460 // bool operator<=(L, R);
5461 // bool operator>=(L, R);
5462 // bool operator==(L, R);
5463 // bool operator!=(L, R);
5464 //
5465 // where LR is the result of the usual arithmetic conversions
5466 // between types L and R.
5467 //
5468 // C++ [over.built]p24:
5469 //
5470 // For every pair of promoted arithmetic types L and R, there exist
5471 // candidate operator functions of the form
5472 //
5473 // LR operator?(bool, L, R);
5474 //
5475 // where LR is the result of the usual arithmetic conversions
5476 // between types L and R.
5477 // Our candidates ignore the first parameter.
5478 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005479 if (!HasArithmeticOrEnumeralCandidateType)
5480 return;
5481
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005482 for (unsigned Left = FirstPromotedArithmeticType;
5483 Left < LastPromotedArithmeticType; ++Left) {
5484 for (unsigned Right = FirstPromotedArithmeticType;
5485 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005486 QualType LandR[2] = { getArithmeticType(Left),
5487 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005488 QualType Result =
5489 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005490 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005491 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5492 }
5493 }
5494
5495 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5496 // conditional operator for vector types.
5497 for (BuiltinCandidateTypeSet::iterator
5498 Vec1 = CandidateTypes[0].vector_begin(),
5499 Vec1End = CandidateTypes[0].vector_end();
5500 Vec1 != Vec1End; ++Vec1) {
5501 for (BuiltinCandidateTypeSet::iterator
5502 Vec2 = CandidateTypes[1].vector_begin(),
5503 Vec2End = CandidateTypes[1].vector_end();
5504 Vec2 != Vec2End; ++Vec2) {
5505 QualType LandR[2] = { *Vec1, *Vec2 };
5506 QualType Result = S.Context.BoolTy;
5507 if (!isComparison) {
5508 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5509 Result = *Vec1;
5510 else
5511 Result = *Vec2;
5512 }
5513
5514 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5515 }
5516 }
5517 }
5518
5519 // C++ [over.built]p17:
5520 //
5521 // For every pair of promoted integral types L and R, there
5522 // exist candidate operator functions of the form
5523 //
5524 // LR operator%(L, R);
5525 // LR operator&(L, R);
5526 // LR operator^(L, R);
5527 // LR operator|(L, R);
5528 // L operator<<(L, R);
5529 // L operator>>(L, R);
5530 //
5531 // where LR is the result of the usual arithmetic conversions
5532 // between types L and R.
5533 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005534 if (!HasArithmeticOrEnumeralCandidateType)
5535 return;
5536
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005537 for (unsigned Left = FirstPromotedIntegralType;
5538 Left < LastPromotedIntegralType; ++Left) {
5539 for (unsigned Right = FirstPromotedIntegralType;
5540 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005541 QualType LandR[2] = { getArithmeticType(Left),
5542 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005543 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5544 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005545 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005546 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5547 }
5548 }
5549 }
5550
5551 // C++ [over.built]p20:
5552 //
5553 // For every pair (T, VQ), where T is an enumeration or
5554 // pointer to member type and VQ is either volatile or
5555 // empty, there exist candidate operator functions of the form
5556 //
5557 // VQ T& operator=(VQ T&, T);
5558 void addAssignmentMemberPointerOrEnumeralOverloads() {
5559 /// Set of (canonical) types that we've already handled.
5560 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5561
5562 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5563 for (BuiltinCandidateTypeSet::iterator
5564 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5565 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5566 Enum != EnumEnd; ++Enum) {
5567 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5568 continue;
5569
5570 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5571 CandidateSet);
5572 }
5573
5574 for (BuiltinCandidateTypeSet::iterator
5575 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5576 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5577 MemPtr != MemPtrEnd; ++MemPtr) {
5578 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5579 continue;
5580
5581 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5582 CandidateSet);
5583 }
5584 }
5585 }
5586
5587 // C++ [over.built]p19:
5588 //
5589 // For every pair (T, VQ), where T is any type and VQ is either
5590 // volatile or empty, there exist candidate operator functions
5591 // of the form
5592 //
5593 // T*VQ& operator=(T*VQ&, T*);
5594 //
5595 // C++ [over.built]p21:
5596 //
5597 // For every pair (T, VQ), where T is a cv-qualified or
5598 // cv-unqualified object type and VQ is either volatile or
5599 // empty, there exist candidate operator functions of the form
5600 //
5601 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5602 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5603 void addAssignmentPointerOverloads(bool isEqualOp) {
5604 /// Set of (canonical) types that we've already handled.
5605 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5606
5607 for (BuiltinCandidateTypeSet::iterator
5608 Ptr = CandidateTypes[0].pointer_begin(),
5609 PtrEnd = CandidateTypes[0].pointer_end();
5610 Ptr != PtrEnd; ++Ptr) {
5611 // If this is operator=, keep track of the builtin candidates we added.
5612 if (isEqualOp)
5613 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005614 else if (!(*Ptr)->getPointeeType()->isObjectType())
5615 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005616
5617 // non-volatile version
5618 QualType ParamTypes[2] = {
5619 S.Context.getLValueReferenceType(*Ptr),
5620 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5621 };
5622 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5623 /*IsAssigmentOperator=*/ isEqualOp);
5624
5625 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5626 VisibleTypeConversionsQuals.hasVolatile()) {
5627 // volatile version
5628 ParamTypes[0] =
5629 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5630 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5631 /*IsAssigmentOperator=*/isEqualOp);
5632 }
5633 }
5634
5635 if (isEqualOp) {
5636 for (BuiltinCandidateTypeSet::iterator
5637 Ptr = CandidateTypes[1].pointer_begin(),
5638 PtrEnd = CandidateTypes[1].pointer_end();
5639 Ptr != PtrEnd; ++Ptr) {
5640 // Make sure we don't add the same candidate twice.
5641 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5642 continue;
5643
Chandler Carruth8e543b32010-12-12 08:17:55 +00005644 QualType ParamTypes[2] = {
5645 S.Context.getLValueReferenceType(*Ptr),
5646 *Ptr,
5647 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005648
5649 // non-volatile version
5650 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5651 /*IsAssigmentOperator=*/true);
5652
5653 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5654 VisibleTypeConversionsQuals.hasVolatile()) {
5655 // volatile version
5656 ParamTypes[0] =
5657 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005658 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5659 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005660 }
5661 }
5662 }
5663 }
5664
5665 // C++ [over.built]p18:
5666 //
5667 // For every triple (L, VQ, R), where L is an arithmetic type,
5668 // VQ is either volatile or empty, and R is a promoted
5669 // arithmetic type, there exist candidate operator functions of
5670 // the form
5671 //
5672 // VQ L& operator=(VQ L&, R);
5673 // VQ L& operator*=(VQ L&, R);
5674 // VQ L& operator/=(VQ L&, R);
5675 // VQ L& operator+=(VQ L&, R);
5676 // VQ L& operator-=(VQ L&, R);
5677 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005678 if (!HasArithmeticOrEnumeralCandidateType)
5679 return;
5680
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005681 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5682 for (unsigned Right = FirstPromotedArithmeticType;
5683 Right < LastPromotedArithmeticType; ++Right) {
5684 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005685 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005686
5687 // Add this built-in operator as a candidate (VQ is empty).
5688 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005689 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005690 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5691 /*IsAssigmentOperator=*/isEqualOp);
5692
5693 // Add this built-in operator as a candidate (VQ is 'volatile').
5694 if (VisibleTypeConversionsQuals.hasVolatile()) {
5695 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005696 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005697 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005698 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5699 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005700 /*IsAssigmentOperator=*/isEqualOp);
5701 }
5702 }
5703 }
5704
5705 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5706 for (BuiltinCandidateTypeSet::iterator
5707 Vec1 = CandidateTypes[0].vector_begin(),
5708 Vec1End = CandidateTypes[0].vector_end();
5709 Vec1 != Vec1End; ++Vec1) {
5710 for (BuiltinCandidateTypeSet::iterator
5711 Vec2 = CandidateTypes[1].vector_begin(),
5712 Vec2End = CandidateTypes[1].vector_end();
5713 Vec2 != Vec2End; ++Vec2) {
5714 QualType ParamTypes[2];
5715 ParamTypes[1] = *Vec2;
5716 // Add this built-in operator as a candidate (VQ is empty).
5717 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5719 /*IsAssigmentOperator=*/isEqualOp);
5720
5721 // Add this built-in operator as a candidate (VQ is 'volatile').
5722 if (VisibleTypeConversionsQuals.hasVolatile()) {
5723 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5724 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005725 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5726 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005727 /*IsAssigmentOperator=*/isEqualOp);
5728 }
5729 }
5730 }
5731 }
5732
5733 // C++ [over.built]p22:
5734 //
5735 // For every triple (L, VQ, R), where L is an integral type, VQ
5736 // is either volatile or empty, and R is a promoted integral
5737 // type, there exist candidate operator functions of the form
5738 //
5739 // VQ L& operator%=(VQ L&, R);
5740 // VQ L& operator<<=(VQ L&, R);
5741 // VQ L& operator>>=(VQ L&, R);
5742 // VQ L& operator&=(VQ L&, R);
5743 // VQ L& operator^=(VQ L&, R);
5744 // VQ L& operator|=(VQ L&, R);
5745 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005746 if (!HasArithmeticOrEnumeralCandidateType)
5747 return;
5748
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005749 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5750 for (unsigned Right = FirstPromotedIntegralType;
5751 Right < LastPromotedIntegralType; ++Right) {
5752 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005753 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005754
5755 // Add this built-in operator as a candidate (VQ is empty).
5756 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005757 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005758 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5759 if (VisibleTypeConversionsQuals.hasVolatile()) {
5760 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005761 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005762 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5763 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5764 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5765 CandidateSet);
5766 }
5767 }
5768 }
5769 }
5770
5771 // C++ [over.operator]p23:
5772 //
5773 // There also exist candidate operator functions of the form
5774 //
5775 // bool operator!(bool);
5776 // bool operator&&(bool, bool);
5777 // bool operator||(bool, bool);
5778 void addExclaimOverload() {
5779 QualType ParamTy = S.Context.BoolTy;
5780 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5781 /*IsAssignmentOperator=*/false,
5782 /*NumContextualBoolArguments=*/1);
5783 }
5784 void addAmpAmpOrPipePipeOverload() {
5785 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5786 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5787 /*IsAssignmentOperator=*/false,
5788 /*NumContextualBoolArguments=*/2);
5789 }
5790
5791 // C++ [over.built]p13:
5792 //
5793 // For every cv-qualified or cv-unqualified object type T there
5794 // exist candidate operator functions of the form
5795 //
5796 // T* operator+(T*, ptrdiff_t); [ABOVE]
5797 // T& operator[](T*, ptrdiff_t);
5798 // T* operator-(T*, ptrdiff_t); [ABOVE]
5799 // T* operator+(ptrdiff_t, T*); [ABOVE]
5800 // T& operator[](ptrdiff_t, T*);
5801 void addSubscriptOverloads() {
5802 for (BuiltinCandidateTypeSet::iterator
5803 Ptr = CandidateTypes[0].pointer_begin(),
5804 PtrEnd = CandidateTypes[0].pointer_end();
5805 Ptr != PtrEnd; ++Ptr) {
5806 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5807 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005808 if (!PointeeType->isObjectType())
5809 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005810
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005811 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5812
5813 // T& operator[](T*, ptrdiff_t)
5814 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5815 }
5816
5817 for (BuiltinCandidateTypeSet::iterator
5818 Ptr = CandidateTypes[1].pointer_begin(),
5819 PtrEnd = CandidateTypes[1].pointer_end();
5820 Ptr != PtrEnd; ++Ptr) {
5821 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5822 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005823 if (!PointeeType->isObjectType())
5824 continue;
5825
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005826 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5827
5828 // T& operator[](ptrdiff_t, T*)
5829 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5830 }
5831 }
5832
5833 // C++ [over.built]p11:
5834 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5835 // C1 is the same type as C2 or is a derived class of C2, T is an object
5836 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5837 // there exist candidate operator functions of the form
5838 //
5839 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5840 //
5841 // where CV12 is the union of CV1 and CV2.
5842 void addArrowStarOverloads() {
5843 for (BuiltinCandidateTypeSet::iterator
5844 Ptr = CandidateTypes[0].pointer_begin(),
5845 PtrEnd = CandidateTypes[0].pointer_end();
5846 Ptr != PtrEnd; ++Ptr) {
5847 QualType C1Ty = (*Ptr);
5848 QualType C1;
5849 QualifierCollector Q1;
5850 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5851 if (!isa<RecordType>(C1))
5852 continue;
5853 // heuristic to reduce number of builtin candidates in the set.
5854 // Add volatile/restrict version only if there are conversions to a
5855 // volatile/restrict type.
5856 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5857 continue;
5858 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5859 continue;
5860 for (BuiltinCandidateTypeSet::iterator
5861 MemPtr = CandidateTypes[1].member_pointer_begin(),
5862 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5863 MemPtr != MemPtrEnd; ++MemPtr) {
5864 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5865 QualType C2 = QualType(mptr->getClass(), 0);
5866 C2 = C2.getUnqualifiedType();
5867 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5868 break;
5869 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5870 // build CV12 T&
5871 QualType T = mptr->getPointeeType();
5872 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5873 T.isVolatileQualified())
5874 continue;
5875 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5876 T.isRestrictQualified())
5877 continue;
5878 T = Q1.apply(S.Context, T);
5879 QualType ResultTy = S.Context.getLValueReferenceType(T);
5880 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5881 }
5882 }
5883 }
5884
5885 // Note that we don't consider the first argument, since it has been
5886 // contextually converted to bool long ago. The candidates below are
5887 // therefore added as binary.
5888 //
5889 // C++ [over.built]p25:
5890 // For every type T, where T is a pointer, pointer-to-member, or scoped
5891 // enumeration type, there exist candidate operator functions of the form
5892 //
5893 // T operator?(bool, T, T);
5894 //
5895 void addConditionalOperatorOverloads() {
5896 /// Set of (canonical) types that we've already handled.
5897 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5898
5899 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5900 for (BuiltinCandidateTypeSet::iterator
5901 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5902 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5903 Ptr != PtrEnd; ++Ptr) {
5904 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5905 continue;
5906
5907 QualType ParamTypes[2] = { *Ptr, *Ptr };
5908 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5909 }
5910
5911 for (BuiltinCandidateTypeSet::iterator
5912 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5913 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5914 MemPtr != MemPtrEnd; ++MemPtr) {
5915 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5916 continue;
5917
5918 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5919 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5920 }
5921
5922 if (S.getLangOptions().CPlusPlus0x) {
5923 for (BuiltinCandidateTypeSet::iterator
5924 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5925 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5926 Enum != EnumEnd; ++Enum) {
5927 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5928 continue;
5929
5930 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5931 continue;
5932
5933 QualType ParamTypes[2] = { *Enum, *Enum };
5934 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5935 }
5936 }
5937 }
5938 }
5939};
5940
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005941} // end anonymous namespace
5942
5943/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5944/// operator overloads to the candidate set (C++ [over.built]), based
5945/// on the operator @p Op and the arguments given. For example, if the
5946/// operator is a binary '+', this routine might add "int
5947/// operator+(int, int)" to cover integer addition.
5948void
5949Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5950 SourceLocation OpLoc,
5951 Expr **Args, unsigned NumArgs,
5952 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005953 // Find all of the types that the arguments can convert to, but only
5954 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005955 // that make use of these types. Also record whether we encounter non-record
5956 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005957 Qualifiers VisibleTypeConversionsQuals;
5958 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005959 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5960 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005961
5962 bool HasNonRecordCandidateType = false;
5963 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005964 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5965 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5966 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5967 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5968 OpLoc,
5969 true,
5970 (Op == OO_Exclaim ||
5971 Op == OO_AmpAmp ||
5972 Op == OO_PipePipe),
5973 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005974 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5975 CandidateTypes[ArgIdx].hasNonRecordTypes();
5976 HasArithmeticOrEnumeralCandidateType =
5977 HasArithmeticOrEnumeralCandidateType ||
5978 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005979 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005980
Chandler Carruth00a38332010-12-13 01:44:01 +00005981 // Exit early when no non-record types have been added to the candidate set
5982 // for any of the arguments to the operator.
5983 if (!HasNonRecordCandidateType)
5984 return;
5985
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005986 // Setup an object to manage the common state for building overloads.
5987 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5988 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005989 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005990 CandidateTypes, CandidateSet);
5991
5992 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005993 switch (Op) {
5994 case OO_None:
5995 case NUM_OVERLOADED_OPERATORS:
5996 assert(false && "Expected an overloaded operator");
5997 break;
5998
Chandler Carruth5184de02010-12-12 08:51:33 +00005999 case OO_New:
6000 case OO_Delete:
6001 case OO_Array_New:
6002 case OO_Array_Delete:
6003 case OO_Call:
6004 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6005 break;
6006
6007 case OO_Comma:
6008 case OO_Arrow:
6009 // C++ [over.match.oper]p3:
6010 // -- For the operator ',', the unary operator '&', or the
6011 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006012 break;
6013
6014 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006015 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006016 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006017 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006018
6019 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006020 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006021 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006022 } else {
6023 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6024 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6025 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006026 break;
6027
Chandler Carruth5184de02010-12-12 08:51:33 +00006028 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006029 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006030 OpBuilder.addUnaryStarPointerOverloads();
6031 else
6032 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6033 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006034
Chandler Carruth5184de02010-12-12 08:51:33 +00006035 case OO_Slash:
6036 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006037 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006038
6039 case OO_PlusPlus:
6040 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006041 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6042 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006043 break;
6044
Douglas Gregor84605ae2009-08-24 13:43:27 +00006045 case OO_EqualEqual:
6046 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006047 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006048 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006049
Douglas Gregora11693b2008-11-12 17:17:38 +00006050 case OO_Less:
6051 case OO_Greater:
6052 case OO_LessEqual:
6053 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006054 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006055 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6056 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006057
Douglas Gregora11693b2008-11-12 17:17:38 +00006058 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006059 case OO_Caret:
6060 case OO_Pipe:
6061 case OO_LessLess:
6062 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006063 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006064 break;
6065
Chandler Carruth5184de02010-12-12 08:51:33 +00006066 case OO_Amp: // '&' is either unary or binary
6067 if (NumArgs == 1)
6068 // C++ [over.match.oper]p3:
6069 // -- For the operator ',', the unary operator '&', or the
6070 // operator '->', the built-in candidates set is empty.
6071 break;
6072
6073 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6074 break;
6075
6076 case OO_Tilde:
6077 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6078 break;
6079
Douglas Gregora11693b2008-11-12 17:17:38 +00006080 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006081 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006082 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006083
6084 case OO_PlusEqual:
6085 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006086 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006087 // Fall through.
6088
6089 case OO_StarEqual:
6090 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006091 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006092 break;
6093
6094 case OO_PercentEqual:
6095 case OO_LessLessEqual:
6096 case OO_GreaterGreaterEqual:
6097 case OO_AmpEqual:
6098 case OO_CaretEqual:
6099 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006100 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006101 break;
6102
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006103 case OO_Exclaim:
6104 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006105 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006106
Douglas Gregora11693b2008-11-12 17:17:38 +00006107 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006108 case OO_PipePipe:
6109 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006110 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006111
6112 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006113 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006114 break;
6115
6116 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006117 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006118 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006119
6120 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006121 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006122 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6123 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006124 }
6125}
6126
Douglas Gregore254f902009-02-04 00:32:51 +00006127/// \brief Add function candidates found via argument-dependent lookup
6128/// to the set of overloading candidates.
6129///
6130/// This routine performs argument-dependent name lookup based on the
6131/// given function name (which may also be an operator name) and adds
6132/// all of the overload candidates found by ADL to the overload
6133/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006134void
Douglas Gregore254f902009-02-04 00:32:51 +00006135Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006136 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006137 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006138 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006139 OverloadCandidateSet& CandidateSet,
6140 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00006141 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006142
John McCall91f61fc2010-01-26 06:04:06 +00006143 // FIXME: This approach for uniquing ADL results (and removing
6144 // redundant candidates from the set) relies on pointer-equality,
6145 // which means we need to key off the canonical decl. However,
6146 // always going back to the canonical decl might not get us the
6147 // right set of default arguments. What default arguments are
6148 // we supposed to consider on ADL candidates, anyway?
6149
Douglas Gregorcabea402009-09-22 15:41:20 +00006150 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00006151 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00006152
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006153 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006154 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6155 CandEnd = CandidateSet.end();
6156 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006157 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006158 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006159 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006160 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006161 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006162
6163 // For each of the ADL candidates we found, add it to the overload
6164 // set.
John McCall8fe68082010-01-26 07:16:45 +00006165 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006166 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006167 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006168 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006169 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006170
John McCalla0296f72010-03-19 07:35:19 +00006171 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006172 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006173 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006174 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006175 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006176 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006177 }
Douglas Gregore254f902009-02-04 00:32:51 +00006178}
6179
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006180/// isBetterOverloadCandidate - Determines whether the first overload
6181/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006182bool
John McCall5c32be02010-08-24 20:38:10 +00006183isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006184 const OverloadCandidate &Cand1,
6185 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006186 SourceLocation Loc,
6187 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006188 // Define viable functions to be better candidates than non-viable
6189 // functions.
6190 if (!Cand2.Viable)
6191 return Cand1.Viable;
6192 else if (!Cand1.Viable)
6193 return false;
6194
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006195 // C++ [over.match.best]p1:
6196 //
6197 // -- if F is a static member function, ICS1(F) is defined such
6198 // that ICS1(F) is neither better nor worse than ICS1(G) for
6199 // any function G, and, symmetrically, ICS1(G) is neither
6200 // better nor worse than ICS1(F).
6201 unsigned StartArg = 0;
6202 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6203 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006204
Douglas Gregord3cb3562009-07-07 23:38:56 +00006205 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006206 // A viable function F1 is defined to be a better function than another
6207 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006208 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006209 unsigned NumArgs = Cand1.Conversions.size();
6210 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6211 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006212 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006213 switch (CompareImplicitConversionSequences(S,
6214 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006215 Cand2.Conversions[ArgIdx])) {
6216 case ImplicitConversionSequence::Better:
6217 // Cand1 has a better conversion sequence.
6218 HasBetterConversion = true;
6219 break;
6220
6221 case ImplicitConversionSequence::Worse:
6222 // Cand1 can't be better than Cand2.
6223 return false;
6224
6225 case ImplicitConversionSequence::Indistinguishable:
6226 // Do nothing.
6227 break;
6228 }
6229 }
6230
Mike Stump11289f42009-09-09 15:08:12 +00006231 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006232 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006233 if (HasBetterConversion)
6234 return true;
6235
Mike Stump11289f42009-09-09 15:08:12 +00006236 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006237 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006238 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006239 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6240 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006241
6242 // -- F1 and F2 are function template specializations, and the function
6243 // template for F1 is more specialized than the template for F2
6244 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006245 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006246 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006247 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006248 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006249 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6250 Cand2.Function->getPrimaryTemplate(),
6251 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006252 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006253 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006254 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006255 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006256 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006257
Douglas Gregora1f013e2008-11-07 22:36:19 +00006258 // -- the context is an initialization by user-defined conversion
6259 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6260 // from the return type of F1 to the destination type (i.e.,
6261 // the type of the entity being initialized) is a better
6262 // conversion sequence than the standard conversion sequence
6263 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006264 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006265 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006266 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006267 switch (CompareStandardConversionSequences(S,
6268 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006269 Cand2.FinalConversion)) {
6270 case ImplicitConversionSequence::Better:
6271 // Cand1 has a better conversion sequence.
6272 return true;
6273
6274 case ImplicitConversionSequence::Worse:
6275 // Cand1 can't be better than Cand2.
6276 return false;
6277
6278 case ImplicitConversionSequence::Indistinguishable:
6279 // Do nothing
6280 break;
6281 }
6282 }
6283
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006284 return false;
6285}
6286
Mike Stump11289f42009-09-09 15:08:12 +00006287/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006288/// within an overload candidate set.
6289///
6290/// \param CandidateSet the set of candidate functions.
6291///
6292/// \param Loc the location of the function name (or operator symbol) for
6293/// which overload resolution occurs.
6294///
Mike Stump11289f42009-09-09 15:08:12 +00006295/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006296/// function, Best points to the candidate function found.
6297///
6298/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006299OverloadingResult
6300OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006301 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006302 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006303 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006304 Best = end();
6305 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6306 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006307 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006308 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006309 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006310 }
6311
6312 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006313 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006314 return OR_No_Viable_Function;
6315
6316 // Make sure that this function is better than every other viable
6317 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006318 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006319 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006320 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006321 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006322 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006323 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006324 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006325 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006326 }
Mike Stump11289f42009-09-09 15:08:12 +00006327
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006328 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006329 if (Best->Function &&
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006330 (Best->Function->isDeleted() || Best->Function->isUnavailable()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006331 return OR_Deleted;
6332
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006333 return OR_Success;
6334}
6335
John McCall53262c92010-01-12 02:15:36 +00006336namespace {
6337
6338enum OverloadCandidateKind {
6339 oc_function,
6340 oc_method,
6341 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006342 oc_function_template,
6343 oc_method_template,
6344 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006345 oc_implicit_default_constructor,
6346 oc_implicit_copy_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006347 oc_implicit_copy_assignment,
6348 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006349};
6350
John McCalle1ac8d12010-01-13 00:25:19 +00006351OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6352 FunctionDecl *Fn,
6353 std::string &Description) {
6354 bool isTemplate = false;
6355
6356 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6357 isTemplate = true;
6358 Description = S.getTemplateArgumentBindingsText(
6359 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6360 }
John McCallfd0b2f82010-01-06 09:43:14 +00006361
6362 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006363 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006364 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006365
Sebastian Redl08905022011-02-05 19:23:19 +00006366 if (Ctor->getInheritedConstructor())
6367 return oc_implicit_inherited_constructor;
6368
John McCall53262c92010-01-12 02:15:36 +00006369 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6370 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006371 }
6372
6373 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6374 // This actually gets spelled 'candidate function' for now, but
6375 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006376 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006377 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006378
Douglas Gregorec3bec02010-09-27 22:37:28 +00006379 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006380 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006381 return oc_implicit_copy_assignment;
6382 }
6383
John McCalle1ac8d12010-01-13 00:25:19 +00006384 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006385}
6386
Sebastian Redl08905022011-02-05 19:23:19 +00006387void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6388 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6389 if (!Ctor) return;
6390
6391 Ctor = Ctor->getInheritedConstructor();
6392 if (!Ctor) return;
6393
6394 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6395}
6396
John McCall53262c92010-01-12 02:15:36 +00006397} // end anonymous namespace
6398
6399// Notes the location of an overload candidate.
6400void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006401 std::string FnDesc;
6402 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6403 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6404 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006405 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006406}
6407
Douglas Gregorb491ed32011-02-19 21:32:49 +00006408//Notes the location of all overload candidates designated through
6409// OverloadedExpr
6410void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6411 assert(OverloadedExpr->getType() == Context.OverloadTy);
6412
6413 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6414 OverloadExpr *OvlExpr = Ovl.Expression;
6415
6416 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6417 IEnd = OvlExpr->decls_end();
6418 I != IEnd; ++I) {
6419 if (FunctionTemplateDecl *FunTmpl =
6420 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6421 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6422 } else if (FunctionDecl *Fun
6423 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6424 NoteOverloadCandidate(Fun);
6425 }
6426 }
6427}
6428
John McCall0d1da222010-01-12 00:44:57 +00006429/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6430/// "lead" diagnostic; it will be given two arguments, the source and
6431/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006432void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6433 Sema &S,
6434 SourceLocation CaretLoc,
6435 const PartialDiagnostic &PDiag) const {
6436 S.Diag(CaretLoc, PDiag)
6437 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006438 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006439 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6440 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006441 }
John McCall12f97bc2010-01-08 04:41:39 +00006442}
6443
John McCall0d1da222010-01-12 00:44:57 +00006444namespace {
6445
John McCall6a61b522010-01-13 09:16:55 +00006446void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6447 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6448 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006449 assert(Cand->Function && "for now, candidate must be a function");
6450 FunctionDecl *Fn = Cand->Function;
6451
6452 // There's a conversion slot for the object argument if this is a
6453 // non-constructor method. Note that 'I' corresponds the
6454 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006455 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006456 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006457 if (I == 0)
6458 isObjectArgument = true;
6459 else
6460 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006461 }
6462
John McCalle1ac8d12010-01-13 00:25:19 +00006463 std::string FnDesc;
6464 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6465
John McCall6a61b522010-01-13 09:16:55 +00006466 Expr *FromExpr = Conv.Bad.FromExpr;
6467 QualType FromTy = Conv.Bad.getFromType();
6468 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006469
John McCallfb7ad0f2010-02-02 02:42:52 +00006470 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006471 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006472 Expr *E = FromExpr->IgnoreParens();
6473 if (isa<UnaryOperator>(E))
6474 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006475 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006476
6477 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6478 << (unsigned) FnKind << FnDesc
6479 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6480 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006481 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006482 return;
6483 }
6484
John McCall6d174642010-01-23 08:10:49 +00006485 // Do some hand-waving analysis to see if the non-viability is due
6486 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006487 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6488 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6489 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6490 CToTy = RT->getPointeeType();
6491 else {
6492 // TODO: detect and diagnose the full richness of const mismatches.
6493 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6494 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6495 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6496 }
6497
6498 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6499 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6500 // It is dumb that we have to do this here.
6501 while (isa<ArrayType>(CFromTy))
6502 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6503 while (isa<ArrayType>(CToTy))
6504 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6505
6506 Qualifiers FromQs = CFromTy.getQualifiers();
6507 Qualifiers ToQs = CToTy.getQualifiers();
6508
6509 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6510 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6511 << (unsigned) FnKind << FnDesc
6512 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6513 << FromTy
6514 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6515 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006516 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006517 return;
6518 }
6519
6520 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6521 assert(CVR && "unexpected qualifiers mismatch");
6522
6523 if (isObjectArgument) {
6524 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6525 << (unsigned) FnKind << FnDesc
6526 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6527 << FromTy << (CVR - 1);
6528 } else {
6529 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6530 << (unsigned) FnKind << FnDesc
6531 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6532 << FromTy << (CVR - 1) << I+1;
6533 }
Sebastian Redl08905022011-02-05 19:23:19 +00006534 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006535 return;
6536 }
6537
John McCall6d174642010-01-23 08:10:49 +00006538 // Diagnose references or pointers to incomplete types differently,
6539 // since it's far from impossible that the incompleteness triggered
6540 // the failure.
6541 QualType TempFromTy = FromTy.getNonReferenceType();
6542 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6543 TempFromTy = PTy->getPointeeType();
6544 if (TempFromTy->isIncompleteType()) {
6545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6546 << (unsigned) FnKind << FnDesc
6547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6548 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006549 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006550 return;
6551 }
6552
Douglas Gregor56f2e342010-06-30 23:01:39 +00006553 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006554 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006555 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6556 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6557 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6558 FromPtrTy->getPointeeType()) &&
6559 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6560 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006562 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006563 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006564 }
6565 } else if (const ObjCObjectPointerType *FromPtrTy
6566 = FromTy->getAs<ObjCObjectPointerType>()) {
6567 if (const ObjCObjectPointerType *ToPtrTy
6568 = ToTy->getAs<ObjCObjectPointerType>())
6569 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6570 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6571 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6572 FromPtrTy->getPointeeType()) &&
6573 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006574 BaseToDerivedConversion = 2;
6575 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6576 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6577 !FromTy->isIncompleteType() &&
6578 !ToRefTy->getPointeeType()->isIncompleteType() &&
6579 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6580 BaseToDerivedConversion = 3;
6581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006582
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006583 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006585 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006586 << (unsigned) FnKind << FnDesc
6587 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006588 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006589 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006590 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006591 return;
6592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006593
John McCall47000992010-01-14 03:28:57 +00006594 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006595 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6596 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006597 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006598 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006599 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006600}
6601
6602void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6603 unsigned NumFormalArgs) {
6604 // TODO: treat calls to a missing default constructor as a special case
6605
6606 FunctionDecl *Fn = Cand->Function;
6607 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6608
6609 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006610
John McCall6a61b522010-01-13 09:16:55 +00006611 // at least / at most / exactly
6612 unsigned mode, modeCount;
6613 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006614 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6615 (Cand->FailureKind == ovl_fail_bad_deduction &&
6616 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006617 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006618 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006619 mode = 0; // "at least"
6620 else
6621 mode = 2; // "exactly"
6622 modeCount = MinParams;
6623 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006624 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6625 (Cand->FailureKind == ovl_fail_bad_deduction &&
6626 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006627 if (MinParams != FnTy->getNumArgs())
6628 mode = 1; // "at most"
6629 else
6630 mode = 2; // "exactly"
6631 modeCount = FnTy->getNumArgs();
6632 }
6633
6634 std::string Description;
6635 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6636
6637 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006638 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006639 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006640 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006641}
6642
John McCall8b9ed552010-02-01 18:53:26 +00006643/// Diagnose a failed template-argument deduction.
6644void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6645 Expr **Args, unsigned NumArgs) {
6646 FunctionDecl *Fn = Cand->Function; // pattern
6647
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006648 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006649 NamedDecl *ParamD;
6650 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6651 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6652 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006653 switch (Cand->DeductionFailure.Result) {
6654 case Sema::TDK_Success:
6655 llvm_unreachable("TDK_success while diagnosing bad deduction");
6656
6657 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006658 assert(ParamD && "no parameter found for incomplete deduction result");
6659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6660 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006661 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006662 return;
6663 }
6664
John McCall42d7d192010-08-05 09:05:08 +00006665 case Sema::TDK_Underqualified: {
6666 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6667 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6668
6669 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6670
6671 // Param will have been canonicalized, but it should just be a
6672 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006673 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006674 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006675 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006676 assert(S.Context.hasSameType(Param, NonCanonParam));
6677
6678 // Arg has also been canonicalized, but there's nothing we can do
6679 // about that. It also doesn't matter as much, because it won't
6680 // have any template parameters in it (because deduction isn't
6681 // done on dependent types).
6682 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6683
6684 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6685 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00006686 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00006687 return;
6688 }
6689
6690 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006691 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006692 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006693 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006694 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006695 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006696 which = 1;
6697 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006698 which = 2;
6699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006700
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006703 << *Cand->DeductionFailure.getFirstArg()
6704 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00006705 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006706 return;
6707 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006708
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006709 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006710 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006711 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006713 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6714 << ParamD->getDeclName();
6715 else {
6716 int index = 0;
6717 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6718 index = TTP->getIndex();
6719 else if (NonTypeTemplateParmDecl *NTTP
6720 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6721 index = NTTP->getIndex();
6722 else
6723 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006724 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006725 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6726 << (index + 1);
6727 }
Sebastian Redl08905022011-02-05 19:23:19 +00006728 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006729 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006730
Douglas Gregor02eb4832010-05-08 18:13:28 +00006731 case Sema::TDK_TooManyArguments:
6732 case Sema::TDK_TooFewArguments:
6733 DiagnoseArityMismatch(S, Cand, NumArgs);
6734 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006735
6736 case Sema::TDK_InstantiationDepth:
6737 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00006738 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006739 return;
6740
6741 case Sema::TDK_SubstitutionFailure: {
6742 std::string ArgString;
6743 if (TemplateArgumentList *Args
6744 = Cand->DeductionFailure.getTemplateArgumentList())
6745 ArgString = S.getTemplateArgumentBindingsText(
6746 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6747 *Args);
6748 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6749 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00006750 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006751 return;
6752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006753
John McCall8b9ed552010-02-01 18:53:26 +00006754 // TODO: diagnose these individually, then kill off
6755 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006756 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006757 case Sema::TDK_FailedOverloadResolution:
6758 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00006759 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006760 return;
6761 }
6762}
6763
6764/// Generates a 'note' diagnostic for an overload candidate. We've
6765/// already generated a primary error at the call site.
6766///
6767/// It really does need to be a single diagnostic with its caret
6768/// pointed at the candidate declaration. Yes, this creates some
6769/// major challenges of technical writing. Yes, this makes pointing
6770/// out problems with specific arguments quite awkward. It's still
6771/// better than generating twenty screens of text for every failed
6772/// overload.
6773///
6774/// It would be great to be able to express per-candidate problems
6775/// more richly for those diagnostic clients that cared, but we'd
6776/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006777void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6778 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006779 FunctionDecl *Fn = Cand->Function;
6780
John McCall12f97bc2010-01-08 04:41:39 +00006781 // Note deleted candidates, but only if they're viable.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006782 if (Cand->Viable && (Fn->isDeleted() || Fn->isUnavailable())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006783 std::string FnDesc;
6784 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006785
6786 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006787 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00006788 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00006789 return;
John McCall12f97bc2010-01-08 04:41:39 +00006790 }
6791
John McCalle1ac8d12010-01-13 00:25:19 +00006792 // We don't really have anything else to say about viable candidates.
6793 if (Cand->Viable) {
6794 S.NoteOverloadCandidate(Fn);
6795 return;
6796 }
John McCall0d1da222010-01-12 00:44:57 +00006797
John McCall6a61b522010-01-13 09:16:55 +00006798 switch (Cand->FailureKind) {
6799 case ovl_fail_too_many_arguments:
6800 case ovl_fail_too_few_arguments:
6801 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006802
John McCall6a61b522010-01-13 09:16:55 +00006803 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006804 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6805
John McCallfe796dd2010-01-23 05:17:32 +00006806 case ovl_fail_trivial_conversion:
6807 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006808 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006809 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006810
John McCall65eb8792010-02-25 01:37:24 +00006811 case ovl_fail_bad_conversion: {
6812 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6813 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006814 if (Cand->Conversions[I].isBad())
6815 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006816
John McCall6a61b522010-01-13 09:16:55 +00006817 // FIXME: this currently happens when we're called from SemaInit
6818 // when user-conversion overload fails. Figure out how to handle
6819 // those conditions and diagnose them well.
6820 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006821 }
John McCall65eb8792010-02-25 01:37:24 +00006822 }
John McCalld3224162010-01-08 00:58:21 +00006823}
6824
6825void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6826 // Desugar the type of the surrogate down to a function type,
6827 // retaining as many typedefs as possible while still showing
6828 // the function type (and, therefore, its parameter types).
6829 QualType FnType = Cand->Surrogate->getConversionType();
6830 bool isLValueReference = false;
6831 bool isRValueReference = false;
6832 bool isPointer = false;
6833 if (const LValueReferenceType *FnTypeRef =
6834 FnType->getAs<LValueReferenceType>()) {
6835 FnType = FnTypeRef->getPointeeType();
6836 isLValueReference = true;
6837 } else if (const RValueReferenceType *FnTypeRef =
6838 FnType->getAs<RValueReferenceType>()) {
6839 FnType = FnTypeRef->getPointeeType();
6840 isRValueReference = true;
6841 }
6842 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6843 FnType = FnTypePtr->getPointeeType();
6844 isPointer = true;
6845 }
6846 // Desugar down to a function type.
6847 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6848 // Reconstruct the pointer/reference as appropriate.
6849 if (isPointer) FnType = S.Context.getPointerType(FnType);
6850 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6851 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6852
6853 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6854 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00006855 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00006856}
6857
6858void NoteBuiltinOperatorCandidate(Sema &S,
6859 const char *Opc,
6860 SourceLocation OpLoc,
6861 OverloadCandidate *Cand) {
6862 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6863 std::string TypeStr("operator");
6864 TypeStr += Opc;
6865 TypeStr += "(";
6866 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6867 if (Cand->Conversions.size() == 1) {
6868 TypeStr += ")";
6869 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6870 } else {
6871 TypeStr += ", ";
6872 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6873 TypeStr += ")";
6874 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6875 }
6876}
6877
6878void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6879 OverloadCandidate *Cand) {
6880 unsigned NoOperands = Cand->Conversions.size();
6881 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6882 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006883 if (ICS.isBad()) break; // all meaningless after first invalid
6884 if (!ICS.isAmbiguous()) continue;
6885
John McCall5c32be02010-08-24 20:38:10 +00006886 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006887 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006888 }
6889}
6890
John McCall3712d9e2010-01-15 23:32:50 +00006891SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6892 if (Cand->Function)
6893 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006894 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006895 return Cand->Surrogate->getLocation();
6896 return SourceLocation();
6897}
6898
John McCallad2587a2010-01-12 00:48:53 +00006899struct CompareOverloadCandidatesForDisplay {
6900 Sema &S;
6901 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006902
6903 bool operator()(const OverloadCandidate *L,
6904 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006905 // Fast-path this check.
6906 if (L == R) return false;
6907
John McCall12f97bc2010-01-08 04:41:39 +00006908 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006909 if (L->Viable) {
6910 if (!R->Viable) return true;
6911
6912 // TODO: introduce a tri-valued comparison for overload
6913 // candidates. Would be more worthwhile if we had a sort
6914 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006915 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6916 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006917 } else if (R->Viable)
6918 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006919
John McCall3712d9e2010-01-15 23:32:50 +00006920 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006921
John McCall3712d9e2010-01-15 23:32:50 +00006922 // Criteria by which we can sort non-viable candidates:
6923 if (!L->Viable) {
6924 // 1. Arity mismatches come after other candidates.
6925 if (L->FailureKind == ovl_fail_too_many_arguments ||
6926 L->FailureKind == ovl_fail_too_few_arguments)
6927 return false;
6928 if (R->FailureKind == ovl_fail_too_many_arguments ||
6929 R->FailureKind == ovl_fail_too_few_arguments)
6930 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006931
John McCallfe796dd2010-01-23 05:17:32 +00006932 // 2. Bad conversions come first and are ordered by the number
6933 // of bad conversions and quality of good conversions.
6934 if (L->FailureKind == ovl_fail_bad_conversion) {
6935 if (R->FailureKind != ovl_fail_bad_conversion)
6936 return true;
6937
6938 // If there's any ordering between the defined conversions...
6939 // FIXME: this might not be transitive.
6940 assert(L->Conversions.size() == R->Conversions.size());
6941
6942 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006943 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6944 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006945 switch (CompareImplicitConversionSequences(S,
6946 L->Conversions[I],
6947 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006948 case ImplicitConversionSequence::Better:
6949 leftBetter++;
6950 break;
6951
6952 case ImplicitConversionSequence::Worse:
6953 leftBetter--;
6954 break;
6955
6956 case ImplicitConversionSequence::Indistinguishable:
6957 break;
6958 }
6959 }
6960 if (leftBetter > 0) return true;
6961 if (leftBetter < 0) return false;
6962
6963 } else if (R->FailureKind == ovl_fail_bad_conversion)
6964 return false;
6965
John McCall3712d9e2010-01-15 23:32:50 +00006966 // TODO: others?
6967 }
6968
6969 // Sort everything else by location.
6970 SourceLocation LLoc = GetLocationForCandidate(L);
6971 SourceLocation RLoc = GetLocationForCandidate(R);
6972
6973 // Put candidates without locations (e.g. builtins) at the end.
6974 if (LLoc.isInvalid()) return false;
6975 if (RLoc.isInvalid()) return true;
6976
6977 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006978 }
6979};
6980
John McCallfe796dd2010-01-23 05:17:32 +00006981/// CompleteNonViableCandidate - Normally, overload resolution only
6982/// computes up to the first
6983void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6984 Expr **Args, unsigned NumArgs) {
6985 assert(!Cand->Viable);
6986
6987 // Don't do anything on failures other than bad conversion.
6988 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6989
6990 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006991 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006992 unsigned ConvCount = Cand->Conversions.size();
6993 while (true) {
6994 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6995 ConvIdx++;
6996 if (Cand->Conversions[ConvIdx - 1].isBad())
6997 break;
6998 }
6999
7000 if (ConvIdx == ConvCount)
7001 return;
7002
John McCall65eb8792010-02-25 01:37:24 +00007003 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7004 "remaining conversion is initialized?");
7005
Douglas Gregoradc7a702010-04-16 17:45:54 +00007006 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007007 // operation somehow.
7008 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007009
7010 const FunctionProtoType* Proto;
7011 unsigned ArgIdx = ConvIdx;
7012
7013 if (Cand->IsSurrogate) {
7014 QualType ConvType
7015 = Cand->Surrogate->getConversionType().getNonReferenceType();
7016 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7017 ConvType = ConvPtrType->getPointeeType();
7018 Proto = ConvType->getAs<FunctionProtoType>();
7019 ArgIdx--;
7020 } else if (Cand->Function) {
7021 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7022 if (isa<CXXMethodDecl>(Cand->Function) &&
7023 !isa<CXXConstructorDecl>(Cand->Function))
7024 ArgIdx--;
7025 } else {
7026 // Builtin binary operator with a bad first conversion.
7027 assert(ConvCount <= 3);
7028 for (; ConvIdx != ConvCount; ++ConvIdx)
7029 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007030 = TryCopyInitialization(S, Args[ConvIdx],
7031 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007032 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007033 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00007034 return;
7035 }
7036
7037 // Fill in the rest of the conversions.
7038 unsigned NumArgsInProto = Proto->getNumArgs();
7039 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7040 if (ArgIdx < NumArgsInProto)
7041 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007042 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007043 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007044 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00007045 else
7046 Cand->Conversions[ConvIdx].setEllipsis();
7047 }
7048}
7049
John McCalld3224162010-01-08 00:58:21 +00007050} // end anonymous namespace
7051
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007052/// PrintOverloadCandidates - When overload resolution fails, prints
7053/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007054/// set.
John McCall5c32be02010-08-24 20:38:10 +00007055void OverloadCandidateSet::NoteCandidates(Sema &S,
7056 OverloadCandidateDisplayKind OCD,
7057 Expr **Args, unsigned NumArgs,
7058 const char *Opc,
7059 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007060 // Sort the candidates by viability and position. Sorting directly would
7061 // be prohibitive, so we make a set of pointers and sort those.
7062 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007063 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7064 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007065 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007066 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007067 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007068 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007069 if (Cand->Function || Cand->IsSurrogate)
7070 Cands.push_back(Cand);
7071 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7072 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007073 }
7074 }
7075
John McCallad2587a2010-01-12 00:48:53 +00007076 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007077 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007078
John McCall0d1da222010-01-12 00:44:57 +00007079 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007080
John McCall12f97bc2010-01-08 04:41:39 +00007081 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007082 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007083 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007084 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7085 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007086
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007087 // Set an arbitrary limit on the number of candidate functions we'll spam
7088 // the user with. FIXME: This limit should depend on details of the
7089 // candidate list.
7090 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7091 break;
7092 }
7093 ++CandsShown;
7094
John McCalld3224162010-01-08 00:58:21 +00007095 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007096 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007097 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007098 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007099 else {
7100 assert(Cand->Viable &&
7101 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007102 // Generally we only see ambiguities including viable builtin
7103 // operators if overload resolution got screwed up by an
7104 // ambiguous user-defined conversion.
7105 //
7106 // FIXME: It's quite possible for different conversions to see
7107 // different ambiguities, though.
7108 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007109 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007110 ReportedAmbiguousConversions = true;
7111 }
John McCalld3224162010-01-08 00:58:21 +00007112
John McCall0d1da222010-01-12 00:44:57 +00007113 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007114 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007115 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007116 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007117
7118 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007119 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007120}
7121
Douglas Gregorb491ed32011-02-19 21:32:49 +00007122// [PossiblyAFunctionType] --> [Return]
7123// NonFunctionType --> NonFunctionType
7124// R (A) --> R(A)
7125// R (*)(A) --> R (A)
7126// R (&)(A) --> R (A)
7127// R (S::*)(A) --> R (A)
7128QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7129 QualType Ret = PossiblyAFunctionType;
7130 if (const PointerType *ToTypePtr =
7131 PossiblyAFunctionType->getAs<PointerType>())
7132 Ret = ToTypePtr->getPointeeType();
7133 else if (const ReferenceType *ToTypeRef =
7134 PossiblyAFunctionType->getAs<ReferenceType>())
7135 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007136 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007137 PossiblyAFunctionType->getAs<MemberPointerType>())
7138 Ret = MemTypePtr->getPointeeType();
7139 Ret =
7140 Context.getCanonicalType(Ret).getUnqualifiedType();
7141 return Ret;
7142}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007143
Douglas Gregorb491ed32011-02-19 21:32:49 +00007144// A helper class to help with address of function resolution
7145// - allows us to avoid passing around all those ugly parameters
7146class AddressOfFunctionResolver
7147{
7148 Sema& S;
7149 Expr* SourceExpr;
7150 const QualType& TargetType;
7151 QualType TargetFunctionType; // Extracted function type from target type
7152
7153 bool Complain;
7154 //DeclAccessPair& ResultFunctionAccessPair;
7155 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007156
Douglas Gregorb491ed32011-02-19 21:32:49 +00007157 bool TargetTypeIsNonStaticMemberFunction;
7158 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007159
Douglas Gregorb491ed32011-02-19 21:32:49 +00007160 OverloadExpr::FindResult OvlExprInfo;
7161 OverloadExpr *OvlExpr;
7162 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007163 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007164
Douglas Gregorb491ed32011-02-19 21:32:49 +00007165public:
7166 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7167 const QualType& TargetType, bool Complain)
7168 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7169 Complain(Complain), Context(S.getASTContext()),
7170 TargetTypeIsNonStaticMemberFunction(
7171 !!TargetType->getAs<MemberPointerType>()),
7172 FoundNonTemplateFunction(false),
7173 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7174 OvlExpr(OvlExprInfo.Expression)
7175 {
7176 ExtractUnqualifiedFunctionTypeFromTargetType();
7177
7178 if (!TargetFunctionType->isFunctionType()) {
7179 if (OvlExpr->hasExplicitTemplateArgs()) {
7180 DeclAccessPair dap;
7181 if( FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7182 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007183
7184 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7185 if (!Method->isStatic()) {
7186 // If the target type is a non-function type and the function
7187 // found is a non-static member function, pretend as if that was
7188 // the target, it's the only possible type to end up with.
7189 TargetTypeIsNonStaticMemberFunction = true;
7190
7191 // And skip adding the function if its not in the proper form.
7192 // We'll diagnose this due to an empty set of functions.
7193 if (!OvlExprInfo.HasFormOfMemberPointer)
7194 return;
7195 }
7196 }
7197
Douglas Gregorb491ed32011-02-19 21:32:49 +00007198 Matches.push_back(std::make_pair(dap,Fn));
7199 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007200 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007201 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007202 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007203
7204 if (OvlExpr->hasExplicitTemplateArgs())
7205 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007206
Douglas Gregorb491ed32011-02-19 21:32:49 +00007207 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7208 // C++ [over.over]p4:
7209 // If more than one function is selected, [...]
7210 if (Matches.size() > 1) {
7211 if (FoundNonTemplateFunction)
7212 EliminateAllTemplateMatches();
7213 else
7214 EliminateAllExceptMostSpecializedTemplate();
7215 }
7216 }
7217 }
7218
7219private:
7220 bool isTargetTypeAFunction() const {
7221 return TargetFunctionType->isFunctionType();
7222 }
7223
7224 // [ToType] [Return]
7225
7226 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7227 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7228 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7229 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7230 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7231 }
7232
7233 // return true if any matching specializations were found
7234 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7235 const DeclAccessPair& CurAccessFunPair) {
7236 if (CXXMethodDecl *Method
7237 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7238 // Skip non-static function templates when converting to pointer, and
7239 // static when converting to member pointer.
7240 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7241 return false;
7242 }
7243 else if (TargetTypeIsNonStaticMemberFunction)
7244 return false;
7245
7246 // C++ [over.over]p2:
7247 // If the name is a function template, template argument deduction is
7248 // done (14.8.2.2), and if the argument deduction succeeds, the
7249 // resulting template argument list is used to generate a single
7250 // function template specialization, which is added to the set of
7251 // overloaded functions considered.
7252 FunctionDecl *Specialization = 0;
7253 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7254 if (Sema::TemplateDeductionResult Result
7255 = S.DeduceTemplateArguments(FunctionTemplate,
7256 &OvlExplicitTemplateArgs,
7257 TargetFunctionType, Specialization,
7258 Info)) {
7259 // FIXME: make a note of the failed deduction for diagnostics.
7260 (void)Result;
7261 return false;
7262 }
7263
7264 // Template argument deduction ensures that we have an exact match.
7265 // This function template specicalization works.
7266 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7267 assert(TargetFunctionType
7268 == Context.getCanonicalType(Specialization->getType()));
7269 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7270 return true;
7271 }
7272
7273 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7274 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007275 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007276 // Skip non-static functions when converting to pointer, and static
7277 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007278 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7279 return false;
7280 }
7281 else if (TargetTypeIsNonStaticMemberFunction)
7282 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007283
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007284 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007285 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007286 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7287 FunDecl->getType()) ||
7288 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007289 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007290 Matches.push_back(std::make_pair(CurAccessFunPair,
7291 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007292 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007293 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007294 }
Mike Stump11289f42009-09-09 15:08:12 +00007295 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007296
7297 return false;
7298 }
7299
7300 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7301 bool Ret = false;
7302
7303 // If the overload expression doesn't have the form of a pointer to
7304 // member, don't try to convert it to a pointer-to-member type.
7305 if (IsInvalidFormOfPointerToMemberFunction())
7306 return false;
7307
7308 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7309 E = OvlExpr->decls_end();
7310 I != E; ++I) {
7311 // Look through any using declarations to find the underlying function.
7312 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7313
7314 // C++ [over.over]p3:
7315 // Non-member functions and static member functions match
7316 // targets of type "pointer-to-function" or "reference-to-function."
7317 // Nonstatic member functions match targets of
7318 // type "pointer-to-member-function."
7319 // Note that according to DR 247, the containing class does not matter.
7320 if (FunctionTemplateDecl *FunctionTemplate
7321 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7322 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7323 Ret = true;
7324 }
7325 // If we have explicit template arguments supplied, skip non-templates.
7326 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7327 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7328 Ret = true;
7329 }
7330 assert(Ret || Matches.empty());
7331 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007332 }
7333
Douglas Gregorb491ed32011-02-19 21:32:49 +00007334 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007335 // [...] and any given function template specialization F1 is
7336 // eliminated if the set contains a second function template
7337 // specialization whose function template is more specialized
7338 // than the function template of F1 according to the partial
7339 // ordering rules of 14.5.5.2.
7340
7341 // The algorithm specified above is quadratic. We instead use a
7342 // two-pass algorithm (similar to the one used to identify the
7343 // best viable function in an overload set) that identifies the
7344 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007345
7346 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7347 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7348 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007349
John McCall58cc69d2010-01-27 01:50:18 +00007350 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007351 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7352 TPOC_Other, 0, SourceExpr->getLocStart(),
7353 S.PDiag(),
7354 S.PDiag(diag::err_addr_ovl_ambiguous)
7355 << Matches[0].second->getDeclName(),
7356 S.PDiag(diag::note_ovl_candidate)
7357 << (unsigned) oc_function_template,
7358 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007359
Douglas Gregorb491ed32011-02-19 21:32:49 +00007360 if (Result != MatchesCopy.end()) {
7361 // Make it the first and only element
7362 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7363 Matches[0].second = cast<FunctionDecl>(*Result);
7364 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007365 }
7366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007367
Douglas Gregorb491ed32011-02-19 21:32:49 +00007368 void EliminateAllTemplateMatches() {
7369 // [...] any function template specializations in the set are
7370 // eliminated if the set also contains a non-template function, [...]
7371 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7372 if (Matches[I].second->getPrimaryTemplate() == 0)
7373 ++I;
7374 else {
7375 Matches[I] = Matches[--N];
7376 Matches.set_size(N);
7377 }
7378 }
7379 }
7380
7381public:
7382 void ComplainNoMatchesFound() const {
7383 assert(Matches.empty());
7384 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7385 << OvlExpr->getName() << TargetFunctionType
7386 << OvlExpr->getSourceRange();
7387 S.NoteAllOverloadCandidates(OvlExpr);
7388 }
7389
7390 bool IsInvalidFormOfPointerToMemberFunction() const {
7391 return TargetTypeIsNonStaticMemberFunction &&
7392 !OvlExprInfo.HasFormOfMemberPointer;
7393 }
7394
7395 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7396 // TODO: Should we condition this on whether any functions might
7397 // have matched, or is it more appropriate to do that in callers?
7398 // TODO: a fixit wouldn't hurt.
7399 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7400 << TargetType << OvlExpr->getSourceRange();
7401 }
7402
7403 void ComplainOfInvalidConversion() const {
7404 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7405 << OvlExpr->getName() << TargetType;
7406 }
7407
7408 void ComplainMultipleMatchesFound() const {
7409 assert(Matches.size() > 1);
7410 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7411 << OvlExpr->getName()
7412 << OvlExpr->getSourceRange();
7413 S.NoteAllOverloadCandidates(OvlExpr);
7414 }
7415
7416 int getNumMatches() const { return Matches.size(); }
7417
7418 FunctionDecl* getMatchingFunctionDecl() const {
7419 if (Matches.size() != 1) return 0;
7420 return Matches[0].second;
7421 }
7422
7423 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7424 if (Matches.size() != 1) return 0;
7425 return &Matches[0].first;
7426 }
7427};
7428
7429/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7430/// an overloaded function (C++ [over.over]), where @p From is an
7431/// expression with overloaded function type and @p ToType is the type
7432/// we're trying to resolve to. For example:
7433///
7434/// @code
7435/// int f(double);
7436/// int f(int);
7437///
7438/// int (*pfd)(double) = f; // selects f(double)
7439/// @endcode
7440///
7441/// This routine returns the resulting FunctionDecl if it could be
7442/// resolved, and NULL otherwise. When @p Complain is true, this
7443/// routine will emit diagnostics if there is an error.
7444FunctionDecl *
7445Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7446 bool Complain,
7447 DeclAccessPair &FoundResult) {
7448
7449 assert(AddressOfExpr->getType() == Context.OverloadTy);
7450
7451 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7452 int NumMatches = Resolver.getNumMatches();
7453 FunctionDecl* Fn = 0;
7454 if ( NumMatches == 0 && Complain) {
7455 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7456 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7457 else
7458 Resolver.ComplainNoMatchesFound();
7459 }
7460 else if (NumMatches > 1 && Complain)
7461 Resolver.ComplainMultipleMatchesFound();
7462 else if (NumMatches == 1) {
7463 Fn = Resolver.getMatchingFunctionDecl();
7464 assert(Fn);
7465 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7466 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007467 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007468 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007469 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007470
7471 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007472}
7473
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007475/// resolve that overloaded function expression down to a single function.
7476///
7477/// This routine can only resolve template-ids that refer to a single function
7478/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007479/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007480/// as described in C++0x [temp.arg.explicit]p3.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007481FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From,
7482 bool Complain,
7483 DeclAccessPair* FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007484 // C++ [over.over]p1:
7485 // [...] [Note: any redundant set of parentheses surrounding the
7486 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007487 // C++ [over.over]p1:
7488 // [...] The overloaded function name can be preceded by the &
7489 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007490 if (From->getType() != Context.OverloadTy)
7491 return 0;
7492
John McCall8d08b9b2010-08-27 09:08:28 +00007493 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007494
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007495 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007496 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007497 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007498
7499 TemplateArgumentListInfo ExplicitTemplateArgs;
7500 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007501
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007502 // Look through all of the overloaded functions, searching for one
7503 // whose type matches exactly.
7504 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007505 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7506 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007507 // C++0x [temp.arg.explicit]p3:
7508 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509 // where deduction is not done, if a template argument list is
7510 // specified and it, along with any default template arguments,
7511 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007512 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007513 FunctionTemplateDecl *FunctionTemplate
7514 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007516 // C++ [over.over]p2:
7517 // If the name is a function template, template argument deduction is
7518 // done (14.8.2.2), and if the argument deduction succeeds, the
7519 // resulting template argument list is used to generate a single
7520 // function template specialization, which is added to the set of
7521 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007522 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007523 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007524 if (TemplateDeductionResult Result
7525 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7526 Specialization, Info)) {
7527 // FIXME: make a note of the failed deduction for diagnostics.
7528 (void)Result;
7529 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007530 }
7531
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007532 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007533 if (Matched) {
7534 if (FoundResult)
7535 *FoundResult = DeclAccessPair();
7536
7537 if (Complain) {
7538 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7539 << OvlExpr->getName();
7540 NoteAllOverloadCandidates(OvlExpr);
7541 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007542 return 0;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007543 }
7544
7545 if ((Matched = Specialization) && FoundResult)
7546 *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007548
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007549 return Matched;
7550}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007551
Douglas Gregor1beec452011-03-12 01:48:56 +00007552
7553
7554
7555// Resolve and fix an overloaded expression that
7556// can be resolved because it identifies a single function
7557// template specialization
7558// Last three arguments should only be supplied if Complain = true
7559ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
7560 Expr *SrcExpr, bool DoFunctionPointerConverion, bool Complain,
7561 const SourceRange& OpRangeForComplaining,
7562 QualType DestTypeForComplaining,
7563 unsigned DiagIDForComplaining ) {
7564
7565 assert(SrcExpr->getType() == Context.OverloadTy);
7566
7567 DeclAccessPair Found;
7568 Expr* SingleFunctionExpression = 0;
7569 if (FunctionDecl* Fn = ResolveSingleFunctionTemplateSpecialization(
7570 SrcExpr, false, // false -> Complain
7571 &Found)) {
7572 if (!DiagnoseUseOfDecl(Fn, SrcExpr->getSourceRange().getBegin())) {
7573 // mark the expression as resolved to Fn
7574 SingleFunctionExpression = FixOverloadedFunctionReference(SrcExpr,
7575 Found, Fn);
7576 if (DoFunctionPointerConverion)
7577 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression);
7578 }
7579 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007580 if (!SingleFunctionExpression) {
7581 if (Complain) {
7582 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
7583 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7584 << oe->getName() << DestTypeForComplaining << OpRangeForComplaining
7585 << oe->getQualifierLoc().getSourceRange();
7586 NoteAllOverloadCandidates(SrcExpr);
7587 }
7588 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00007589 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007590
Douglas Gregor1beec452011-03-12 01:48:56 +00007591 return SingleFunctionExpression;
7592}
7593
Douglas Gregorcabea402009-09-22 15:41:20 +00007594/// \brief Add a single candidate to the overload set.
7595static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007596 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007597 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007598 Expr **Args, unsigned NumArgs,
7599 OverloadCandidateSet &CandidateSet,
7600 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007601 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007602 if (isa<UsingShadowDecl>(Callee))
7603 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7604
Douglas Gregorcabea402009-09-22 15:41:20 +00007605 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007606 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007607 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007608 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007609 return;
John McCalld14a8642009-11-21 08:51:07 +00007610 }
7611
7612 if (FunctionTemplateDecl *FuncTemplate
7613 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007614 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7615 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007616 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007617 return;
7618 }
7619
7620 assert(false && "unhandled case in overloaded call candidate");
7621
7622 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007623}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007624
Douglas Gregorcabea402009-09-22 15:41:20 +00007625/// \brief Add the overload candidates named by callee and/or found by argument
7626/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007627void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007628 Expr **Args, unsigned NumArgs,
7629 OverloadCandidateSet &CandidateSet,
7630 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007631
7632#ifndef NDEBUG
7633 // Verify that ArgumentDependentLookup is consistent with the rules
7634 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007635 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007636 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7637 // and let Y be the lookup set produced by argument dependent
7638 // lookup (defined as follows). If X contains
7639 //
7640 // -- a declaration of a class member, or
7641 //
7642 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007643 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007644 //
7645 // -- a declaration that is neither a function or a function
7646 // template
7647 //
7648 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007649
John McCall57500772009-12-16 12:17:52 +00007650 if (ULE->requiresADL()) {
7651 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7652 E = ULE->decls_end(); I != E; ++I) {
7653 assert(!(*I)->getDeclContext()->isRecord());
7654 assert(isa<UsingShadowDecl>(*I) ||
7655 !(*I)->getDeclContext()->isFunctionOrMethod());
7656 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007657 }
7658 }
7659#endif
7660
John McCall57500772009-12-16 12:17:52 +00007661 // It would be nice to avoid this copy.
7662 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00007663 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00007664 if (ULE->hasExplicitTemplateArgs()) {
7665 ULE->copyTemplateArgumentsInto(TABuffer);
7666 ExplicitTemplateArgs = &TABuffer;
7667 }
7668
7669 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7670 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007671 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007672 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007673 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007674
John McCall57500772009-12-16 12:17:52 +00007675 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007676 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7677 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007678 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007679 CandidateSet,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007680 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007681}
John McCalld681c392009-12-16 08:11:27 +00007682
7683/// Attempts to recover from a call where no functions were found.
7684///
7685/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007686static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007687BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007688 UnresolvedLookupExpr *ULE,
7689 SourceLocation LParenLoc,
7690 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007691 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007692
7693 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00007694 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00007695
John McCall57500772009-12-16 12:17:52 +00007696 TemplateArgumentListInfo TABuffer;
7697 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7698 if (ULE->hasExplicitTemplateArgs()) {
7699 ULE->copyTemplateArgumentsInto(TABuffer);
7700 ExplicitTemplateArgs = &TABuffer;
7701 }
7702
John McCalld681c392009-12-16 08:11:27 +00007703 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7704 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007705 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007706 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007707
John McCall57500772009-12-16 12:17:52 +00007708 assert(!R.empty() && "lookup results empty despite recovery");
7709
7710 // Build an implicit member call if appropriate. Just drop the
7711 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007712 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007713 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007714 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7715 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007716 else if (ExplicitTemplateArgs)
7717 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7718 else
7719 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7720
7721 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007722 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007723
7724 // This shouldn't cause an infinite loop because we're giving it
7725 // an expression with non-empty lookup results, which should never
7726 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007727 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007728 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007729}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007730
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007731/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007732/// (which eventually refers to the declaration Func) and the call
7733/// arguments Args/NumArgs, attempt to resolve the function call down
7734/// to a specific function. If overload resolution succeeds, returns
7735/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007736/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007737/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007738ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007739Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007740 SourceLocation LParenLoc,
7741 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00007742 SourceLocation RParenLoc,
7743 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00007744#ifndef NDEBUG
7745 if (ULE->requiresADL()) {
7746 // To do ADL, we must have found an unqualified name.
7747 assert(!ULE->getQualifier() && "qualified name with ADL");
7748
7749 // We don't perform ADL for implicit declarations of builtins.
7750 // Verify that this was correctly set up.
7751 FunctionDecl *F;
7752 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7753 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7754 F->getBuiltinID() && F->isImplicit())
7755 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007756
John McCall57500772009-12-16 12:17:52 +00007757 // We don't perform ADL in C.
7758 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7759 }
7760#endif
7761
John McCallbc077cf2010-02-08 23:07:23 +00007762 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007763
John McCall57500772009-12-16 12:17:52 +00007764 // Add the functions denoted by the callee to the set of candidate
7765 // functions, including those from argument-dependent lookup.
7766 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007767
7768 // If we found nothing, try to recover.
7769 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7770 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007771 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007772 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007773 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007774
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007775 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007776 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007777 case OR_Success: {
7778 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00007779 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00007780 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007781 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7782 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007783 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00007784 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7785 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00007786 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007787
7788 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007789 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007790 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007791 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007792 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007793 break;
7794
7795 case OR_Ambiguous:
7796 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007797 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007798 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007799 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007800
7801 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007802 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007803 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7804 << Best->Function->isDeleted()
7805 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007806 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007807 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7809 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00007810 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007811 }
7812
Douglas Gregorb412e172010-07-25 18:17:45 +00007813 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007814 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007815}
7816
John McCall4c4c1df2010-01-26 03:27:55 +00007817static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007818 return Functions.size() > 1 ||
7819 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7820}
7821
Douglas Gregor084d8552009-03-13 23:49:33 +00007822/// \brief Create a unary operation that may resolve to an overloaded
7823/// operator.
7824///
7825/// \param OpLoc The location of the operator itself (e.g., '*').
7826///
7827/// \param OpcIn The UnaryOperator::Opcode that describes this
7828/// operator.
7829///
7830/// \param Functions The set of non-member functions that will be
7831/// considered by overload resolution. The caller needs to build this
7832/// set based on the context using, e.g.,
7833/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7834/// set should not contain any member functions; those will be added
7835/// by CreateOverloadedUnaryOp().
7836///
7837/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007838ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007839Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7840 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007841 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007842 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007843
7844 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7845 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7846 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007847 // TODO: provide better source location info.
7848 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007849
John McCalle26a8722010-12-04 08:14:53 +00007850 if (Input->getObjectKind() == OK_ObjCProperty)
7851 ConvertPropertyForRValue(Input);
7852
Douglas Gregor084d8552009-03-13 23:49:33 +00007853 Expr *Args[2] = { Input, 0 };
7854 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007855
Douglas Gregor084d8552009-03-13 23:49:33 +00007856 // For post-increment and post-decrement, add the implicit '0' as
7857 // the second argument, so that we know this is a post-increment or
7858 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007859 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007860 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007861 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7862 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007863 NumArgs = 2;
7864 }
7865
7866 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007867 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007868 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007869 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00007870 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007871 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007872 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007873
John McCall58cc69d2010-01-27 01:50:18 +00007874 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007875 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007876 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00007877 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007878 /*ADL*/ true, IsOverloaded(Fns),
7879 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007880 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00007881 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00007882 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007883 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007884 OpLoc));
7885 }
7886
7887 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007888 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007889
7890 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007891 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007892
7893 // Add operator candidates that are member functions.
7894 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7895
John McCall4c4c1df2010-01-26 03:27:55 +00007896 // Add candidates from ADL.
7897 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007898 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007899 /*ExplicitTemplateArgs*/ 0,
7900 CandidateSet);
7901
Douglas Gregor084d8552009-03-13 23:49:33 +00007902 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007903 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007904
7905 // Perform overload resolution.
7906 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007907 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007908 case OR_Success: {
7909 // We found a built-in operator or an overloaded operator.
7910 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007911
Douglas Gregor084d8552009-03-13 23:49:33 +00007912 if (FnDecl) {
7913 // We matched an overloaded operator. Build a call to that
7914 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007915
Chandler Carruth30141632011-02-25 19:41:05 +00007916 MarkDeclarationReferenced(OpLoc, FnDecl);
7917
Douglas Gregor084d8552009-03-13 23:49:33 +00007918 // Convert the arguments.
7919 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007920 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007921
John McCall16df1e52010-03-30 21:47:33 +00007922 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7923 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007924 return ExprError();
7925 } else {
7926 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007927 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007928 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007929 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007930 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007931 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007932 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007933 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007934 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007935 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007936 }
7937
John McCall4fa0d5f2010-05-06 18:15:07 +00007938 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7939
John McCall7decc9e2010-11-18 06:31:45 +00007940 // Determine the result type.
7941 QualType ResultTy = FnDecl->getResultType();
7942 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7943 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007944
Douglas Gregor084d8552009-03-13 23:49:33 +00007945 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007946 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007947
Eli Friedman030eee42009-11-18 03:58:17 +00007948 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007949 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007950 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007951 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007952
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007953 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007954 FnDecl))
7955 return ExprError();
7956
John McCallb268a282010-08-23 23:25:46 +00007957 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007958 } else {
7959 // We matched a built-in operator. Convert the arguments, then
7960 // break out so that we will build the appropriate built-in
7961 // operator node.
7962 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007963 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007964 return ExprError();
7965
7966 break;
7967 }
7968 }
7969
7970 case OR_No_Viable_Function:
7971 // No viable function; fall through to handling this as a
7972 // built-in operator, which will produce an error message for us.
7973 break;
7974
7975 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007976 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007977 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007978 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007979 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007980 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7981 Args, NumArgs,
7982 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007983 return ExprError();
7984
7985 case OR_Deleted:
7986 Diag(OpLoc, diag::err_ovl_deleted_oper)
7987 << Best->Function->isDeleted()
7988 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007989 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregor084d8552009-03-13 23:49:33 +00007990 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007991 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007992 return ExprError();
7993 }
7994
7995 // Either we found no viable overloaded operator or we matched a
7996 // built-in operator. In either case, fall through to trying to
7997 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007998 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007999}
8000
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008001/// \brief Create a binary operation that may resolve to an overloaded
8002/// operator.
8003///
8004/// \param OpLoc The location of the operator itself (e.g., '+').
8005///
8006/// \param OpcIn The BinaryOperator::Opcode that describes this
8007/// operator.
8008///
8009/// \param Functions The set of non-member functions that will be
8010/// considered by overload resolution. The caller needs to build this
8011/// set based on the context using, e.g.,
8012/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8013/// set should not contain any member functions; those will be added
8014/// by CreateOverloadedBinOp().
8015///
8016/// \param LHS Left-hand argument.
8017/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008018ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008019Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008020 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008021 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008022 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008023 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008024 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008025
8026 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8027 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8028 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8029
8030 // If either side is type-dependent, create an appropriate dependent
8031 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008032 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008033 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008034 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008035 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008036 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008037 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008038 Context.DependentTy,
8039 VK_RValue, OK_Ordinary,
8040 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008041
Douglas Gregor5287f092009-11-05 00:51:44 +00008042 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8043 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008044 VK_LValue,
8045 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008046 Context.DependentTy,
8047 Context.DependentTy,
8048 OpLoc));
8049 }
John McCall4c4c1df2010-01-26 03:27:55 +00008050
8051 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008052 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008053 // TODO: provide better source location info in DNLoc component.
8054 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008055 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008056 = UnresolvedLookupExpr::Create(Context, NamingClass,
8057 NestedNameSpecifierLoc(), OpNameInfo,
8058 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008059 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008060 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008061 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008062 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008063 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008064 OpLoc));
8065 }
8066
John McCalle26a8722010-12-04 08:14:53 +00008067 // Always do property rvalue conversions on the RHS.
8068 if (Args[1]->getObjectKind() == OK_ObjCProperty)
8069 ConvertPropertyForRValue(Args[1]);
8070
8071 // The LHS is more complicated.
8072 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8073
8074 // There's a tension for assignment operators between primitive
8075 // property assignment and the overloaded operators.
8076 if (BinaryOperator::isAssignmentOp(Opc)) {
8077 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8078
8079 // Is the property "logically" settable?
8080 bool Settable = (PRE->isExplicitProperty() ||
8081 PRE->getImplicitPropertySetter());
8082
8083 // To avoid gratuitously inventing semantics, use the primitive
8084 // unless it isn't. Thoughts in case we ever really care:
8085 // - If the property isn't logically settable, we have to
8086 // load and hope.
8087 // - If the property is settable and this is simple assignment,
8088 // we really should use the primitive.
8089 // - If the property is settable, then we could try overloading
8090 // on a generic lvalue of the appropriate type; if it works
8091 // out to a builtin candidate, we would do that same operation
8092 // on the property, and otherwise just error.
8093 if (Settable)
8094 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8095 }
8096
8097 ConvertPropertyForRValue(Args[0]);
8098 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008099
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008100 // If this is the assignment operator, we only perform overload resolution
8101 // if the left-hand side is a class or enumeration type. This is actually
8102 // a hack. The standard requires that we do overload resolution between the
8103 // various built-in candidates, but as DR507 points out, this can lead to
8104 // problems. So we do it this way, which pretty much follows what GCC does.
8105 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008106 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008107 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008108
John McCalle26a8722010-12-04 08:14:53 +00008109 // If this is the .* operator, which is not overloadable, just
8110 // create a built-in binary operator.
8111 if (Opc == BO_PtrMemD)
8112 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8113
Douglas Gregor084d8552009-03-13 23:49:33 +00008114 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008115 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008116
8117 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008118 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008119
8120 // Add operator candidates that are member functions.
8121 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8122
John McCall4c4c1df2010-01-26 03:27:55 +00008123 // Add candidates from ADL.
8124 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8125 Args, 2,
8126 /*ExplicitTemplateArgs*/ 0,
8127 CandidateSet);
8128
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008129 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008130 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008131
8132 // Perform overload resolution.
8133 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008134 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008135 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008136 // We found a built-in operator or an overloaded operator.
8137 FunctionDecl *FnDecl = Best->Function;
8138
8139 if (FnDecl) {
8140 // We matched an overloaded operator. Build a call to that
8141 // operator.
8142
Chandler Carruth30141632011-02-25 19:41:05 +00008143 MarkDeclarationReferenced(OpLoc, FnDecl);
8144
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008145 // Convert the arguments.
8146 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008147 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008148 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008149
Chandler Carruth8e543b32010-12-12 08:17:55 +00008150 ExprResult Arg1 =
8151 PerformCopyInitialization(
8152 InitializedEntity::InitializeParameter(Context,
8153 FnDecl->getParamDecl(0)),
8154 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008155 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008156 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008157
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008158 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008159 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008160 return ExprError();
8161
8162 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008163 } else {
8164 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008165 ExprResult Arg0 = PerformCopyInitialization(
8166 InitializedEntity::InitializeParameter(Context,
8167 FnDecl->getParamDecl(0)),
8168 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008169 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008170 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008171
Chandler Carruth8e543b32010-12-12 08:17:55 +00008172 ExprResult Arg1 =
8173 PerformCopyInitialization(
8174 InitializedEntity::InitializeParameter(Context,
8175 FnDecl->getParamDecl(1)),
8176 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008177 if (Arg1.isInvalid())
8178 return ExprError();
8179 Args[0] = LHS = Arg0.takeAs<Expr>();
8180 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008181 }
8182
John McCall4fa0d5f2010-05-06 18:15:07 +00008183 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8184
John McCall7decc9e2010-11-18 06:31:45 +00008185 // Determine the result type.
8186 QualType ResultTy = FnDecl->getResultType();
8187 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8188 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008189
8190 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00008191 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008192
John McCallb268a282010-08-23 23:25:46 +00008193 CXXOperatorCallExpr *TheCall =
8194 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008195 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008196
8197 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008198 FnDecl))
8199 return ExprError();
8200
John McCallb268a282010-08-23 23:25:46 +00008201 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008202 } else {
8203 // We matched a built-in operator. Convert the arguments, then
8204 // break out so that we will build the appropriate built-in
8205 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00008206 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008207 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00008208 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008209 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008210 return ExprError();
8211
8212 break;
8213 }
8214 }
8215
Douglas Gregor66950a32009-09-30 21:46:01 +00008216 case OR_No_Viable_Function: {
8217 // C++ [over.match.oper]p9:
8218 // If the operator is the operator , [...] and there are no
8219 // viable functions, then the operator is assumed to be the
8220 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008221 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008222 break;
8223
Chandler Carruth8e543b32010-12-12 08:17:55 +00008224 // For class as left operand for assignment or compound assigment
8225 // operator do not fall through to handling in built-in, but report that
8226 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008227 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008228 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008229 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008230 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8231 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008232 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008233 } else {
8234 // No viable function; try to create a built-in operation, which will
8235 // produce an error. Then, show the non-viable candidates.
8236 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008237 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008238 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008239 "C++ binary operator overloading is missing candidates!");
8240 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008241 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8242 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008243 return move(Result);
8244 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008245
8246 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008247 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008248 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008249 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008250 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008251 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8252 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008253 return ExprError();
8254
8255 case OR_Deleted:
8256 Diag(OpLoc, diag::err_ovl_deleted_oper)
8257 << Best->Function->isDeleted()
8258 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008259 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008260 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008261 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008262 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008263 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008264
Douglas Gregor66950a32009-09-30 21:46:01 +00008265 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008266 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008267}
8268
John McCalldadc5752010-08-24 06:29:42 +00008269ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008270Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8271 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008272 Expr *Base, Expr *Idx) {
8273 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008274 DeclarationName OpName =
8275 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8276
8277 // If either side is type-dependent, create an appropriate dependent
8278 // expression.
8279 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8280
John McCall58cc69d2010-01-27 01:50:18 +00008281 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008282 // CHECKME: no 'operator' keyword?
8283 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8284 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008285 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008286 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008287 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008288 /*ADL*/ true, /*Overloaded*/ false,
8289 UnresolvedSetIterator(),
8290 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008291 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008292
Sebastian Redladba46e2009-10-29 20:17:01 +00008293 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8294 Args, 2,
8295 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008296 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008297 RLoc));
8298 }
8299
John McCalle26a8722010-12-04 08:14:53 +00008300 if (Args[0]->getObjectKind() == OK_ObjCProperty)
8301 ConvertPropertyForRValue(Args[0]);
8302 if (Args[1]->getObjectKind() == OK_ObjCProperty)
8303 ConvertPropertyForRValue(Args[1]);
8304
Sebastian Redladba46e2009-10-29 20:17:01 +00008305 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008306 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008307
8308 // Subscript can only be overloaded as a member function.
8309
8310 // Add operator candidates that are member functions.
8311 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8312
8313 // Add builtin operator candidates.
8314 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8315
8316 // Perform overload resolution.
8317 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008318 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008319 case OR_Success: {
8320 // We found a built-in operator or an overloaded operator.
8321 FunctionDecl *FnDecl = Best->Function;
8322
8323 if (FnDecl) {
8324 // We matched an overloaded operator. Build a call to that
8325 // operator.
8326
Chandler Carruth30141632011-02-25 19:41:05 +00008327 MarkDeclarationReferenced(LLoc, FnDecl);
8328
John McCalla0296f72010-03-19 07:35:19 +00008329 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008330 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008331
Sebastian Redladba46e2009-10-29 20:17:01 +00008332 // Convert the arguments.
8333 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008334 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008335 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00008336 return ExprError();
8337
Anders Carlssona68e51e2010-01-29 18:37:50 +00008338 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008339 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008340 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008341 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008342 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008343 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008344 Owned(Args[1]));
8345 if (InputInit.isInvalid())
8346 return ExprError();
8347
8348 Args[1] = InputInit.takeAs<Expr>();
8349
Sebastian Redladba46e2009-10-29 20:17:01 +00008350 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008351 QualType ResultTy = FnDecl->getResultType();
8352 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8353 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008354
8355 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00008356 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008357
John McCallb268a282010-08-23 23:25:46 +00008358 CXXOperatorCallExpr *TheCall =
8359 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
8360 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008361 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008362
John McCallb268a282010-08-23 23:25:46 +00008363 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008364 FnDecl))
8365 return ExprError();
8366
John McCallb268a282010-08-23 23:25:46 +00008367 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008368 } else {
8369 // We matched a built-in operator. Convert the arguments, then
8370 // break out so that we will build the appropriate built-in
8371 // operator node.
8372 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008373 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00008374 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008375 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00008376 return ExprError();
8377
8378 break;
8379 }
8380 }
8381
8382 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008383 if (CandidateSet.empty())
8384 Diag(LLoc, diag::err_ovl_no_oper)
8385 << Args[0]->getType() << /*subscript*/ 0
8386 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8387 else
8388 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8389 << Args[0]->getType()
8390 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008391 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8392 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008393 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008394 }
8395
8396 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008397 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008398 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008399 << Args[0]->getType() << Args[1]->getType()
8400 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008401 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8402 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008403 return ExprError();
8404
8405 case OR_Deleted:
8406 Diag(LLoc, diag::err_ovl_deleted_oper)
8407 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008408 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00008409 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008410 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8411 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008412 return ExprError();
8413 }
8414
8415 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008416 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008417}
8418
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008419/// BuildCallToMemberFunction - Build a call to a member
8420/// function. MemExpr is the expression that refers to the member
8421/// function (and includes the object parameter), Args/NumArgs are the
8422/// arguments to the function call (not including the object
8423/// parameter). The caller needs to validate that the member
8424/// expression refers to a member function or an overloaded member
8425/// function.
John McCalldadc5752010-08-24 06:29:42 +00008426ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008427Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8428 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008429 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008430 // Dig out the member expression. This holds both the object
8431 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008432 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008433
John McCall10eae182009-11-30 22:42:35 +00008434 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008435 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008436 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008437 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008438 if (isa<MemberExpr>(NakedMemExpr)) {
8439 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008440 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008441 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008442 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008443 } else {
8444 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008445 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008446
John McCall6e9f8f62009-12-03 04:06:58 +00008447 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008448 Expr::Classification ObjectClassification
8449 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8450 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008451
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008452 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008453 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008454
John McCall2d74de92009-12-01 22:10:20 +00008455 // FIXME: avoid copy.
8456 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8457 if (UnresExpr->hasExplicitTemplateArgs()) {
8458 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8459 TemplateArgs = &TemplateArgsBuffer;
8460 }
8461
John McCall10eae182009-11-30 22:42:35 +00008462 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8463 E = UnresExpr->decls_end(); I != E; ++I) {
8464
John McCall6e9f8f62009-12-03 04:06:58 +00008465 NamedDecl *Func = *I;
8466 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8467 if (isa<UsingShadowDecl>(Func))
8468 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8469
Douglas Gregor02824322011-01-26 19:30:28 +00008470
Francois Pichet64225792011-01-18 05:04:39 +00008471 // Microsoft supports direct constructor calls.
8472 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8473 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8474 CandidateSet);
8475 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008476 // If explicit template arguments were provided, we can't call a
8477 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008478 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008479 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008480
John McCalla0296f72010-03-19 07:35:19 +00008481 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008482 ObjectClassification,
8483 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00008484 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008485 } else {
John McCall10eae182009-11-30 22:42:35 +00008486 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008487 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008488 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00008489 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008490 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008491 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008492 }
Mike Stump11289f42009-09-09 15:08:12 +00008493
John McCall10eae182009-11-30 22:42:35 +00008494 DeclarationName DeclName = UnresExpr->getMemberName();
8495
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008496 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008497 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008498 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008499 case OR_Success:
8500 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00008501 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00008502 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008503 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008504 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008505 break;
8506
8507 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008508 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008509 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008510 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008511 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008512 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008513 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008514
8515 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008516 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008517 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008518 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008519 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008520 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008521
8522 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008523 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008524 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008525 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008526 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008527 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008528 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008529 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008530 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008531 }
8532
John McCall16df1e52010-03-30 21:47:33 +00008533 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008534
John McCall2d74de92009-12-01 22:10:20 +00008535 // If overload resolution picked a static member, build a
8536 // non-member call based on that function.
8537 if (Method->isStatic()) {
8538 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8539 Args, NumArgs, RParenLoc);
8540 }
8541
John McCall10eae182009-11-30 22:42:35 +00008542 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008543 }
8544
John McCall7decc9e2010-11-18 06:31:45 +00008545 QualType ResultType = Method->getResultType();
8546 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8547 ResultType = ResultType.getNonLValueExprType(Context);
8548
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008549 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008550 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00008551 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008552 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008553
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008554 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008555 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008556 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008557 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008558
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008559 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008560 // We only need to do this if there was actually an overload; otherwise
8561 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008562 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008563 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008564 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8565 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008566 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008567 MemExpr->setBase(ObjectArg);
8568
8569 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008570 const FunctionProtoType *Proto =
8571 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008572 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008573 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008574 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008575
John McCallb268a282010-08-23 23:25:46 +00008576 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008577 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008578
John McCallb268a282010-08-23 23:25:46 +00008579 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008580}
8581
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008582/// BuildCallToObjectOfClassType - Build a call to an object of class
8583/// type (C++ [over.call.object]), which can end up invoking an
8584/// overloaded function call operator (@c operator()) or performing a
8585/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008586ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008587Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008588 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008589 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008590 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008591 if (Object->getObjectKind() == OK_ObjCProperty)
8592 ConvertPropertyForRValue(Object);
8593
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008594 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008595 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008596
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008597 // C++ [over.call.object]p1:
8598 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008599 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008600 // candidate functions includes at least the function call
8601 // operators of T. The function call operators of T are obtained by
8602 // ordinary lookup of the name operator() in the context of
8603 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008604 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008605 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008606
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008607 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008608 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008609 << Object->getSourceRange()))
8610 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008611
John McCall27b18f82009-11-17 02:14:36 +00008612 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8613 LookupQualifiedName(R, Record->getDecl());
8614 R.suppressDiagnostics();
8615
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008616 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008617 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008618 AddMethodCandidate(Oper.getPair(), Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00008619 Object->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008620 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008622
Douglas Gregorab7897a2008-11-19 22:57:39 +00008623 // C++ [over.call.object]p2:
8624 // In addition, for each conversion function declared in T of the
8625 // form
8626 //
8627 // operator conversion-type-id () cv-qualifier;
8628 //
8629 // where cv-qualifier is the same cv-qualification as, or a
8630 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008631 // denotes the type "pointer to function of (P1,...,Pn) returning
8632 // R", or the type "reference to pointer to function of
8633 // (P1,...,Pn) returning R", or the type "reference to function
8634 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008635 // is also considered as a candidate function. Similarly,
8636 // surrogate call functions are added to the set of candidate
8637 // functions for each conversion function declared in an
8638 // accessible base class provided the function is not hidden
8639 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008640 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008641 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008642 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008643 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008644 NamedDecl *D = *I;
8645 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8646 if (isa<UsingShadowDecl>(D))
8647 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008648
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008649 // Skip over templated conversion functions; they aren't
8650 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008651 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008652 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008653
John McCall6e9f8f62009-12-03 04:06:58 +00008654 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008655
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008656 // Strip the reference type (if any) and then the pointer type (if
8657 // any) to get down to what might be a function type.
8658 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8659 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8660 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008661
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008662 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008663 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00008664 Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008665 }
Mike Stump11289f42009-09-09 15:08:12 +00008666
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008667 // Perform overload resolution.
8668 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008669 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8670 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008671 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008672 // Overload resolution succeeded; we'll build the appropriate call
8673 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008674 break;
8675
8676 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008677 if (CandidateSet.empty())
8678 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8679 << Object->getType() << /*call*/ 1
8680 << Object->getSourceRange();
8681 else
8682 Diag(Object->getSourceRange().getBegin(),
8683 diag::err_ovl_no_viable_object_call)
8684 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008685 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008686 break;
8687
8688 case OR_Ambiguous:
8689 Diag(Object->getSourceRange().getBegin(),
8690 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008691 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008692 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008693 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008694
8695 case OR_Deleted:
8696 Diag(Object->getSourceRange().getBegin(),
8697 diag::err_ovl_deleted_object_call)
8698 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008699 << Object->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008700 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008701 << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008702 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008703 break;
Mike Stump11289f42009-09-09 15:08:12 +00008704 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008705
Douglas Gregorb412e172010-07-25 18:17:45 +00008706 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008707 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008708
Douglas Gregorab7897a2008-11-19 22:57:39 +00008709 if (Best->Function == 0) {
8710 // Since there is no function declaration, this is one of the
8711 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008712 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008713 = cast<CXXConversionDecl>(
8714 Best->Conversions[0].UserDefined.ConversionFunction);
8715
John McCalla0296f72010-03-19 07:35:19 +00008716 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008717 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008718
Douglas Gregorab7897a2008-11-19 22:57:39 +00008719 // We selected one of the surrogate functions that converts the
8720 // object parameter to a function pointer. Perform the conversion
8721 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008722
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008723 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008724 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008725 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8726 if (Call.isInvalid())
8727 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008728
Douglas Gregor668443e2011-01-20 00:18:04 +00008729 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008730 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008731 }
8732
Chandler Carruth30141632011-02-25 19:41:05 +00008733 MarkDeclarationReferenced(LParenLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00008734 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008735 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008736
Douglas Gregorab7897a2008-11-19 22:57:39 +00008737 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8738 // that calls this method, using Object for the implicit object
8739 // parameter and passing along the remaining arguments.
8740 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008741 const FunctionProtoType *Proto =
8742 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008743
8744 unsigned NumArgsInProto = Proto->getNumArgs();
8745 unsigned NumArgsToCheck = NumArgs;
8746
8747 // Build the full argument list for the method call (the
8748 // implicit object parameter is placed at the beginning of the
8749 // list).
8750 Expr **MethodArgs;
8751 if (NumArgs < NumArgsInProto) {
8752 NumArgsToCheck = NumArgsInProto;
8753 MethodArgs = new Expr*[NumArgsInProto + 1];
8754 } else {
8755 MethodArgs = new Expr*[NumArgs + 1];
8756 }
8757 MethodArgs[0] = Object;
8758 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8759 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008760
John McCall7decc9e2010-11-18 06:31:45 +00008761 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008762
8763 // Once we've built TheCall, all of the expressions are properly
8764 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008765 QualType ResultTy = Method->getResultType();
8766 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8767 ResultTy = ResultTy.getNonLValueExprType(Context);
8768
John McCallb268a282010-08-23 23:25:46 +00008769 CXXOperatorCallExpr *TheCall =
8770 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8771 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008772 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008773 delete [] MethodArgs;
8774
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008775 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008776 Method))
8777 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008778
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008779 // We may have default arguments. If so, we need to allocate more
8780 // slots in the call for them.
8781 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008782 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008783 else if (NumArgs > NumArgsInProto)
8784 NumArgsToCheck = NumArgsInProto;
8785
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008786 bool IsError = false;
8787
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008788 // Initialize the implicit object parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008789 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008790 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008791 TheCall->setArg(0, Object);
8792
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008793
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008794 // Check the argument types.
8795 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008796 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008797 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008798 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008799
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008800 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008801
John McCalldadc5752010-08-24 06:29:42 +00008802 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008803 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008804 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008805 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008806 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008807
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008808 IsError |= InputInit.isInvalid();
8809 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008810 } else {
John McCalldadc5752010-08-24 06:29:42 +00008811 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008812 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8813 if (DefArg.isInvalid()) {
8814 IsError = true;
8815 break;
8816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008817
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008818 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008819 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008820
8821 TheCall->setArg(i + 1, Arg);
8822 }
8823
8824 // If this is a variadic call, handle args passed through "...".
8825 if (Proto->isVariadic()) {
8826 // Promote the arguments (C99 6.5.2.2p7).
8827 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8828 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008829 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008830 TheCall->setArg(i + 1, Arg);
8831 }
8832 }
8833
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008834 if (IsError) return true;
8835
John McCallb268a282010-08-23 23:25:46 +00008836 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008837 return true;
8838
John McCalle172be52010-08-24 06:09:16 +00008839 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008840}
8841
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008842/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008843/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008844/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008845ExprResult
John McCallb268a282010-08-23 23:25:46 +00008846Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008847 assert(Base->getType()->isRecordType() &&
8848 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008849
John McCalle26a8722010-12-04 08:14:53 +00008850 if (Base->getObjectKind() == OK_ObjCProperty)
8851 ConvertPropertyForRValue(Base);
8852
John McCallbc077cf2010-02-08 23:07:23 +00008853 SourceLocation Loc = Base->getExprLoc();
8854
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008855 // C++ [over.ref]p1:
8856 //
8857 // [...] An expression x->m is interpreted as (x.operator->())->m
8858 // for a class object x of type T if T::operator->() exists and if
8859 // the operator is selected as the best match function by the
8860 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008861 DeclarationName OpName =
8862 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008863 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008864 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008865
John McCallbc077cf2010-02-08 23:07:23 +00008866 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008867 PDiag(diag::err_typecheck_incomplete_tag)
8868 << Base->getSourceRange()))
8869 return ExprError();
8870
John McCall27b18f82009-11-17 02:14:36 +00008871 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8872 LookupQualifiedName(R, BaseRecord->getDecl());
8873 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008874
8875 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008876 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00008877 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8878 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008879 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008880
8881 // Perform overload resolution.
8882 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008883 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008884 case OR_Success:
8885 // Overload resolution succeeded; we'll build the call below.
8886 break;
8887
8888 case OR_No_Viable_Function:
8889 if (CandidateSet.empty())
8890 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008891 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008892 else
8893 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008894 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008895 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008896 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008897
8898 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008899 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8900 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008901 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008902 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008903
8904 case OR_Deleted:
8905 Diag(OpLoc, diag::err_ovl_deleted_oper)
8906 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008907 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008908 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008909 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008910 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008911 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008912 }
8913
Chandler Carruth30141632011-02-25 19:41:05 +00008914 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00008915 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008916 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008917
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008918 // Convert the object parameter.
8919 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008920 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8921 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008922 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008923
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008924 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008925 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008926
John McCall7decc9e2010-11-18 06:31:45 +00008927 QualType ResultTy = Method->getResultType();
8928 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8929 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008930 CXXOperatorCallExpr *TheCall =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008931 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008932 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008933
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008934 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008935 Method))
8936 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00008937
8938 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008939}
8940
Douglas Gregorcd695e52008-11-10 20:40:00 +00008941/// FixOverloadedFunctionReference - E is an expression that refers to
8942/// a C++ overloaded function (possibly with some parentheses and
8943/// perhaps a '&' around it). We have resolved the overloaded function
8944/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008945/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008946Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008947 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008948 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008949 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8950 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008951 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008952 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008953
Douglas Gregor51c538b2009-11-20 19:42:02 +00008954 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008955 }
8956
Douglas Gregor51c538b2009-11-20 19:42:02 +00008957 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008958 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8959 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008960 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008961 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008962 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008963 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008964 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008965 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008966
8967 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00008968 ICE->getCastKind(),
8969 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008970 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008971 }
8972
Douglas Gregor51c538b2009-11-20 19:42:02 +00008973 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008974 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008975 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008976 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8977 if (Method->isStatic()) {
8978 // Do nothing: static member functions aren't any different
8979 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008980 } else {
John McCalle66edc12009-11-24 19:00:30 +00008981 // Fix the sub expression, which really has to be an
8982 // UnresolvedLookupExpr holding an overloaded member function
8983 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008984 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8985 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008986 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008987 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008988
John McCalld14a8642009-11-21 08:51:07 +00008989 assert(isa<DeclRefExpr>(SubExpr)
8990 && "fixed to something other than a decl ref");
8991 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8992 && "fixed to a member ref with no nested name qualifier");
8993
8994 // We have taken the address of a pointer to member
8995 // function. Perform the computation here so that we get the
8996 // appropriate pointer to member type.
8997 QualType ClassType
8998 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8999 QualType MemPtrType
9000 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9001
John McCall7decc9e2010-11-18 06:31:45 +00009002 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9003 VK_RValue, OK_Ordinary,
9004 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009005 }
9006 }
John McCall16df1e52010-03-30 21:47:33 +00009007 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9008 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009009 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009010 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009011
John McCalle3027922010-08-25 11:45:40 +00009012 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009013 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009014 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009015 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009016 }
John McCalld14a8642009-11-21 08:51:07 +00009017
9018 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009019 // FIXME: avoid copy.
9020 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009021 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009022 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9023 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009024 }
9025
John McCalld14a8642009-11-21 08:51:07 +00009026 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009027 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009028 Fn,
9029 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009030 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009031 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00009032 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009033 }
9034
John McCall10eae182009-11-30 22:42:35 +00009035 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009036 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009037 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9038 if (MemExpr->hasExplicitTemplateArgs()) {
9039 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9040 TemplateArgs = &TemplateArgsBuffer;
9041 }
John McCall6b51f282009-11-23 01:53:49 +00009042
John McCall2d74de92009-12-01 22:10:20 +00009043 Expr *Base;
9044
John McCall7decc9e2010-11-18 06:31:45 +00009045 // If we're filling in a static method where we used to have an
9046 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009047 if (MemExpr->isImplicitAccess()) {
9048 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9049 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009050 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009051 Fn,
9052 MemExpr->getMemberLoc(),
9053 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009054 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00009055 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009056 } else {
9057 SourceLocation Loc = MemExpr->getMemberLoc();
9058 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009059 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009060 Base = new (Context) CXXThisExpr(Loc,
9061 MemExpr->getBaseType(),
9062 /*isImplicit=*/true);
9063 }
John McCall2d74de92009-12-01 22:10:20 +00009064 } else
John McCallc3007a22010-10-26 07:05:15 +00009065 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009066
9067 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009068 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009069 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009070 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009071 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009072 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009073 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009074 Fn->getType(),
9075 cast<CXXMethodDecl>(Fn)->isStatic()
9076 ? VK_LValue : VK_RValue,
9077 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009079
John McCallc3007a22010-10-26 07:05:15 +00009080 llvm_unreachable("Invalid reference to overloaded function");
9081 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009082}
9083
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009084ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009085 DeclAccessPair Found,
9086 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009087 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009088}
9089
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009090} // end namespace clang