blob: 7458a24dc8f4c1744c1c479ff6476c452c7886a6 [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000023#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000025#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000026#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000027#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000029#include <algorithm>
30
31namespace clang {
32
33/// GetConversionCategory - Retrieve the implicit conversion
34/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000035ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036GetConversionCategory(ImplicitConversionKind Kind) {
37 static const ImplicitConversionCategory
38 Category[(int)ICK_Num_Conversion_Kinds] = {
39 ICC_Identity,
40 ICC_Lvalue_Transformation,
41 ICC_Lvalue_Transformation,
42 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000043 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000044 ICC_Qualification_Adjustment,
45 ICC_Promotion,
46 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000047 ICC_Promotion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000050 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
53 ICC_Conversion,
54 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000055 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000056 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000057 ICC_Conversion,
58 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000059 ICC_Conversion
60 };
61 return Category[(int)Kind];
62}
63
64/// GetConversionRank - Retrieve the implicit conversion rank
65/// corresponding to the given implicit conversion kind.
66ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
67 static const ImplicitConversionRank
68 Rank[(int)ICK_Num_Conversion_Kinds] = {
69 ICR_Exact_Match,
70 ICR_Exact_Match,
71 ICR_Exact_Match,
72 ICR_Exact_Match,
73 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000074 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000075 ICR_Promotion,
76 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000077 ICR_Promotion,
78 ICR_Conversion,
79 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000080 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
83 ICR_Conversion,
84 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000085 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000086 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000087 ICR_Conversion,
88 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000089 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000090 };
91 return Rank[(int)Kind];
92}
93
94/// GetImplicitConversionName - Return the name of this kind of
95/// implicit conversion.
96const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000097 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "No conversion",
99 "Lvalue-to-rvalue",
100 "Array-to-pointer",
101 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000102 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 "Qualification",
104 "Integral promotion",
105 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000106 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107 "Integral conversion",
108 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000109 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110 "Floating-integral conversion",
111 "Pointer conversion",
112 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000113 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000114 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000115 "Derived-to-base conversion",
116 "Vector conversion",
117 "Vector splat",
118 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000119 };
120 return Name[Kind];
121}
122
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000123/// StandardConversionSequence - Set the standard conversion
124/// sequence to the identity conversion.
125void StandardConversionSequence::setAsIdentityConversion() {
126 First = ICK_Identity;
127 Second = ICK_Identity;
128 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000129 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000130 ReferenceBinding = false;
131 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000132 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000133 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000134}
135
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000136/// getRank - Retrieve the rank of this standard conversion sequence
137/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
138/// implicit conversions.
139ImplicitConversionRank StandardConversionSequence::getRank() const {
140 ImplicitConversionRank Rank = ICR_Exact_Match;
141 if (GetConversionRank(First) > Rank)
142 Rank = GetConversionRank(First);
143 if (GetConversionRank(Second) > Rank)
144 Rank = GetConversionRank(Second);
145 if (GetConversionRank(Third) > Rank)
146 Rank = GetConversionRank(Third);
147 return Rank;
148}
149
150/// isPointerConversionToBool - Determines whether this conversion is
151/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000152/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000154bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 // Note that FromType has not necessarily been transformed by the
156 // array-to-pointer or function-to-pointer implicit conversions, so
157 // check for their presence as well as checking whether FromType is
158 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000159 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000160 (getFromType()->isPointerType() ||
161 getFromType()->isObjCObjectPointerType() ||
162 getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
164 return true;
165
166 return false;
167}
168
Douglas Gregor5c407d92008-10-23 00:40:37 +0000169/// isPointerConversionToVoidPointer - Determines whether this
170/// conversion is a conversion of a pointer to a void pointer. This is
171/// used as part of the ranking of standard conversion sequences (C++
172/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000173bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000174StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000175isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000176 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000177 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000178
179 // Note that FromType has not necessarily been transformed by the
180 // array-to-pointer implicit conversion, so check for its presence
181 // and redo the conversion to get a pointer.
182 if (First == ICK_Array_To_Pointer)
183 FromType = Context.getArrayDecayedType(FromType);
184
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000185 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000186 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000187 return ToPtrType->getPointeeType()->isVoidType();
188
189 return false;
190}
191
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000192/// DebugPrint - Print this standard conversion sequence to standard
193/// error. Useful for debugging overloading issues.
194void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000195 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000196 bool PrintedSomething = false;
197 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000198 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000199 PrintedSomething = true;
200 }
201
202 if (Second != ICK_Identity) {
203 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000204 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000206 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000207
208 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000209 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000210 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000211 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000212 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000213 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000214 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000215 PrintedSomething = true;
216 }
217
218 if (Third != ICK_Identity) {
219 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000220 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000222 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 PrintedSomething = true;
224 }
225
226 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
229}
230
231/// DebugPrint - Print this user-defined conversion sequence to standard
232/// error. Useful for debugging overloading issues.
233void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000234 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000235 if (Before.First || Before.Second || Before.Third) {
236 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000237 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000239 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000241 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000242 After.DebugPrint();
243 }
244}
245
246/// DebugPrint - Print this implicit conversion sequence to standard
247/// error. Useful for debugging overloading issues.
248void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000249 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000250 switch (ConversionKind) {
251 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000252 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000253 Standard.DebugPrint();
254 break;
255 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 UserDefined.DebugPrint();
258 break;
259 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261 break;
John McCall0d1da222010-01-12 00:44:57 +0000262 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000263 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000264 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000266 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000267 break;
268 }
269
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000270 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000271}
272
John McCall0d1da222010-01-12 00:44:57 +0000273void AmbiguousConversionSequence::construct() {
274 new (&conversions()) ConversionSet();
275}
276
277void AmbiguousConversionSequence::destruct() {
278 conversions().~ConversionSet();
279}
280
281void
282AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
283 FromTypePtr = O.FromTypePtr;
284 ToTypePtr = O.ToTypePtr;
285 new (&conversions()) ConversionSet(O.conversions());
286}
287
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000288namespace {
289 // Structure used by OverloadCandidate::DeductionFailureInfo to store
290 // template parameter and template argument information.
291 struct DFIParamWithArguments {
292 TemplateParameter Param;
293 TemplateArgument FirstArg;
294 TemplateArgument SecondArg;
295 };
296}
297
298/// \brief Convert from Sema's representation of template deduction information
299/// to the form used in overload-candidate information.
300OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000301static MakeDeductionFailureInfo(ASTContext &Context,
302 Sema::TemplateDeductionResult TDK,
Douglas Gregord09efd42010-05-08 20:07:26 +0000303 Sema::TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000304 OverloadCandidate::DeductionFailureInfo Result;
305 Result.Result = static_cast<unsigned>(TDK);
306 Result.Data = 0;
307 switch (TDK) {
308 case Sema::TDK_Success:
309 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000310 case Sema::TDK_TooManyArguments:
311 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000312 break;
313
314 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000315 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000316 Result.Data = Info.Param.getOpaqueValue();
317 break;
318
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000319 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000320 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000321 // FIXME: Should allocate from normal heap so that we can free this later.
322 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000323 Saved->Param = Info.Param;
324 Saved->FirstArg = Info.FirstArg;
325 Saved->SecondArg = Info.SecondArg;
326 Result.Data = Saved;
327 break;
328 }
329
330 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000331 Result.Data = Info.take();
332 break;
333
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000334 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000335 case Sema::TDK_FailedOverloadResolution:
336 break;
337 }
338
339 return Result;
340}
John McCall0d1da222010-01-12 00:44:57 +0000341
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000342void OverloadCandidate::DeductionFailureInfo::Destroy() {
343 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
344 case Sema::TDK_Success:
345 case Sema::TDK_InstantiationDepth:
346 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000347 case Sema::TDK_TooManyArguments:
348 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000349 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 break;
351
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000352 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000353 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000354 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000355 Data = 0;
356 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000357
358 case Sema::TDK_SubstitutionFailure:
359 // FIXME: Destroy the template arugment list?
360 Data = 0;
361 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362
Douglas Gregor461761d2010-05-08 18:20:53 +0000363 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000364 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 case Sema::TDK_FailedOverloadResolution:
366 break;
367 }
368}
369
370TemplateParameter
371OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
372 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
373 case Sema::TDK_Success:
374 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000375 case Sema::TDK_TooManyArguments:
376 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000377 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000378 return TemplateParameter();
379
380 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000381 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000382 return TemplateParameter::getFromOpaqueValue(Data);
383
384 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000385 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 return static_cast<DFIParamWithArguments*>(Data)->Param;
387
388 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000389 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000390 case Sema::TDK_FailedOverloadResolution:
391 break;
392 }
393
394 return TemplateParameter();
395}
Douglas Gregord09efd42010-05-08 20:07:26 +0000396
397TemplateArgumentList *
398OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
399 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
400 case Sema::TDK_Success:
401 case Sema::TDK_InstantiationDepth:
402 case Sema::TDK_TooManyArguments:
403 case Sema::TDK_TooFewArguments:
404 case Sema::TDK_Incomplete:
405 case Sema::TDK_InvalidExplicitArguments:
406 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000407 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000408 return 0;
409
410 case Sema::TDK_SubstitutionFailure:
411 return static_cast<TemplateArgumentList*>(Data);
412
413 // Unhandled
414 case Sema::TDK_NonDeducedMismatch:
415 case Sema::TDK_FailedOverloadResolution:
416 break;
417 }
418
419 return 0;
420}
421
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
423 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
424 case Sema::TDK_Success:
425 case Sema::TDK_InstantiationDepth:
426 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000427 case Sema::TDK_TooManyArguments:
428 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000429 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000430 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 return 0;
432
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000433 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000434 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000435 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
436
Douglas Gregor461761d2010-05-08 18:20:53 +0000437 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000438 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000439 case Sema::TDK_FailedOverloadResolution:
440 break;
441 }
442
443 return 0;
444}
445
446const TemplateArgument *
447OverloadCandidate::DeductionFailureInfo::getSecondArg() {
448 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
449 case Sema::TDK_Success:
450 case Sema::TDK_InstantiationDepth:
451 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000452 case Sema::TDK_TooManyArguments:
453 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000454 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000455 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000456 return 0;
457
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000459 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
461
Douglas Gregor461761d2010-05-08 18:20:53 +0000462 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000463 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000464 case Sema::TDK_FailedOverloadResolution:
465 break;
466 }
467
468 return 0;
469}
470
471void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000472 inherited::clear();
473 Functions.clear();
474}
475
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000477// overload of the declarations in Old. This routine returns false if
478// New and Old cannot be overloaded, e.g., if New has the same
479// signature as some function in Old (C++ 1.3.10) or if the Old
480// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000481// it does return false, MatchedDecl will point to the decl that New
482// cannot be overloaded with. This decl may be a UsingShadowDecl on
483// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484//
485// Example: Given the following input:
486//
487// void f(int, float); // #1
488// void f(int, int); // #2
489// int f(int, int); // #3
490//
491// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000492// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493//
John McCall3d988d92009-12-02 08:47:38 +0000494// When we process #2, Old contains only the FunctionDecl for #1. By
495// comparing the parameter types, we see that #1 and #2 are overloaded
496// (since they have different signatures), so this routine returns
497// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498//
John McCall3d988d92009-12-02 08:47:38 +0000499// When we process #3, Old is an overload set containing #1 and #2. We
500// compare the signatures of #3 to #1 (they're overloaded, so we do
501// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
502// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000503// signature), IsOverload returns false and MatchedDecl will be set to
504// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000505//
506// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
507// into a class by a using declaration. The rules for whether to hide
508// shadow declarations ignore some properties which otherwise figure
509// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000510Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000511Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
512 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000513 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000514 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000515 NamedDecl *OldD = *I;
516
517 bool OldIsUsingDecl = false;
518 if (isa<UsingShadowDecl>(OldD)) {
519 OldIsUsingDecl = true;
520
521 // We can always introduce two using declarations into the same
522 // context, even if they have identical signatures.
523 if (NewIsUsingDecl) continue;
524
525 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
526 }
527
528 // If either declaration was introduced by a using declaration,
529 // we'll need to use slightly different rules for matching.
530 // Essentially, these rules are the normal rules, except that
531 // function templates hide function templates with different
532 // return types or template parameter lists.
533 bool UseMemberUsingDeclRules =
534 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
535
John McCall3d988d92009-12-02 08:47:38 +0000536 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000537 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
538 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
539 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
540 continue;
541 }
542
John McCalldaa3d6b2009-12-09 03:35:25 +0000543 Match = *I;
544 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545 }
John McCall3d988d92009-12-02 08:47:38 +0000546 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000547 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
548 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
549 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
550 continue;
551 }
552
John McCalldaa3d6b2009-12-09 03:35:25 +0000553 Match = *I;
554 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000555 }
John McCall84d87672009-12-10 09:41:52 +0000556 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
557 // We can overload with these, which can show up when doing
558 // redeclaration checks for UsingDecls.
559 assert(Old.getLookupKind() == LookupUsingDeclName);
560 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
561 // Optimistically assume that an unresolved using decl will
562 // overload; if it doesn't, we'll have to diagnose during
563 // template instantiation.
564 } else {
John McCall1f82f242009-11-18 22:49:29 +0000565 // (C++ 13p1):
566 // Only function declarations can be overloaded; object and type
567 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000568 Match = *I;
569 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000570 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000571 }
John McCall1f82f242009-11-18 22:49:29 +0000572
John McCalldaa3d6b2009-12-09 03:35:25 +0000573 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000574}
575
John McCalle9cccd82010-06-16 08:42:20 +0000576bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
577 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000578 // If both of the functions are extern "C", then they are not
579 // overloads.
580 if (Old->isExternC() && New->isExternC())
581 return false;
582
John McCall1f82f242009-11-18 22:49:29 +0000583 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
584 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
585
586 // C++ [temp.fct]p2:
587 // A function template can be overloaded with other function templates
588 // and with normal (non-template) functions.
589 if ((OldTemplate == 0) != (NewTemplate == 0))
590 return true;
591
592 // Is the function New an overload of the function Old?
593 QualType OldQType = Context.getCanonicalType(Old->getType());
594 QualType NewQType = Context.getCanonicalType(New->getType());
595
596 // Compare the signatures (C++ 1.3.10) of the two functions to
597 // determine whether they are overloads. If we find any mismatch
598 // in the signature, they are overloads.
599
600 // If either of these functions is a K&R-style function (no
601 // prototype), then we consider them to have matching signatures.
602 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
603 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
604 return false;
605
606 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
607 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
608
609 // The signature of a function includes the types of its
610 // parameters (C++ 1.3.10), which includes the presence or absence
611 // of the ellipsis; see C++ DR 357).
612 if (OldQType != NewQType &&
613 (OldType->getNumArgs() != NewType->getNumArgs() ||
614 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000615 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000616 return true;
617
618 // C++ [temp.over.link]p4:
619 // The signature of a function template consists of its function
620 // signature, its return type and its template parameter list. The names
621 // of the template parameters are significant only for establishing the
622 // relationship between the template parameters and the rest of the
623 // signature.
624 //
625 // We check the return type and template parameter lists for function
626 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000627 //
628 // However, we don't consider either of these when deciding whether
629 // a member introduced by a shadow declaration is hidden.
630 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000631 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
632 OldTemplate->getTemplateParameters(),
633 false, TPL_TemplateMatch) ||
634 OldType->getResultType() != NewType->getResultType()))
635 return true;
636
637 // If the function is a class member, its signature includes the
638 // cv-qualifiers (if any) on the function itself.
639 //
640 // As part of this, also check whether one of the member functions
641 // is static, in which case they are not overloads (C++
642 // 13.1p2). While not part of the definition of the signature,
643 // this check is important to determine whether these functions
644 // can be overloaded.
645 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
646 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
647 if (OldMethod && NewMethod &&
648 !OldMethod->isStatic() && !NewMethod->isStatic() &&
649 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
650 return true;
651
652 // The signatures match; this is not an overload.
653 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000654}
655
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000656/// TryImplicitConversion - Attempt to perform an implicit conversion
657/// from the given expression (Expr) to the given type (ToType). This
658/// function returns an implicit conversion sequence that can be used
659/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000660///
661/// void f(float f);
662/// void g(int i) { f(i); }
663///
664/// this routine would produce an implicit conversion sequence to
665/// describe the initialization of f from i, which will be a standard
666/// conversion sequence containing an lvalue-to-rvalue conversion (C++
667/// 4.1) followed by a floating-integral conversion (C++ 4.9).
668//
669/// Note that this routine only determines how the conversion can be
670/// performed; it does not actually perform the conversion. As such,
671/// it will not produce any diagnostics if no conversion is available,
672/// but will instead return an implicit conversion sequence of kind
673/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000674///
675/// If @p SuppressUserConversions, then user-defined conversions are
676/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000677/// If @p AllowExplicit, then explicit user-defined conversions are
678/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000679ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000680Sema::TryImplicitConversion(Expr* From, QualType ToType,
681 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000682 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000683 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000684 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000685 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000686 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000687 return ICS;
688 }
689
690 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000691 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000692 return ICS;
693 }
694
Douglas Gregor836a7e82010-08-11 02:15:33 +0000695 // C++ [over.ics.user]p4:
696 // A conversion of an expression of class type to the same class
697 // type is given Exact Match rank, and a conversion of an
698 // expression of class type to a base class of that type is
699 // given Conversion rank, in spite of the fact that a copy/move
700 // constructor (i.e., a user-defined conversion function) is
701 // called for those cases.
702 QualType FromType = From->getType();
703 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
704 (Context.hasSameUnqualifiedType(FromType, ToType) ||
705 IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000706 ICS.setStandard();
707 ICS.Standard.setAsIdentityConversion();
708 ICS.Standard.setFromType(FromType);
709 ICS.Standard.setAllToTypes(ToType);
710
711 // We don't actually check at this point whether there is a valid
712 // copy/move constructor, since overloading just assumes that it
713 // exists. When we actually perform initialization, we'll find the
714 // appropriate constructor to copy the returned object, if needed.
715 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000716
Douglas Gregor5ab11652010-04-17 22:01:05 +0000717 // Determine whether this is considered a derived-to-base conversion.
718 if (!Context.hasSameUnqualifiedType(FromType, ToType))
719 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000720
721 return ICS;
722 }
723
724 if (SuppressUserConversions) {
725 // We're not in the case above, so there is no conversion that
726 // we can perform.
727 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000728 return ICS;
729 }
730
731 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000732 OverloadCandidateSet Conversions(From->getExprLoc());
733 OverloadingResult UserDefResult
734 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000735 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000736
737 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000738 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000739 // C++ [over.ics.user]p4:
740 // A conversion of an expression of class type to the same class
741 // type is given Exact Match rank, and a conversion of an
742 // expression of class type to a base class of that type is
743 // given Conversion rank, in spite of the fact that a copy
744 // constructor (i.e., a user-defined conversion function) is
745 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000746 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000747 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000748 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000749 = Context.getCanonicalType(From->getType().getUnqualifiedType());
750 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000751 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000752 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000753 // Turn this into a "standard" conversion sequence, so that it
754 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000755 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000756 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000757 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000758 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000759 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000760 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000761 ICS.Standard.Second = ICK_Derived_To_Base;
762 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000763 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000764
765 // C++ [over.best.ics]p4:
766 // However, when considering the argument of a user-defined
767 // conversion function that is a candidate by 13.3.1.3 when
768 // invoked for the copying of the temporary in the second step
769 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
770 // 13.3.1.6 in all cases, only standard conversion sequences and
771 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000772 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000773 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000774 }
John McCalle8c8cd22010-01-13 22:30:33 +0000775 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000776 ICS.setAmbiguous();
777 ICS.Ambiguous.setFromType(From->getType());
778 ICS.Ambiguous.setToType(ToType);
779 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
780 Cand != Conversions.end(); ++Cand)
781 if (Cand->Viable)
782 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000783 } else {
John McCall65eb8792010-02-25 01:37:24 +0000784 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000785 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000786
787 return ICS;
788}
789
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000790/// PerformImplicitConversion - Perform an implicit conversion of the
791/// expression From to the type ToType. Returns true if there was an
792/// error, false otherwise. The expression From is replaced with the
793/// converted expression. Flavor is the kind of conversion we're
794/// performing, used in the error message. If @p AllowExplicit,
795/// explicit user-defined conversions are permitted.
796bool
797Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
798 AssignmentAction Action, bool AllowExplicit) {
799 ImplicitConversionSequence ICS;
800 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
801}
802
803bool
804Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
805 AssignmentAction Action, bool AllowExplicit,
806 ImplicitConversionSequence& ICS) {
807 ICS = TryImplicitConversion(From, ToType,
808 /*SuppressUserConversions=*/false,
809 AllowExplicit,
810 /*InOverloadResolution=*/false);
811 return PerformImplicitConversion(From, ToType, ICS, Action);
812}
813
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000814/// \brief Determine whether the conversion from FromType to ToType is a valid
815/// conversion that strips "noreturn" off the nested function type.
816static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
817 QualType ToType, QualType &ResultTy) {
818 if (Context.hasSameUnqualifiedType(FromType, ToType))
819 return false;
820
821 // Strip the noreturn off the type we're converting from; noreturn can
822 // safely be removed.
823 FromType = Context.getNoReturnType(FromType, false);
824 if (!Context.hasSameUnqualifiedType(FromType, ToType))
825 return false;
826
827 ResultTy = FromType;
828 return true;
829}
Douglas Gregor46188682010-05-18 22:42:18 +0000830
831/// \brief Determine whether the conversion from FromType to ToType is a valid
832/// vector conversion.
833///
834/// \param ICK Will be set to the vector conversion kind, if this is a vector
835/// conversion.
836static bool IsVectorConversion(ASTContext &Context, QualType FromType,
837 QualType ToType, ImplicitConversionKind &ICK) {
838 // We need at least one of these types to be a vector type to have a vector
839 // conversion.
840 if (!ToType->isVectorType() && !FromType->isVectorType())
841 return false;
842
843 // Identical types require no conversions.
844 if (Context.hasSameUnqualifiedType(FromType, ToType))
845 return false;
846
847 // There are no conversions between extended vector types, only identity.
848 if (ToType->isExtVectorType()) {
849 // There are no conversions between extended vector types other than the
850 // identity conversion.
851 if (FromType->isExtVectorType())
852 return false;
853
854 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000855 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000856 ICK = ICK_Vector_Splat;
857 return true;
858 }
859 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000860
861 // We can perform the conversion between vector types in the following cases:
862 // 1)vector types are equivalent AltiVec and GCC vector types
863 // 2)lax vector conversions are permitted and the vector types are of the
864 // same size
865 if (ToType->isVectorType() && FromType->isVectorType()) {
866 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000867 (Context.getLangOptions().LaxVectorConversions &&
868 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000869 ICK = ICK_Vector_Conversion;
870 return true;
871 }
Douglas Gregor46188682010-05-18 22:42:18 +0000872 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000873
Douglas Gregor46188682010-05-18 22:42:18 +0000874 return false;
875}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000876
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000877/// IsStandardConversion - Determines whether there is a standard
878/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
879/// expression From to the type ToType. Standard conversion sequences
880/// only consider non-class types; for conversions that involve class
881/// types, use TryImplicitConversion. If a conversion exists, SCS will
882/// contain the standard conversion sequence required to perform this
883/// conversion and this routine will return true. Otherwise, this
884/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000885bool
886Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000887 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000888 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889 QualType FromType = From->getType();
890
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000891 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000892 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000893 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000894 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000895 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000896 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000897
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000898 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000899 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000900 if (FromType->isRecordType() || ToType->isRecordType()) {
901 if (getLangOptions().CPlusPlus)
902 return false;
903
Mike Stump11289f42009-09-09 15:08:12 +0000904 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000905 }
906
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000907 // The first conversion can be an lvalue-to-rvalue conversion,
908 // array-to-pointer conversion, or function-to-pointer conversion
909 // (C++ 4p1).
910
Douglas Gregor980fb162010-04-29 18:24:40 +0000911 if (FromType == Context.OverloadTy) {
912 DeclAccessPair AccessPair;
913 if (FunctionDecl *Fn
914 = ResolveAddressOfOverloadedFunction(From, ToType, false,
915 AccessPair)) {
916 // We were able to resolve the address of the overloaded function,
917 // so we can convert to the type of that function.
918 FromType = Fn->getType();
919 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
920 if (!Method->isStatic()) {
921 Type *ClassType
922 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
923 FromType = Context.getMemberPointerType(FromType, ClassType);
924 }
925 }
926
927 // If the "from" expression takes the address of the overloaded
928 // function, update the type of the resulting expression accordingly.
929 if (FromType->getAs<FunctionType>())
930 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
931 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
932 FromType = Context.getPointerType(FromType);
933
934 // Check that we've computed the proper type after overload resolution.
935 assert(Context.hasSameType(FromType,
936 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
937 } else {
938 return false;
939 }
940 }
Mike Stump11289f42009-09-09 15:08:12 +0000941 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942 // An lvalue (3.10) of a non-function, non-array type T can be
943 // converted to an rvalue.
944 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000945 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000946 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000947 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000948 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000949
950 // If T is a non-class type, the type of the rvalue is the
951 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000952 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
953 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000954 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000955 } else if (FromType->isArrayType()) {
956 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000957 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000958
959 // An lvalue or rvalue of type "array of N T" or "array of unknown
960 // bound of T" can be converted to an rvalue of type "pointer to
961 // T" (C++ 4.2p1).
962 FromType = Context.getArrayDecayedType(FromType);
963
964 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
965 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000966 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967
968 // For the purpose of ranking in overload resolution
969 // (13.3.3.1.1), this conversion is considered an
970 // array-to-pointer conversion followed by a qualification
971 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000972 SCS.Second = ICK_Identity;
973 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000974 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000975 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000976 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000977 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
978 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000979 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000980
981 // An lvalue of function type T can be converted to an rvalue of
982 // type "pointer to T." The result is a pointer to the
983 // function. (C++ 4.3p1).
984 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000985 } else {
986 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000987 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000988 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000989 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000990
991 // The second conversion can be an integral promotion, floating
992 // point promotion, integral conversion, floating point conversion,
993 // floating-integral conversion, pointer conversion,
994 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000995 // For overloading in C, this can also be a "compatible-type"
996 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000997 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000998 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000999 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001000 // The unqualified versions of the types are the same: there's no
1001 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001002 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +00001003 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001004 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001005 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001006 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001007 } else if (IsFloatingPointPromotion(FromType, ToType)) {
1008 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001009 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001010 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001011 } else if (IsComplexPromotion(FromType, ToType)) {
1012 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001013 SCS.Second = ICK_Complex_Promotion;
1014 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001015 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001016 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001017 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001018 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001019 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001020 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1021 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001022 SCS.Second = ICK_Complex_Conversion;
1023 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001024 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1025 (ToType->isComplexType() && FromType->isArithmeticType())) {
1026 // Complex-real conversions (C99 6.3.1.7)
1027 SCS.Second = ICK_Complex_Real;
1028 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001029 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001030 // Floating point conversions (C++ 4.8).
1031 SCS.Second = ICK_Floating_Conversion;
1032 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001033 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001034 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001035 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001036 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001037 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001038 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001039 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +00001040 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1041 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001042 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001043 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001044 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +00001045 } else if (IsMemberPointerConversion(From, FromType, ToType,
1046 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001047 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001048 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001049 } else if (ToType->isBooleanType() &&
1050 (FromType->isArithmeticType() ||
1051 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001052 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001053 FromType->isBlockPointerType() ||
1054 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001055 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001056 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001057 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001058 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001059 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1060 SCS.Second = SecondICK;
1061 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001062 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001063 Context.typesAreCompatible(ToType, FromType)) {
1064 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001065 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001066 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001067 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1068 // Treat a conversion that strips "noreturn" as an identity conversion.
1069 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001070 } else {
1071 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001072 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001074 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001075
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001076 QualType CanonFrom;
1077 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001078 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001079 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001080 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001081 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001082 CanonFrom = Context.getCanonicalType(FromType);
1083 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001084 } else {
1085 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001086 SCS.Third = ICK_Identity;
1087
Mike Stump11289f42009-09-09 15:08:12 +00001088 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001089 // [...] Any difference in top-level cv-qualification is
1090 // subsumed by the initialization itself and does not constitute
1091 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001092 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001093 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001094 if (CanonFrom.getLocalUnqualifiedType()
1095 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001096 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1097 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001098 FromType = ToType;
1099 CanonFrom = CanonTo;
1100 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001101 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001102 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103
1104 // If we have not converted the argument type to the parameter type,
1105 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001106 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001107 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001108
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001109 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110}
1111
1112/// IsIntegralPromotion - Determines whether the conversion from the
1113/// expression From (whose potentially-adjusted type is FromType) to
1114/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1115/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001116bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001117 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001118 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001119 if (!To) {
1120 return false;
1121 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122
1123 // An rvalue of type char, signed char, unsigned char, short int, or
1124 // unsigned short int can be converted to an rvalue of type int if
1125 // int can represent all the values of the source type; otherwise,
1126 // the source rvalue can be converted to an rvalue of type unsigned
1127 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001128 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1129 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130 if (// We can promote any signed, promotable integer type to an int
1131 (FromType->isSignedIntegerType() ||
1132 // We can promote any unsigned integer type whose size is
1133 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001134 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001135 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001136 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001137 }
1138
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001139 return To->getKind() == BuiltinType::UInt;
1140 }
1141
1142 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1143 // can be converted to an rvalue of the first of the following types
1144 // that can represent all the values of its underlying type: int,
1145 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001146
1147 // We pre-calculate the promotion type for enum types.
1148 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1149 if (ToType->isIntegerType())
1150 return Context.hasSameUnqualifiedType(ToType,
1151 FromEnumType->getDecl()->getPromotionType());
1152
1153 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001154 // Determine whether the type we're converting from is signed or
1155 // unsigned.
1156 bool FromIsSigned;
1157 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001158
1159 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1160 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001161
1162 // The types we'll try to promote to, in the appropriate
1163 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001164 QualType PromoteTypes[6] = {
1165 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001166 Context.LongTy, Context.UnsignedLongTy ,
1167 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001169 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1171 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001172 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001173 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1174 // We found the type that we can promote to. If this is the
1175 // type we wanted, we have a promotion. Otherwise, no
1176 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001177 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001178 }
1179 }
1180 }
1181
1182 // An rvalue for an integral bit-field (9.6) can be converted to an
1183 // rvalue of type int if int can represent all the values of the
1184 // bit-field; otherwise, it can be converted to unsigned int if
1185 // unsigned int can represent all the values of the bit-field. If
1186 // the bit-field is larger yet, no integral promotion applies to
1187 // it. If the bit-field has an enumerated type, it is treated as any
1188 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001189 // FIXME: We should delay checking of bit-fields until we actually perform the
1190 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001191 using llvm::APSInt;
1192 if (From)
1193 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001194 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001195 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001196 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1197 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1198 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001199
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001200 // Are we promoting to an int from a bitfield that fits in an int?
1201 if (BitWidth < ToSize ||
1202 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1203 return To->getKind() == BuiltinType::Int;
1204 }
Mike Stump11289f42009-09-09 15:08:12 +00001205
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001206 // Are we promoting to an unsigned int from an unsigned bitfield
1207 // that fits into an unsigned int?
1208 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1209 return To->getKind() == BuiltinType::UInt;
1210 }
Mike Stump11289f42009-09-09 15:08:12 +00001211
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001212 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001213 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001214 }
Mike Stump11289f42009-09-09 15:08:12 +00001215
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001216 // An rvalue of type bool can be converted to an rvalue of type int,
1217 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001218 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001219 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001220 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001221
1222 return false;
1223}
1224
1225/// IsFloatingPointPromotion - Determines whether the conversion from
1226/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1227/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001228bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229 /// An rvalue of type float can be converted to an rvalue of type
1230 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001231 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1232 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001233 if (FromBuiltin->getKind() == BuiltinType::Float &&
1234 ToBuiltin->getKind() == BuiltinType::Double)
1235 return true;
1236
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001237 // C99 6.3.1.5p1:
1238 // When a float is promoted to double or long double, or a
1239 // double is promoted to long double [...].
1240 if (!getLangOptions().CPlusPlus &&
1241 (FromBuiltin->getKind() == BuiltinType::Float ||
1242 FromBuiltin->getKind() == BuiltinType::Double) &&
1243 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1244 return true;
1245 }
1246
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001247 return false;
1248}
1249
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001250/// \brief Determine if a conversion is a complex promotion.
1251///
1252/// A complex promotion is defined as a complex -> complex conversion
1253/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001254/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001255bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001256 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001257 if (!FromComplex)
1258 return false;
1259
John McCall9dd450b2009-09-21 23:43:11 +00001260 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001261 if (!ToComplex)
1262 return false;
1263
1264 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001265 ToComplex->getElementType()) ||
1266 IsIntegralPromotion(0, FromComplex->getElementType(),
1267 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001268}
1269
Douglas Gregor237f96c2008-11-26 23:31:11 +00001270/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1271/// the pointer type FromPtr to a pointer to type ToPointee, with the
1272/// same type qualifiers as FromPtr has on its pointee type. ToType,
1273/// if non-empty, will be a pointer to ToType that may or may not have
1274/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001275static QualType
1276BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001277 QualType ToPointee, QualType ToType,
1278 ASTContext &Context) {
1279 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1280 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001281 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001282
1283 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001284 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001285 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001286 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001287 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001288
1289 // Build a pointer to ToPointee. It has the right qualifiers
1290 // already.
1291 return Context.getPointerType(ToPointee);
1292 }
1293
1294 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001295 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001296 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1297 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001298}
1299
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001300/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1301/// the FromType, which is an objective-c pointer, to ToType, which may or may
1302/// not have the right set of qualifiers.
1303static QualType
1304BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1305 QualType ToType,
1306 ASTContext &Context) {
1307 QualType CanonFromType = Context.getCanonicalType(FromType);
1308 QualType CanonToType = Context.getCanonicalType(ToType);
1309 Qualifiers Quals = CanonFromType.getQualifiers();
1310
1311 // Exact qualifier match -> return the pointer type we're converting to.
1312 if (CanonToType.getLocalQualifiers() == Quals)
1313 return ToType;
1314
1315 // Just build a canonical type that has the right qualifiers.
1316 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1317}
1318
Mike Stump11289f42009-09-09 15:08:12 +00001319static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001320 bool InOverloadResolution,
1321 ASTContext &Context) {
1322 // Handle value-dependent integral null pointer constants correctly.
1323 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1324 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001325 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001326 return !InOverloadResolution;
1327
Douglas Gregor56751b52009-09-25 04:25:58 +00001328 return Expr->isNullPointerConstant(Context,
1329 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1330 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001331}
Mike Stump11289f42009-09-09 15:08:12 +00001332
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333/// IsPointerConversion - Determines whether the conversion of the
1334/// expression From, which has the (possibly adjusted) type FromType,
1335/// can be converted to the type ToType via a pointer conversion (C++
1336/// 4.10). If so, returns true and places the converted type (that
1337/// might differ from ToType in its cv-qualifiers at some level) into
1338/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001339///
Douglas Gregora29dc052008-11-27 01:19:21 +00001340/// This routine also supports conversions to and from block pointers
1341/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1342/// pointers to interfaces. FIXME: Once we've determined the
1343/// appropriate overloading rules for Objective-C, we may want to
1344/// split the Objective-C checks into a different routine; however,
1345/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001346/// conversions, so for now they live here. IncompatibleObjC will be
1347/// set if the conversion is an allowed Objective-C conversion that
1348/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001350 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001351 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001352 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001353 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001354 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1355 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001356
Mike Stump11289f42009-09-09 15:08:12 +00001357 // Conversion from a null pointer constant to any Objective-C pointer type.
1358 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001359 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001360 ConvertedType = ToType;
1361 return true;
1362 }
1363
Douglas Gregor231d1c62008-11-27 00:15:41 +00001364 // Blocks: Block pointers can be converted to void*.
1365 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001367 ConvertedType = ToType;
1368 return true;
1369 }
1370 // Blocks: A null pointer constant can be converted to a block
1371 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001372 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001373 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001374 ConvertedType = ToType;
1375 return true;
1376 }
1377
Sebastian Redl576fd422009-05-10 18:38:11 +00001378 // If the left-hand-side is nullptr_t, the right side can be a null
1379 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001380 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001381 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001382 ConvertedType = ToType;
1383 return true;
1384 }
1385
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001386 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001387 if (!ToTypePtr)
1388 return false;
1389
1390 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001391 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001392 ConvertedType = ToType;
1393 return true;
1394 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001395
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001396 // Beyond this point, both types need to be pointers
1397 // , including objective-c pointers.
1398 QualType ToPointeeType = ToTypePtr->getPointeeType();
1399 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1400 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1401 ToType, Context);
1402 return true;
1403
1404 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001405 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001406 if (!FromTypePtr)
1407 return false;
1408
1409 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001410
Douglas Gregorfb640862010-08-18 21:25:30 +00001411 // If the unqualified pointee types are the same, this can't be a
1412 // pointer conversion, so don't do all of the work below.
1413 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1414 return false;
1415
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001416 // An rvalue of type "pointer to cv T," where T is an object type,
1417 // can be converted to an rvalue of type "pointer to cv void" (C++
1418 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001419 if (FromPointeeType->isIncompleteOrObjectType() &&
1420 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001421 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001422 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001423 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424 return true;
1425 }
1426
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001427 // When we're overloading in C, we allow a special kind of pointer
1428 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001429 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001430 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001431 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001432 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001433 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001434 return true;
1435 }
1436
Douglas Gregor5c407d92008-10-23 00:40:37 +00001437 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001438 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001439 // An rvalue of type "pointer to cv D," where D is a class type,
1440 // can be converted to an rvalue of type "pointer to cv B," where
1441 // B is a base class (clause 10) of D. If B is an inaccessible
1442 // (clause 11) or ambiguous (10.2) base class of D, a program that
1443 // necessitates this conversion is ill-formed. The result of the
1444 // conversion is a pointer to the base class sub-object of the
1445 // derived class object. The null pointer value is converted to
1446 // the null pointer value of the destination type.
1447 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001448 // Note that we do not check for ambiguity or inaccessibility
1449 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001450 if (getLangOptions().CPlusPlus &&
1451 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001452 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001453 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001454 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001455 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001456 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001457 ToType, Context);
1458 return true;
1459 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001460
Douglas Gregora119f102008-12-19 19:13:09 +00001461 return false;
1462}
1463
1464/// isObjCPointerConversion - Determines whether this is an
1465/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1466/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001467bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001468 QualType& ConvertedType,
1469 bool &IncompatibleObjC) {
1470 if (!getLangOptions().ObjC1)
1471 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001472
Steve Naroff7cae42b2009-07-10 23:34:53 +00001473 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001474 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001475 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001476 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001477
Steve Naroff7cae42b2009-07-10 23:34:53 +00001478 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001479 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001480 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001481 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001482 ConvertedType = ToType;
1483 return true;
1484 }
1485 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001486 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001487 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001488 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001489 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001490 ConvertedType = ToType;
1491 return true;
1492 }
1493 // Objective C++: We're able to convert from a pointer to an
1494 // interface to a pointer to a different interface.
1495 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001496 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1497 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1498 if (getLangOptions().CPlusPlus && LHS && RHS &&
1499 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1500 FromObjCPtr->getPointeeType()))
1501 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001502 ConvertedType = ToType;
1503 return true;
1504 }
1505
1506 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1507 // Okay: this is some kind of implicit downcast of Objective-C
1508 // interfaces, which is permitted. However, we're going to
1509 // complain about it.
1510 IncompatibleObjC = true;
1511 ConvertedType = FromType;
1512 return true;
1513 }
Mike Stump11289f42009-09-09 15:08:12 +00001514 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001515 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001516 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001517 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001518 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001519 else if (const BlockPointerType *ToBlockPtr =
1520 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001521 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001522 // to a block pointer type.
1523 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1524 ConvertedType = ToType;
1525 return true;
1526 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001527 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001528 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001529 else if (FromType->getAs<BlockPointerType>() &&
1530 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1531 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001532 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001533 ConvertedType = ToType;
1534 return true;
1535 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001536 else
Douglas Gregora119f102008-12-19 19:13:09 +00001537 return false;
1538
Douglas Gregor033f56d2008-12-23 00:53:59 +00001539 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001540 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001541 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001542 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001543 FromPointeeType = FromBlockPtr->getPointeeType();
1544 else
Douglas Gregora119f102008-12-19 19:13:09 +00001545 return false;
1546
Douglas Gregora119f102008-12-19 19:13:09 +00001547 // If we have pointers to pointers, recursively check whether this
1548 // is an Objective-C conversion.
1549 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1550 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1551 IncompatibleObjC)) {
1552 // We always complain about this conversion.
1553 IncompatibleObjC = true;
1554 ConvertedType = ToType;
1555 return true;
1556 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001557 // Allow conversion of pointee being objective-c pointer to another one;
1558 // as in I* to id.
1559 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1560 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1561 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1562 IncompatibleObjC)) {
1563 ConvertedType = ToType;
1564 return true;
1565 }
1566
Douglas Gregor033f56d2008-12-23 00:53:59 +00001567 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001568 // differences in the argument and result types are in Objective-C
1569 // pointer conversions. If so, we permit the conversion (but
1570 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001571 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001572 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001573 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001574 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001575 if (FromFunctionType && ToFunctionType) {
1576 // If the function types are exactly the same, this isn't an
1577 // Objective-C pointer conversion.
1578 if (Context.getCanonicalType(FromPointeeType)
1579 == Context.getCanonicalType(ToPointeeType))
1580 return false;
1581
1582 // Perform the quick checks that will tell us whether these
1583 // function types are obviously different.
1584 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1585 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1586 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1587 return false;
1588
1589 bool HasObjCConversion = false;
1590 if (Context.getCanonicalType(FromFunctionType->getResultType())
1591 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1592 // Okay, the types match exactly. Nothing to do.
1593 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1594 ToFunctionType->getResultType(),
1595 ConvertedType, IncompatibleObjC)) {
1596 // Okay, we have an Objective-C pointer conversion.
1597 HasObjCConversion = true;
1598 } else {
1599 // Function types are too different. Abort.
1600 return false;
1601 }
Mike Stump11289f42009-09-09 15:08:12 +00001602
Douglas Gregora119f102008-12-19 19:13:09 +00001603 // Check argument types.
1604 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1605 ArgIdx != NumArgs; ++ArgIdx) {
1606 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1607 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1608 if (Context.getCanonicalType(FromArgType)
1609 == Context.getCanonicalType(ToArgType)) {
1610 // Okay, the types match exactly. Nothing to do.
1611 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1612 ConvertedType, IncompatibleObjC)) {
1613 // Okay, we have an Objective-C pointer conversion.
1614 HasObjCConversion = true;
1615 } else {
1616 // Argument types are too different. Abort.
1617 return false;
1618 }
1619 }
1620
1621 if (HasObjCConversion) {
1622 // We had an Objective-C conversion. Allow this pointer
1623 // conversion, but complain about it.
1624 ConvertedType = ToType;
1625 IncompatibleObjC = true;
1626 return true;
1627 }
1628 }
1629
Sebastian Redl72b597d2009-01-25 19:43:20 +00001630 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001631}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001632
1633/// FunctionArgTypesAreEqual - This routine checks two function proto types
1634/// for equlity of their argument types. Caller has already checked that
1635/// they have same number of arguments. This routine assumes that Objective-C
1636/// pointer types which only differ in their protocol qualifiers are equal.
1637bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1638 FunctionProtoType* NewType){
1639 if (!getLangOptions().ObjC1)
1640 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1641 NewType->arg_type_begin());
1642
1643 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1644 N = NewType->arg_type_begin(),
1645 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1646 QualType ToType = (*O);
1647 QualType FromType = (*N);
1648 if (ToType != FromType) {
1649 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1650 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001651 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1652 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1653 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1654 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001655 continue;
1656 }
John McCall8b07ec22010-05-15 11:32:37 +00001657 else if (const ObjCObjectPointerType *PTTo =
1658 ToType->getAs<ObjCObjectPointerType>()) {
1659 if (const ObjCObjectPointerType *PTFr =
1660 FromType->getAs<ObjCObjectPointerType>())
1661 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1662 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001663 }
1664 return false;
1665 }
1666 }
1667 return true;
1668}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669
Douglas Gregor39c16d42008-10-24 04:54:22 +00001670/// CheckPointerConversion - Check the pointer conversion from the
1671/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001672/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001673/// conversions for which IsPointerConversion has already returned
1674/// true. It returns true and produces a diagnostic if there was an
1675/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001676bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001677 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001678 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001679 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001680 QualType FromType = From->getType();
1681
Douglas Gregor4038cf42010-06-08 17:35:15 +00001682 if (CXXBoolLiteralExpr* LitBool
1683 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1684 if (LitBool->getValue() == false)
1685 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1686 << ToType;
1687
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001688 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1689 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001690 QualType FromPointeeType = FromPtrType->getPointeeType(),
1691 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001692
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001693 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1694 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001695 // We must have a derived-to-base conversion. Check an
1696 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001697 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1698 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001699 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001700 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001701 return true;
1702
1703 // The conversion was successful.
1704 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001705 }
1706 }
Mike Stump11289f42009-09-09 15:08:12 +00001707 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001708 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001709 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001710 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001711 // Objective-C++ conversions are always okay.
1712 // FIXME: We should have a different class of conversions for the
1713 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001714 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001715 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001716
Steve Naroff7cae42b2009-07-10 23:34:53 +00001717 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001718 return false;
1719}
1720
Sebastian Redl72b597d2009-01-25 19:43:20 +00001721/// IsMemberPointerConversion - Determines whether the conversion of the
1722/// expression From, which has the (possibly adjusted) type FromType, can be
1723/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1724/// If so, returns true and places the converted type (that might differ from
1725/// ToType in its cv-qualifiers at some level) into ConvertedType.
1726bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001727 QualType ToType,
1728 bool InOverloadResolution,
1729 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001730 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001731 if (!ToTypePtr)
1732 return false;
1733
1734 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001735 if (From->isNullPointerConstant(Context,
1736 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1737 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001738 ConvertedType = ToType;
1739 return true;
1740 }
1741
1742 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001743 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001744 if (!FromTypePtr)
1745 return false;
1746
1747 // A pointer to member of B can be converted to a pointer to member of D,
1748 // where D is derived from B (C++ 4.11p2).
1749 QualType FromClass(FromTypePtr->getClass(), 0);
1750 QualType ToClass(ToTypePtr->getClass(), 0);
1751 // FIXME: What happens when these are dependent? Is this function even called?
1752
1753 if (IsDerivedFrom(ToClass, FromClass)) {
1754 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1755 ToClass.getTypePtr());
1756 return true;
1757 }
1758
1759 return false;
1760}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001761
Sebastian Redl72b597d2009-01-25 19:43:20 +00001762/// CheckMemberPointerConversion - Check the member pointer conversion from the
1763/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001764/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001765/// for which IsMemberPointerConversion has already returned true. It returns
1766/// true and produces a diagnostic if there was an error, or returns false
1767/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001768bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001769 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001770 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001771 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001772 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001773 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001774 if (!FromPtrType) {
1775 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001776 assert(From->isNullPointerConstant(Context,
1777 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001778 "Expr must be null pointer constant!");
1779 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001780 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001781 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001782
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001783 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001784 assert(ToPtrType && "No member pointer cast has a target type "
1785 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001786
Sebastian Redled8f2002009-01-28 18:33:18 +00001787 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1788 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001789
Sebastian Redled8f2002009-01-28 18:33:18 +00001790 // FIXME: What about dependent types?
1791 assert(FromClass->isRecordType() && "Pointer into non-class.");
1792 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001793
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001794 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001795 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001796 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1797 assert(DerivationOkay &&
1798 "Should not have been called if derivation isn't OK.");
1799 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001800
Sebastian Redled8f2002009-01-28 18:33:18 +00001801 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1802 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001803 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1804 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1805 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1806 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001807 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001808
Douglas Gregor89ee6822009-02-28 01:32:25 +00001809 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001810 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1811 << FromClass << ToClass << QualType(VBase, 0)
1812 << From->getSourceRange();
1813 return true;
1814 }
1815
John McCall5b0829a2010-02-10 09:31:12 +00001816 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001817 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1818 Paths.front(),
1819 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001820
Anders Carlssond7923c62009-08-22 23:33:40 +00001821 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001822 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001823 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001824 return false;
1825}
1826
Douglas Gregor9a657932008-10-21 23:43:52 +00001827/// IsQualificationConversion - Determines whether the conversion from
1828/// an rvalue of type FromType to ToType is a qualification conversion
1829/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001830bool
1831Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001832 FromType = Context.getCanonicalType(FromType);
1833 ToType = Context.getCanonicalType(ToType);
1834
1835 // If FromType and ToType are the same type, this is not a
1836 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001837 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001838 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001839
Douglas Gregor9a657932008-10-21 23:43:52 +00001840 // (C++ 4.4p4):
1841 // A conversion can add cv-qualifiers at levels other than the first
1842 // in multi-level pointers, subject to the following rules: [...]
1843 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001844 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001845 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001846 // Within each iteration of the loop, we check the qualifiers to
1847 // determine if this still looks like a qualification
1848 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001849 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001850 // until there are no more pointers or pointers-to-members left to
1851 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001852 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001853
1854 // -- for every j > 0, if const is in cv 1,j then const is in cv
1855 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001856 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001857 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001858
Douglas Gregor9a657932008-10-21 23:43:52 +00001859 // -- if the cv 1,j and cv 2,j are different, then const is in
1860 // every cv for 0 < k < j.
1861 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001862 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001863 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001864
Douglas Gregor9a657932008-10-21 23:43:52 +00001865 // Keep track of whether all prior cv-qualifiers in the "to" type
1866 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001867 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001868 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001869 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001870
1871 // We are left with FromType and ToType being the pointee types
1872 // after unwrapping the original FromType and ToType the same number
1873 // of types. If we unwrapped any pointers, and if FromType and
1874 // ToType have the same unqualified type (since we checked
1875 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001876 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001877}
1878
Douglas Gregor576e98c2009-01-30 23:27:23 +00001879/// Determines whether there is a user-defined conversion sequence
1880/// (C++ [over.ics.user]) that converts expression From to the type
1881/// ToType. If such a conversion exists, User will contain the
1882/// user-defined conversion sequence that performs such a conversion
1883/// and this routine will return true. Otherwise, this routine returns
1884/// false and User is unspecified.
1885///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001886/// \param AllowExplicit true if the conversion should consider C++0x
1887/// "explicit" conversion functions as well as non-explicit conversion
1888/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001889OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1890 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001891 OverloadCandidateSet& CandidateSet,
1892 bool AllowExplicit) {
1893 // Whether we will only visit constructors.
1894 bool ConstructorsOnly = false;
1895
1896 // If the type we are conversion to is a class type, enumerate its
1897 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001898 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001899 // C++ [over.match.ctor]p1:
1900 // When objects of class type are direct-initialized (8.5), or
1901 // copy-initialized from an expression of the same or a
1902 // derived class type (8.5), overload resolution selects the
1903 // constructor. [...] For copy-initialization, the candidate
1904 // functions are all the converting constructors (12.3.1) of
1905 // that class. The argument list is the expression-list within
1906 // the parentheses of the initializer.
1907 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1908 (From->getType()->getAs<RecordType>() &&
1909 IsDerivedFrom(From->getType(), ToType)))
1910 ConstructorsOnly = true;
1911
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001912 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1913 // We're not going to find any constructors.
1914 } else if (CXXRecordDecl *ToRecordDecl
1915 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001916 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00001917 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001918 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001919 NamedDecl *D = *Con;
1920 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1921
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001922 // Find the constructor (which may be a template).
1923 CXXConstructorDecl *Constructor = 0;
1924 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001925 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001926 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001927 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001928 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1929 else
John McCalla0296f72010-03-19 07:35:19 +00001930 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001931
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001932 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001933 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001934 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001935 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001936 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001937 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001938 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001939 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001940 // Allow one user-defined conversion when user specifies a
1941 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001942 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001943 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001944 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001945 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001946 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001947 }
1948 }
1949
Douglas Gregor5ab11652010-04-17 22:01:05 +00001950 // Enumerate conversion functions, if we're allowed to.
1951 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001952 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001953 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001954 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001955 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001956 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001957 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001958 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1959 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001960 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001961 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001962 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001963 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001964 DeclAccessPair FoundDecl = I.getPair();
1965 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001966 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1967 if (isa<UsingShadowDecl>(D))
1968 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1969
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001970 CXXConversionDecl *Conv;
1971 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001972 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1973 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001974 else
John McCallda4458e2010-03-31 01:36:47 +00001975 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001976
1977 if (AllowExplicit || !Conv->isExplicit()) {
1978 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001979 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001980 ActingContext, From, ToType,
1981 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001982 else
John McCalla0296f72010-03-19 07:35:19 +00001983 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001984 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001985 }
1986 }
1987 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001988 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001989
1990 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001991 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001992 case OR_Success:
1993 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001994 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001995 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1996 // C++ [over.ics.user]p1:
1997 // If the user-defined conversion is specified by a
1998 // constructor (12.3.1), the initial standard conversion
1999 // sequence converts the source type to the type required by
2000 // the argument of the constructor.
2001 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002002 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00002003 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00002004 User.EllipsisConversion = true;
2005 else {
2006 User.Before = Best->Conversions[0].Standard;
2007 User.EllipsisConversion = false;
2008 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002009 User.ConversionFunction = Constructor;
2010 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002011 User.After.setFromType(
2012 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002013 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002014 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002015 } else if (CXXConversionDecl *Conversion
2016 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2017 // C++ [over.ics.user]p1:
2018 //
2019 // [...] If the user-defined conversion is specified by a
2020 // conversion function (12.3.2), the initial standard
2021 // conversion sequence converts the source type to the
2022 // implicit object parameter of the conversion function.
2023 User.Before = Best->Conversions[0].Standard;
2024 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002025 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002026
2027 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002028 // The second standard conversion sequence converts the
2029 // result of the user-defined conversion to the target type
2030 // for the sequence. Since an implicit conversion sequence
2031 // is an initialization, the special rules for
2032 // initialization by user-defined conversion apply when
2033 // selecting the best user-defined conversion for a
2034 // user-defined conversion sequence (see 13.3.3 and
2035 // 13.3.3.1).
2036 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002037 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002038 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002039 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002040 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002043 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002044 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002045 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002046 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002047 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002048
2049 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002050 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002051 }
2052
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002053 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002054}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002055
2056bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002057Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002058 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002059 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002060 OverloadingResult OvResult =
2061 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002062 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002063 if (OvResult == OR_Ambiguous)
2064 Diag(From->getSourceRange().getBegin(),
2065 diag::err_typecheck_ambiguous_condition)
2066 << From->getType() << ToType << From->getSourceRange();
2067 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2068 Diag(From->getSourceRange().getBegin(),
2069 diag::err_typecheck_nonviable_condition)
2070 << From->getType() << ToType << From->getSourceRange();
2071 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002072 return false;
John McCallad907772010-01-12 07:18:19 +00002073 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002074 return true;
2075}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002076
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002077/// CompareImplicitConversionSequences - Compare two implicit
2078/// conversion sequences to determine whether one is better than the
2079/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002080ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002081Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2082 const ImplicitConversionSequence& ICS2)
2083{
2084 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2085 // conversion sequences (as defined in 13.3.3.1)
2086 // -- a standard conversion sequence (13.3.3.1.1) is a better
2087 // conversion sequence than a user-defined conversion sequence or
2088 // an ellipsis conversion sequence, and
2089 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2090 // conversion sequence than an ellipsis conversion sequence
2091 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002092 //
John McCall0d1da222010-01-12 00:44:57 +00002093 // C++0x [over.best.ics]p10:
2094 // For the purpose of ranking implicit conversion sequences as
2095 // described in 13.3.3.2, the ambiguous conversion sequence is
2096 // treated as a user-defined sequence that is indistinguishable
2097 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002098 if (ICS1.getKindRank() < ICS2.getKindRank())
2099 return ImplicitConversionSequence::Better;
2100 else if (ICS2.getKindRank() < ICS1.getKindRank())
2101 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002102
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002103 // The following checks require both conversion sequences to be of
2104 // the same kind.
2105 if (ICS1.getKind() != ICS2.getKind())
2106 return ImplicitConversionSequence::Indistinguishable;
2107
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002108 // Two implicit conversion sequences of the same form are
2109 // indistinguishable conversion sequences unless one of the
2110 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002111 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002112 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002113 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002114 // User-defined conversion sequence U1 is a better conversion
2115 // sequence than another user-defined conversion sequence U2 if
2116 // they contain the same user-defined conversion function or
2117 // constructor and if the second standard conversion sequence of
2118 // U1 is better than the second standard conversion sequence of
2119 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002120 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002121 ICS2.UserDefined.ConversionFunction)
2122 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2123 ICS2.UserDefined.After);
2124 }
2125
2126 return ImplicitConversionSequence::Indistinguishable;
2127}
2128
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002129static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2130 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2131 Qualifiers Quals;
2132 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2133 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2134 }
2135
2136 return Context.hasSameUnqualifiedType(T1, T2);
2137}
2138
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002139// Per 13.3.3.2p3, compare the given standard conversion sequences to
2140// determine if one is a proper subset of the other.
2141static ImplicitConversionSequence::CompareKind
2142compareStandardConversionSubsets(ASTContext &Context,
2143 const StandardConversionSequence& SCS1,
2144 const StandardConversionSequence& SCS2) {
2145 ImplicitConversionSequence::CompareKind Result
2146 = ImplicitConversionSequence::Indistinguishable;
2147
Douglas Gregore87561a2010-05-23 22:10:15 +00002148 // the identity conversion sequence is considered to be a subsequence of
2149 // any non-identity conversion sequence
2150 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2151 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2152 return ImplicitConversionSequence::Better;
2153 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2154 return ImplicitConversionSequence::Worse;
2155 }
2156
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002157 if (SCS1.Second != SCS2.Second) {
2158 if (SCS1.Second == ICK_Identity)
2159 Result = ImplicitConversionSequence::Better;
2160 else if (SCS2.Second == ICK_Identity)
2161 Result = ImplicitConversionSequence::Worse;
2162 else
2163 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002164 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002165 return ImplicitConversionSequence::Indistinguishable;
2166
2167 if (SCS1.Third == SCS2.Third) {
2168 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2169 : ImplicitConversionSequence::Indistinguishable;
2170 }
2171
2172 if (SCS1.Third == ICK_Identity)
2173 return Result == ImplicitConversionSequence::Worse
2174 ? ImplicitConversionSequence::Indistinguishable
2175 : ImplicitConversionSequence::Better;
2176
2177 if (SCS2.Third == ICK_Identity)
2178 return Result == ImplicitConversionSequence::Better
2179 ? ImplicitConversionSequence::Indistinguishable
2180 : ImplicitConversionSequence::Worse;
2181
2182 return ImplicitConversionSequence::Indistinguishable;
2183}
2184
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002185/// CompareStandardConversionSequences - Compare two standard
2186/// conversion sequences to determine whether one is better than the
2187/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002188ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002189Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2190 const StandardConversionSequence& SCS2)
2191{
2192 // Standard conversion sequence S1 is a better conversion sequence
2193 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2194
2195 // -- S1 is a proper subsequence of S2 (comparing the conversion
2196 // sequences in the canonical form defined by 13.3.3.1.1,
2197 // excluding any Lvalue Transformation; the identity conversion
2198 // sequence is considered to be a subsequence of any
2199 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002200 if (ImplicitConversionSequence::CompareKind CK
2201 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2202 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002203
2204 // -- the rank of S1 is better than the rank of S2 (by the rules
2205 // defined below), or, if not that,
2206 ImplicitConversionRank Rank1 = SCS1.getRank();
2207 ImplicitConversionRank Rank2 = SCS2.getRank();
2208 if (Rank1 < Rank2)
2209 return ImplicitConversionSequence::Better;
2210 else if (Rank2 < Rank1)
2211 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002212
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002213 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2214 // are indistinguishable unless one of the following rules
2215 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002216
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002217 // A conversion that is not a conversion of a pointer, or
2218 // pointer to member, to bool is better than another conversion
2219 // that is such a conversion.
2220 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2221 return SCS2.isPointerConversionToBool()
2222 ? ImplicitConversionSequence::Better
2223 : ImplicitConversionSequence::Worse;
2224
Douglas Gregor5c407d92008-10-23 00:40:37 +00002225 // C++ [over.ics.rank]p4b2:
2226 //
2227 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002228 // conversion of B* to A* is better than conversion of B* to
2229 // void*, and conversion of A* to void* is better than conversion
2230 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002231 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002232 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002233 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002234 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002235 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2236 // Exactly one of the conversion sequences is a conversion to
2237 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002238 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2239 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002240 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2241 // Neither conversion sequence converts to a void pointer; compare
2242 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002243 if (ImplicitConversionSequence::CompareKind DerivedCK
2244 = CompareDerivedToBaseConversions(SCS1, SCS2))
2245 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002246 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2247 // Both conversion sequences are conversions to void
2248 // pointers. Compare the source types to determine if there's an
2249 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002250 QualType FromType1 = SCS1.getFromType();
2251 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002252
2253 // Adjust the types we're converting from via the array-to-pointer
2254 // conversion, if we need to.
2255 if (SCS1.First == ICK_Array_To_Pointer)
2256 FromType1 = Context.getArrayDecayedType(FromType1);
2257 if (SCS2.First == ICK_Array_To_Pointer)
2258 FromType2 = Context.getArrayDecayedType(FromType2);
2259
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002260 QualType FromPointee1
2261 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2262 QualType FromPointee2
2263 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002264
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002265 if (IsDerivedFrom(FromPointee2, FromPointee1))
2266 return ImplicitConversionSequence::Better;
2267 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2268 return ImplicitConversionSequence::Worse;
2269
2270 // Objective-C++: If one interface is more specific than the
2271 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002272 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2273 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002274 if (FromIface1 && FromIface1) {
2275 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2276 return ImplicitConversionSequence::Better;
2277 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2278 return ImplicitConversionSequence::Worse;
2279 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002280 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002281
2282 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2283 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002284 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002285 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002286 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002287
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002288 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002289 // C++0x [over.ics.rank]p3b4:
2290 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2291 // implicit object parameter of a non-static member function declared
2292 // without a ref-qualifier, and S1 binds an rvalue reference to an
2293 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002294 // FIXME: We don't know if we're dealing with the implicit object parameter,
2295 // or if the member function in this case has a ref qualifier.
2296 // (Of course, we don't have ref qualifiers yet.)
2297 if (SCS1.RRefBinding != SCS2.RRefBinding)
2298 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2299 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002300
2301 // C++ [over.ics.rank]p3b4:
2302 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2303 // which the references refer are the same type except for
2304 // top-level cv-qualifiers, and the type to which the reference
2305 // initialized by S2 refers is more cv-qualified than the type
2306 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002307 QualType T1 = SCS1.getToType(2);
2308 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002309 T1 = Context.getCanonicalType(T1);
2310 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002311 Qualifiers T1Quals, T2Quals;
2312 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2313 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2314 if (UnqualT1 == UnqualT2) {
2315 // If the type is an array type, promote the element qualifiers to the type
2316 // for comparison.
2317 if (isa<ArrayType>(T1) && T1Quals)
2318 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2319 if (isa<ArrayType>(T2) && T2Quals)
2320 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002321 if (T2.isMoreQualifiedThan(T1))
2322 return ImplicitConversionSequence::Better;
2323 else if (T1.isMoreQualifiedThan(T2))
2324 return ImplicitConversionSequence::Worse;
2325 }
2326 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002327
2328 return ImplicitConversionSequence::Indistinguishable;
2329}
2330
2331/// CompareQualificationConversions - Compares two standard conversion
2332/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002333/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2334ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002335Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002336 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002337 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002338 // -- S1 and S2 differ only in their qualification conversion and
2339 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2340 // cv-qualification signature of type T1 is a proper subset of
2341 // the cv-qualification signature of type T2, and S1 is not the
2342 // deprecated string literal array-to-pointer conversion (4.2).
2343 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2344 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2345 return ImplicitConversionSequence::Indistinguishable;
2346
2347 // FIXME: the example in the standard doesn't use a qualification
2348 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002349 QualType T1 = SCS1.getToType(2);
2350 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002351 T1 = Context.getCanonicalType(T1);
2352 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002353 Qualifiers T1Quals, T2Quals;
2354 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2355 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002356
2357 // If the types are the same, we won't learn anything by unwrapped
2358 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002359 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002360 return ImplicitConversionSequence::Indistinguishable;
2361
Chandler Carruth607f38e2009-12-29 07:16:59 +00002362 // If the type is an array type, promote the element qualifiers to the type
2363 // for comparison.
2364 if (isa<ArrayType>(T1) && T1Quals)
2365 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2366 if (isa<ArrayType>(T2) && T2Quals)
2367 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2368
Mike Stump11289f42009-09-09 15:08:12 +00002369 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002370 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002371 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002372 // Within each iteration of the loop, we check the qualifiers to
2373 // determine if this still looks like a qualification
2374 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002375 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002376 // until there are no more pointers or pointers-to-members left
2377 // to unwrap. This essentially mimics what
2378 // IsQualificationConversion does, but here we're checking for a
2379 // strict subset of qualifiers.
2380 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2381 // The qualifiers are the same, so this doesn't tell us anything
2382 // about how the sequences rank.
2383 ;
2384 else if (T2.isMoreQualifiedThan(T1)) {
2385 // T1 has fewer qualifiers, so it could be the better sequence.
2386 if (Result == ImplicitConversionSequence::Worse)
2387 // Neither has qualifiers that are a subset of the other's
2388 // qualifiers.
2389 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002390
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002391 Result = ImplicitConversionSequence::Better;
2392 } else if (T1.isMoreQualifiedThan(T2)) {
2393 // T2 has fewer qualifiers, so it could be the better sequence.
2394 if (Result == ImplicitConversionSequence::Better)
2395 // Neither has qualifiers that are a subset of the other's
2396 // qualifiers.
2397 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002398
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002399 Result = ImplicitConversionSequence::Worse;
2400 } else {
2401 // Qualifiers are disjoint.
2402 return ImplicitConversionSequence::Indistinguishable;
2403 }
2404
2405 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002406 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002407 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002408 }
2409
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002410 // Check that the winning standard conversion sequence isn't using
2411 // the deprecated string literal array to pointer conversion.
2412 switch (Result) {
2413 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002414 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002415 Result = ImplicitConversionSequence::Indistinguishable;
2416 break;
2417
2418 case ImplicitConversionSequence::Indistinguishable:
2419 break;
2420
2421 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002422 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002423 Result = ImplicitConversionSequence::Indistinguishable;
2424 break;
2425 }
2426
2427 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002428}
2429
Douglas Gregor5c407d92008-10-23 00:40:37 +00002430/// CompareDerivedToBaseConversions - Compares two standard conversion
2431/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002432/// various kinds of derived-to-base conversions (C++
2433/// [over.ics.rank]p4b3). As part of these checks, we also look at
2434/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002435ImplicitConversionSequence::CompareKind
2436Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2437 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002438 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002439 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002440 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002441 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002442
2443 // Adjust the types we're converting from via the array-to-pointer
2444 // conversion, if we need to.
2445 if (SCS1.First == ICK_Array_To_Pointer)
2446 FromType1 = Context.getArrayDecayedType(FromType1);
2447 if (SCS2.First == ICK_Array_To_Pointer)
2448 FromType2 = Context.getArrayDecayedType(FromType2);
2449
2450 // Canonicalize all of the types.
2451 FromType1 = Context.getCanonicalType(FromType1);
2452 ToType1 = Context.getCanonicalType(ToType1);
2453 FromType2 = Context.getCanonicalType(FromType2);
2454 ToType2 = Context.getCanonicalType(ToType2);
2455
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002456 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002457 //
2458 // If class B is derived directly or indirectly from class A and
2459 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002460 //
2461 // For Objective-C, we let A, B, and C also be Objective-C
2462 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002463
2464 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002465 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002466 SCS2.Second == ICK_Pointer_Conversion &&
2467 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2468 FromType1->isPointerType() && FromType2->isPointerType() &&
2469 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002470 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002471 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002472 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002473 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002474 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002475 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002476 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002477 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002478
John McCall8b07ec22010-05-15 11:32:37 +00002479 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2480 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2481 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2482 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002483
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002484 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002485 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2486 if (IsDerivedFrom(ToPointee1, ToPointee2))
2487 return ImplicitConversionSequence::Better;
2488 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2489 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002490
2491 if (ToIface1 && ToIface2) {
2492 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2493 return ImplicitConversionSequence::Better;
2494 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2495 return ImplicitConversionSequence::Worse;
2496 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002497 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002498
2499 // -- conversion of B* to A* is better than conversion of C* to A*,
2500 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2501 if (IsDerivedFrom(FromPointee2, FromPointee1))
2502 return ImplicitConversionSequence::Better;
2503 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2504 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002505
Douglas Gregor237f96c2008-11-26 23:31:11 +00002506 if (FromIface1 && FromIface2) {
2507 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2508 return ImplicitConversionSequence::Better;
2509 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2510 return ImplicitConversionSequence::Worse;
2511 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002512 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002513 }
2514
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002515 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002516 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2517 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2518 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2519 const MemberPointerType * FromMemPointer1 =
2520 FromType1->getAs<MemberPointerType>();
2521 const MemberPointerType * ToMemPointer1 =
2522 ToType1->getAs<MemberPointerType>();
2523 const MemberPointerType * FromMemPointer2 =
2524 FromType2->getAs<MemberPointerType>();
2525 const MemberPointerType * ToMemPointer2 =
2526 ToType2->getAs<MemberPointerType>();
2527 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2528 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2529 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2530 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2531 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2532 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2533 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2534 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002535 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002536 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2537 if (IsDerivedFrom(ToPointee1, ToPointee2))
2538 return ImplicitConversionSequence::Worse;
2539 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2540 return ImplicitConversionSequence::Better;
2541 }
2542 // conversion of B::* to C::* is better than conversion of A::* to C::*
2543 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2544 if (IsDerivedFrom(FromPointee1, FromPointee2))
2545 return ImplicitConversionSequence::Better;
2546 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2547 return ImplicitConversionSequence::Worse;
2548 }
2549 }
2550
Douglas Gregor5ab11652010-04-17 22:01:05 +00002551 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002552 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002553 // -- binding of an expression of type C to a reference of type
2554 // B& is better than binding an expression of type C to a
2555 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002556 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2557 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002558 if (IsDerivedFrom(ToType1, ToType2))
2559 return ImplicitConversionSequence::Better;
2560 else if (IsDerivedFrom(ToType2, ToType1))
2561 return ImplicitConversionSequence::Worse;
2562 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002563
Douglas Gregor2fe98832008-11-03 19:09:14 +00002564 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002565 // -- binding of an expression of type B to a reference of type
2566 // A& is better than binding an expression of type C to a
2567 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002568 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2569 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002570 if (IsDerivedFrom(FromType2, FromType1))
2571 return ImplicitConversionSequence::Better;
2572 else if (IsDerivedFrom(FromType1, FromType2))
2573 return ImplicitConversionSequence::Worse;
2574 }
2575 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002576
Douglas Gregor5c407d92008-10-23 00:40:37 +00002577 return ImplicitConversionSequence::Indistinguishable;
2578}
2579
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002580/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2581/// determine whether they are reference-related,
2582/// reference-compatible, reference-compatible with added
2583/// qualification, or incompatible, for use in C++ initialization by
2584/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2585/// type, and the first type (T1) is the pointee type of the reference
2586/// type being initialized.
2587Sema::ReferenceCompareResult
2588Sema::CompareReferenceRelationship(SourceLocation Loc,
2589 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002590 bool &DerivedToBase,
2591 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002592 assert(!OrigT1->isReferenceType() &&
2593 "T1 must be the pointee type of the reference type");
2594 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2595
2596 QualType T1 = Context.getCanonicalType(OrigT1);
2597 QualType T2 = Context.getCanonicalType(OrigT2);
2598 Qualifiers T1Quals, T2Quals;
2599 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2600 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2601
2602 // C++ [dcl.init.ref]p4:
2603 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2604 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2605 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002606 DerivedToBase = false;
2607 ObjCConversion = false;
2608 if (UnqualT1 == UnqualT2) {
2609 // Nothing to do.
2610 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002611 IsDerivedFrom(UnqualT2, UnqualT1))
2612 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002613 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2614 UnqualT2->isObjCObjectOrInterfaceType() &&
2615 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2616 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002617 else
2618 return Ref_Incompatible;
2619
2620 // At this point, we know that T1 and T2 are reference-related (at
2621 // least).
2622
2623 // If the type is an array type, promote the element qualifiers to the type
2624 // for comparison.
2625 if (isa<ArrayType>(T1) && T1Quals)
2626 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2627 if (isa<ArrayType>(T2) && T2Quals)
2628 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2629
2630 // C++ [dcl.init.ref]p4:
2631 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2632 // reference-related to T2 and cv1 is the same cv-qualification
2633 // as, or greater cv-qualification than, cv2. For purposes of
2634 // overload resolution, cases for which cv1 is greater
2635 // cv-qualification than cv2 are identified as
2636 // reference-compatible with added qualification (see 13.3.3.2).
2637 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2638 return Ref_Compatible;
2639 else if (T1.isMoreQualifiedThan(T2))
2640 return Ref_Compatible_With_Added_Qualification;
2641 else
2642 return Ref_Related;
2643}
2644
Douglas Gregor836a7e82010-08-11 02:15:33 +00002645/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002646/// with DeclType. Return true if something definite is found.
2647static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002648FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2649 QualType DeclType, SourceLocation DeclLoc,
2650 Expr *Init, QualType T2, bool AllowRvalues,
2651 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002652 assert(T2->isRecordType() && "Can only find conversions of record types.");
2653 CXXRecordDecl *T2RecordDecl
2654 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2655
Douglas Gregor836a7e82010-08-11 02:15:33 +00002656 QualType ToType
2657 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2658 : DeclType;
2659
Sebastian Redld92badf2010-06-30 18:13:39 +00002660 OverloadCandidateSet CandidateSet(DeclLoc);
2661 const UnresolvedSetImpl *Conversions
2662 = T2RecordDecl->getVisibleConversionFunctions();
2663 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2664 E = Conversions->end(); I != E; ++I) {
2665 NamedDecl *D = *I;
2666 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2667 if (isa<UsingShadowDecl>(D))
2668 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2669
2670 FunctionTemplateDecl *ConvTemplate
2671 = dyn_cast<FunctionTemplateDecl>(D);
2672 CXXConversionDecl *Conv;
2673 if (ConvTemplate)
2674 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2675 else
2676 Conv = cast<CXXConversionDecl>(D);
2677
Douglas Gregor836a7e82010-08-11 02:15:33 +00002678 // If this is an explicit conversion, and we're not allowed to consider
2679 // explicit conversions, skip it.
2680 if (!AllowExplicit && Conv->isExplicit())
2681 continue;
2682
2683 if (AllowRvalues) {
2684 bool DerivedToBase = false;
2685 bool ObjCConversion = false;
2686 if (!ConvTemplate &&
2687 S.CompareReferenceRelationship(DeclLoc,
2688 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2689 DeclType.getNonReferenceType().getUnqualifiedType(),
2690 DerivedToBase, ObjCConversion)
2691 == Sema::Ref_Incompatible)
2692 continue;
2693 } else {
2694 // If the conversion function doesn't return a reference type,
2695 // it can't be considered for this conversion. An rvalue reference
2696 // is only acceptable if its referencee is a function type.
2697
2698 const ReferenceType *RefType =
2699 Conv->getConversionType()->getAs<ReferenceType>();
2700 if (!RefType ||
2701 (!RefType->isLValueReferenceType() &&
2702 !RefType->getPointeeType()->isFunctionType()))
2703 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002704 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002705
2706 if (ConvTemplate)
2707 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2708 Init, ToType, CandidateSet);
2709 else
2710 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2711 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002712 }
2713
2714 OverloadCandidateSet::iterator Best;
2715 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2716 case OR_Success:
2717 // C++ [over.ics.ref]p1:
2718 //
2719 // [...] If the parameter binds directly to the result of
2720 // applying a conversion function to the argument
2721 // expression, the implicit conversion sequence is a
2722 // user-defined conversion sequence (13.3.3.1.2), with the
2723 // second standard conversion sequence either an identity
2724 // conversion or, if the conversion function returns an
2725 // entity of a type that is a derived class of the parameter
2726 // type, a derived-to-base Conversion.
2727 if (!Best->FinalConversion.DirectBinding)
2728 return false;
2729
2730 ICS.setUserDefined();
2731 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2732 ICS.UserDefined.After = Best->FinalConversion;
2733 ICS.UserDefined.ConversionFunction = Best->Function;
2734 ICS.UserDefined.EllipsisConversion = false;
2735 assert(ICS.UserDefined.After.ReferenceBinding &&
2736 ICS.UserDefined.After.DirectBinding &&
2737 "Expected a direct reference binding!");
2738 return true;
2739
2740 case OR_Ambiguous:
2741 ICS.setAmbiguous();
2742 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2743 Cand != CandidateSet.end(); ++Cand)
2744 if (Cand->Viable)
2745 ICS.Ambiguous.addConversion(Cand->Function);
2746 return true;
2747
2748 case OR_No_Viable_Function:
2749 case OR_Deleted:
2750 // There was no suitable conversion, or we found a deleted
2751 // conversion; continue with other checks.
2752 return false;
2753 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002754
2755 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002756}
2757
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002758/// \brief Compute an implicit conversion sequence for reference
2759/// initialization.
2760static ImplicitConversionSequence
2761TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2762 SourceLocation DeclLoc,
2763 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002764 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002765 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2766
2767 // Most paths end in a failed conversion.
2768 ImplicitConversionSequence ICS;
2769 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2770
2771 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2772 QualType T2 = Init->getType();
2773
2774 // If the initializer is the address of an overloaded function, try
2775 // to resolve the overloaded function. If all goes well, T2 is the
2776 // type of the resulting function.
2777 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2778 DeclAccessPair Found;
2779 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2780 false, Found))
2781 T2 = Fn->getType();
2782 }
2783
2784 // Compute some basic properties of the types and the initializer.
2785 bool isRValRef = DeclType->isRValueReferenceType();
2786 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002787 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002788 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002789 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002790 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2791 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002792
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002793
Sebastian Redld92badf2010-06-30 18:13:39 +00002794 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002795 // A reference to type "cv1 T1" is initialized by an expression
2796 // of type "cv2 T2" as follows:
2797
Sebastian Redld92badf2010-06-30 18:13:39 +00002798 // -- If reference is an lvalue reference and the initializer expression
2799 // The next bullet point (T1 is a function) is pretty much equivalent to this
2800 // one, so it's handled here.
2801 if (!isRValRef || T1->isFunctionType()) {
2802 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2803 // reference-compatible with "cv2 T2," or
2804 //
2805 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2806 if (InitCategory.isLValue() &&
2807 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002808 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002809 // When a parameter of reference type binds directly (8.5.3)
2810 // to an argument expression, the implicit conversion sequence
2811 // is the identity conversion, unless the argument expression
2812 // has a type that is a derived class of the parameter type,
2813 // in which case the implicit conversion sequence is a
2814 // derived-to-base Conversion (13.3.3.1).
2815 ICS.setStandard();
2816 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002817 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2818 : ObjCConversion? ICK_Compatible_Conversion
2819 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002820 ICS.Standard.Third = ICK_Identity;
2821 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2822 ICS.Standard.setToType(0, T2);
2823 ICS.Standard.setToType(1, T1);
2824 ICS.Standard.setToType(2, T1);
2825 ICS.Standard.ReferenceBinding = true;
2826 ICS.Standard.DirectBinding = true;
2827 ICS.Standard.RRefBinding = isRValRef;
2828 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002829
Sebastian Redld92badf2010-06-30 18:13:39 +00002830 // Nothing more to do: the inaccessibility/ambiguity check for
2831 // derived-to-base conversions is suppressed when we're
2832 // computing the implicit conversion sequence (C++
2833 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002834 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002835 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002836
Sebastian Redld92badf2010-06-30 18:13:39 +00002837 // -- has a class type (i.e., T2 is a class type), where T1 is
2838 // not reference-related to T2, and can be implicitly
2839 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2840 // is reference-compatible with "cv3 T3" 92) (this
2841 // conversion is selected by enumerating the applicable
2842 // conversion functions (13.3.1.6) and choosing the best
2843 // one through overload resolution (13.3)),
2844 if (!SuppressUserConversions && T2->isRecordType() &&
2845 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2846 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002847 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2848 Init, T2, /*AllowRvalues=*/false,
2849 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002850 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002851 }
2852 }
2853
Sebastian Redld92badf2010-06-30 18:13:39 +00002854 // -- Otherwise, the reference shall be an lvalue reference to a
2855 // non-volatile const type (i.e., cv1 shall be const), or the reference
2856 // shall be an rvalue reference and the initializer expression shall be
2857 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002858 //
2859 // We actually handle one oddity of C++ [over.ics.ref] at this
2860 // point, which is that, due to p2 (which short-circuits reference
2861 // binding by only attempting a simple conversion for non-direct
2862 // bindings) and p3's strange wording, we allow a const volatile
2863 // reference to bind to an rvalue. Hence the check for the presence
2864 // of "const" rather than checking for "const" being the only
2865 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002866 // This is also the point where rvalue references and lvalue inits no longer
2867 // go together.
2868 if ((!isRValRef && !T1.isConstQualified()) ||
2869 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002870 return ICS;
2871
Sebastian Redld92badf2010-06-30 18:13:39 +00002872 // -- If T1 is a function type, then
2873 // -- if T2 is the same type as T1, the reference is bound to the
2874 // initializer expression lvalue;
2875 // -- if T2 is a class type and the initializer expression can be
2876 // implicitly converted to an lvalue of type T1 [...], the
2877 // reference is bound to the function lvalue that is the result
2878 // of the conversion;
2879 // This is the same as for the lvalue case above, so it was handled there.
2880 // -- otherwise, the program is ill-formed.
2881 // This is the one difference to the lvalue case.
2882 if (T1->isFunctionType())
2883 return ICS;
2884
2885 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002886 // -- the initializer expression is an rvalue and "cv1 T1"
2887 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002888 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002889 // -- T1 is not reference-related to T2 and the initializer
2890 // expression can be implicitly converted to an rvalue
2891 // of type "cv3 T3" (this conversion is selected by
2892 // enumerating the applicable conversion functions
2893 // (13.3.1.6) and choosing the best one through overload
2894 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002895 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002896 // then the reference is bound to the initializer
2897 // expression rvalue in the first case and to the object
2898 // that is the result of the conversion in the second case
2899 // (or, in either case, to the appropriate base class
2900 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002901 if (T2->isRecordType()) {
2902 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2903 // direct binding in C++0x but not in C++03.
2904 if (InitCategory.isRValue() &&
2905 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2906 ICS.setStandard();
2907 ICS.Standard.First = ICK_Identity;
2908 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2909 : ObjCConversion? ICK_Compatible_Conversion
2910 : ICK_Identity;
2911 ICS.Standard.Third = ICK_Identity;
2912 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2913 ICS.Standard.setToType(0, T2);
2914 ICS.Standard.setToType(1, T1);
2915 ICS.Standard.setToType(2, T1);
2916 ICS.Standard.ReferenceBinding = true;
2917 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2918 ICS.Standard.RRefBinding = isRValRef;
2919 ICS.Standard.CopyConstructor = 0;
2920 return ICS;
2921 }
2922
2923 // Second case: not reference-related.
2924 if (RefRelationship == Sema::Ref_Incompatible &&
2925 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2926 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2927 Init, T2, /*AllowRvalues=*/true,
2928 AllowExplicit))
2929 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002930 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002931
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002932 // -- Otherwise, a temporary of type "cv1 T1" is created and
2933 // initialized from the initializer expression using the
2934 // rules for a non-reference copy initialization (8.5). The
2935 // reference is then bound to the temporary. If T1 is
2936 // reference-related to T2, cv1 must be the same
2937 // cv-qualification as, or greater cv-qualification than,
2938 // cv2; otherwise, the program is ill-formed.
2939 if (RefRelationship == Sema::Ref_Related) {
2940 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2941 // we would be reference-compatible or reference-compatible with
2942 // added qualification. But that wasn't the case, so the reference
2943 // initialization fails.
2944 return ICS;
2945 }
2946
2947 // If at least one of the types is a class type, the types are not
2948 // related, and we aren't allowed any user conversions, the
2949 // reference binding fails. This case is important for breaking
2950 // recursion, since TryImplicitConversion below will attempt to
2951 // create a temporary through the use of a copy constructor.
2952 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2953 (T1->isRecordType() || T2->isRecordType()))
2954 return ICS;
2955
2956 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002957 // When a parameter of reference type is not bound directly to
2958 // an argument expression, the conversion sequence is the one
2959 // required to convert the argument expression to the
2960 // underlying type of the reference according to
2961 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2962 // to copy-initializing a temporary of the underlying type with
2963 // the argument expression. Any difference in top-level
2964 // cv-qualification is subsumed by the initialization itself
2965 // and does not constitute a conversion.
2966 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2967 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002968 /*InOverloadResolution=*/false);
2969
2970 // Of course, that's still a reference binding.
2971 if (ICS.isStandard()) {
2972 ICS.Standard.ReferenceBinding = true;
2973 ICS.Standard.RRefBinding = isRValRef;
2974 } else if (ICS.isUserDefined()) {
2975 ICS.UserDefined.After.ReferenceBinding = true;
2976 ICS.UserDefined.After.RRefBinding = isRValRef;
2977 }
2978 return ICS;
2979}
2980
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002981/// TryCopyInitialization - Try to copy-initialize a value of type
2982/// ToType from the expression From. Return the implicit conversion
2983/// sequence required to pass this argument, which may be a bad
2984/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002985/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002986/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002987static ImplicitConversionSequence
2988TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002989 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002990 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002991 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002992 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002993 /*FIXME:*/From->getLocStart(),
2994 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002995 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002996
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002997 return S.TryImplicitConversion(From, ToType,
2998 SuppressUserConversions,
2999 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003000 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003001}
3002
Douglas Gregor436424c2008-11-18 23:14:02 +00003003/// TryObjectArgumentInitialization - Try to initialize the object
3004/// parameter of the given member function (@c Method) from the
3005/// expression @p From.
3006ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00003007Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00003008 CXXMethodDecl *Method,
3009 CXXRecordDecl *ActingContext) {
3010 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003011 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3012 // const volatile object.
3013 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3014 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3015 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003016
3017 // Set up the conversion sequence as a "bad" conversion, to allow us
3018 // to exit early.
3019 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003020
3021 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003022 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003023 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003024 FromType = PT->getPointeeType();
3025
3026 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003027
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003028 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003029 // where X is the class of which the function is a member
3030 // (C++ [over.match.funcs]p4). However, when finding an implicit
3031 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003032 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003033 // (C++ [over.match.funcs]p5). We perform a simplified version of
3034 // reference binding here, that allows class rvalues to bind to
3035 // non-constant references.
3036
3037 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3038 // with the implicit object parameter (C++ [over.match.funcs]p5).
3039 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003040 if (ImplicitParamType.getCVRQualifiers()
3041 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003042 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003043 ICS.setBad(BadConversionSequence::bad_qualifiers,
3044 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003045 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003046 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003047
3048 // Check that we have either the same type or a derived type. It
3049 // affects the conversion rank.
3050 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003051 ImplicitConversionKind SecondKind;
3052 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3053 SecondKind = ICK_Identity;
3054 } else if (IsDerivedFrom(FromType, ClassType))
3055 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003056 else {
John McCall65eb8792010-02-25 01:37:24 +00003057 ICS.setBad(BadConversionSequence::unrelated_class,
3058 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003059 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003060 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003061
3062 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003063 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003064 ICS.Standard.setAsIdentityConversion();
3065 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003066 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003067 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003068 ICS.Standard.ReferenceBinding = true;
3069 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003070 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003071 return ICS;
3072}
3073
3074/// PerformObjectArgumentInitialization - Perform initialization of
3075/// the implicit object parameter for the given Method with the given
3076/// expression.
3077bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003078Sema::PerformObjectArgumentInitialization(Expr *&From,
3079 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003080 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003081 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003082 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003083 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003084 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003085
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003086 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003087 FromRecordType = PT->getPointeeType();
3088 DestType = Method->getThisType(Context);
3089 } else {
3090 FromRecordType = From->getType();
3091 DestType = ImplicitParamRecordType;
3092 }
3093
John McCall6e9f8f62009-12-03 04:06:58 +00003094 // Note that we always use the true parent context when performing
3095 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003096 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003097 = TryObjectArgumentInitialization(From->getType(), Method,
3098 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003099 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003100 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003101 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003102 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003103
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003104 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003105 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003106
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003107 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003108 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003109 From->getType()->isPointerType() ?
3110 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003111 return false;
3112}
3113
Douglas Gregor5fb53972009-01-14 15:45:31 +00003114/// TryContextuallyConvertToBool - Attempt to contextually convert the
3115/// expression From to bool (C++0x [conv]p3).
3116ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003117 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003118 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003119 // FIXME: Are these flags correct?
3120 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003121 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003122 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003123}
3124
3125/// PerformContextuallyConvertToBool - Perform a contextual conversion
3126/// of the expression From to bool (C++0x [conv]p3).
3127bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3128 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003129 if (!ICS.isBad())
3130 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003131
Fariborz Jahanian76197412009-11-18 18:26:29 +00003132 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003133 return Diag(From->getSourceRange().getBegin(),
3134 diag::err_typecheck_bool_condition)
3135 << From->getType() << From->getSourceRange();
3136 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003137}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003138
3139/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3140/// expression From to 'id'.
3141ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003142 QualType Ty = Context.getObjCIdType();
3143 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003144 // FIXME: Are these flags correct?
3145 /*SuppressUserConversions=*/false,
3146 /*AllowExplicit=*/true,
3147 /*InOverloadResolution=*/false);
3148}
3149
3150/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3151/// of the expression From to 'id'.
3152bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003153 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003154 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3155 if (!ICS.isBad())
3156 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3157 return true;
3158}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003159
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003160/// \brief Attempt to convert the given expression to an integral or
3161/// enumeration type.
3162///
3163/// This routine will attempt to convert an expression of class type to an
3164/// integral or enumeration type, if that class type only has a single
3165/// conversion to an integral or enumeration type.
3166///
Douglas Gregor4799d032010-06-30 00:20:43 +00003167/// \param Loc The source location of the construct that requires the
3168/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003169///
Douglas Gregor4799d032010-06-30 00:20:43 +00003170/// \param FromE The expression we're converting from.
3171///
3172/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3173/// have integral or enumeration type.
3174///
3175/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3176/// incomplete class type.
3177///
3178/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3179/// explicit conversion function (because no implicit conversion functions
3180/// were available). This is a recovery mode.
3181///
3182/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3183/// showing which conversion was picked.
3184///
3185/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3186/// conversion function that could convert to integral or enumeration type.
3187///
3188/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3189/// usable conversion function.
3190///
3191/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3192/// function, which may be an extension in this case.
3193///
3194/// \returns The expression, converted to an integral or enumeration type if
3195/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003196ExprResult
John McCallb268a282010-08-23 23:25:46 +00003197Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003198 const PartialDiagnostic &NotIntDiag,
3199 const PartialDiagnostic &IncompleteDiag,
3200 const PartialDiagnostic &ExplicitConvDiag,
3201 const PartialDiagnostic &ExplicitConvNote,
3202 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003203 const PartialDiagnostic &AmbigNote,
3204 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003205 // We can't perform any more checking for type-dependent expressions.
3206 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003207 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003208
3209 // If the expression already has integral or enumeration type, we're golden.
3210 QualType T = From->getType();
3211 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003212 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003213
3214 // FIXME: Check for missing '()' if T is a function type?
3215
3216 // If we don't have a class type in C++, there's no way we can get an
3217 // expression of integral or enumeration type.
3218 const RecordType *RecordTy = T->getAs<RecordType>();
3219 if (!RecordTy || !getLangOptions().CPlusPlus) {
3220 Diag(Loc, NotIntDiag)
3221 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003222 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003223 }
3224
3225 // We must have a complete class type.
3226 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003227 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003228
3229 // Look for a conversion to an integral or enumeration type.
3230 UnresolvedSet<4> ViableConversions;
3231 UnresolvedSet<4> ExplicitConversions;
3232 const UnresolvedSetImpl *Conversions
3233 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3234
3235 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3236 E = Conversions->end();
3237 I != E;
3238 ++I) {
3239 if (CXXConversionDecl *Conversion
3240 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3241 if (Conversion->getConversionType().getNonReferenceType()
3242 ->isIntegralOrEnumerationType()) {
3243 if (Conversion->isExplicit())
3244 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3245 else
3246 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3247 }
3248 }
3249
3250 switch (ViableConversions.size()) {
3251 case 0:
3252 if (ExplicitConversions.size() == 1) {
3253 DeclAccessPair Found = ExplicitConversions[0];
3254 CXXConversionDecl *Conversion
3255 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3256
3257 // The user probably meant to invoke the given explicit
3258 // conversion; use it.
3259 QualType ConvTy
3260 = Conversion->getConversionType().getNonReferenceType();
3261 std::string TypeStr;
3262 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3263
3264 Diag(Loc, ExplicitConvDiag)
3265 << T << ConvTy
3266 << FixItHint::CreateInsertion(From->getLocStart(),
3267 "static_cast<" + TypeStr + ">(")
3268 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3269 ")");
3270 Diag(Conversion->getLocation(), ExplicitConvNote)
3271 << ConvTy->isEnumeralType() << ConvTy;
3272
3273 // If we aren't in a SFINAE context, build a call to the
3274 // explicit conversion function.
3275 if (isSFINAEContext())
3276 return ExprError();
3277
3278 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003279 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003280 }
3281
3282 // We'll complain below about a non-integral condition type.
3283 break;
3284
3285 case 1: {
3286 // Apply this conversion.
3287 DeclAccessPair Found = ViableConversions[0];
3288 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003289
3290 CXXConversionDecl *Conversion
3291 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3292 QualType ConvTy
3293 = Conversion->getConversionType().getNonReferenceType();
3294 if (ConvDiag.getDiagID()) {
3295 if (isSFINAEContext())
3296 return ExprError();
3297
3298 Diag(Loc, ConvDiag)
3299 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3300 }
3301
John McCallb268a282010-08-23 23:25:46 +00003302 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003303 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003304 break;
3305 }
3306
3307 default:
3308 Diag(Loc, AmbigDiag)
3309 << T << From->getSourceRange();
3310 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3311 CXXConversionDecl *Conv
3312 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3313 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3314 Diag(Conv->getLocation(), AmbigNote)
3315 << ConvTy->isEnumeralType() << ConvTy;
3316 }
John McCallb268a282010-08-23 23:25:46 +00003317 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003318 }
3319
Douglas Gregor5823da32010-06-29 23:25:20 +00003320 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003321 Diag(Loc, NotIntDiag)
3322 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003323
John McCallb268a282010-08-23 23:25:46 +00003324 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003325}
3326
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003327/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003328/// candidate functions, using the given function call arguments. If
3329/// @p SuppressUserConversions, then don't allow user-defined
3330/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003331///
3332/// \para PartialOverloading true if we are performing "partial" overloading
3333/// based on an incomplete set of function arguments. This feature is used by
3334/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003335void
3336Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003337 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003338 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003339 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003340 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003341 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003342 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003343 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003344 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003345 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003346 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003347
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003348 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003349 if (!isa<CXXConstructorDecl>(Method)) {
3350 // If we get here, it's because we're calling a member function
3351 // that is named without a member access expression (e.g.,
3352 // "this->f") that was either written explicitly or created
3353 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003354 // function, e.g., X::f(). We use an empty type for the implied
3355 // object argument (C++ [over.call.func]p3), and the acting context
3356 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003357 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003358 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003359 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003360 return;
3361 }
3362 // We treat a constructor like a non-member function, since its object
3363 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003364 }
3365
Douglas Gregorff7028a2009-11-13 23:59:09 +00003366 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003367 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003368
Douglas Gregor27381f32009-11-23 12:27:39 +00003369 // Overload resolution is always an unevaluated context.
3370 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3371
Douglas Gregorffe14e32009-11-14 01:20:54 +00003372 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3373 // C++ [class.copy]p3:
3374 // A member function template is never instantiated to perform the copy
3375 // of a class object to an object of its class type.
3376 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3377 if (NumArgs == 1 &&
3378 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003379 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3380 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003381 return;
3382 }
3383
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003384 // Add this candidate
3385 CandidateSet.push_back(OverloadCandidate());
3386 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003387 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003388 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003389 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003390 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003391 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003392
3393 unsigned NumArgsInProto = Proto->getNumArgs();
3394
3395 // (C++ 13.3.2p2): A candidate function having fewer than m
3396 // parameters is viable only if it has an ellipsis in its parameter
3397 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003398 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3399 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003400 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003401 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003402 return;
3403 }
3404
3405 // (C++ 13.3.2p2): A candidate function having more than m parameters
3406 // is viable only if the (m+1)st parameter has a default argument
3407 // (8.3.6). For the purposes of overload resolution, the
3408 // parameter list is truncated on the right, so that there are
3409 // exactly m parameters.
3410 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003411 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003412 // Not enough arguments.
3413 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003414 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003415 return;
3416 }
3417
3418 // Determine the implicit conversion sequences for each of the
3419 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003420 Candidate.Conversions.resize(NumArgs);
3421 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3422 if (ArgIdx < NumArgsInProto) {
3423 // (C++ 13.3.2p3): for F to be a viable function, there shall
3424 // exist for each argument an implicit conversion sequence
3425 // (13.3.3.1) that converts that argument to the corresponding
3426 // parameter of F.
3427 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003428 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003429 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003430 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003431 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003432 if (Candidate.Conversions[ArgIdx].isBad()) {
3433 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003434 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003435 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003436 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003437 } else {
3438 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3439 // argument for which there is no corresponding parameter is
3440 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003441 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003442 }
3443 }
3444}
3445
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003446/// \brief Add all of the function declarations in the given function set to
3447/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003448void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003449 Expr **Args, unsigned NumArgs,
3450 OverloadCandidateSet& CandidateSet,
3451 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003452 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003453 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3454 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003455 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003456 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003457 cast<CXXMethodDecl>(FD)->getParent(),
3458 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003459 CandidateSet, SuppressUserConversions);
3460 else
John McCalla0296f72010-03-19 07:35:19 +00003461 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003462 SuppressUserConversions);
3463 } else {
John McCalla0296f72010-03-19 07:35:19 +00003464 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003465 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3466 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003467 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003468 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003469 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003470 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003471 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003472 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003473 else
John McCalla0296f72010-03-19 07:35:19 +00003474 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003475 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003476 Args, NumArgs, CandidateSet,
3477 SuppressUserConversions);
3478 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003479 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003480}
3481
John McCallf0f1cf02009-11-17 07:50:12 +00003482/// AddMethodCandidate - Adds a named decl (which is some kind of
3483/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003484void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003485 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003486 Expr **Args, unsigned NumArgs,
3487 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003488 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003489 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003490 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003491
3492 if (isa<UsingShadowDecl>(Decl))
3493 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3494
3495 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3496 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3497 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003498 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3499 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003500 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003501 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003502 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003503 } else {
John McCalla0296f72010-03-19 07:35:19 +00003504 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003505 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003506 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003507 }
3508}
3509
Douglas Gregor436424c2008-11-18 23:14:02 +00003510/// AddMethodCandidate - Adds the given C++ member function to the set
3511/// of candidate functions, using the given function call arguments
3512/// and the object argument (@c Object). For example, in a call
3513/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3514/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3515/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003516/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003517void
John McCalla0296f72010-03-19 07:35:19 +00003518Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003519 CXXRecordDecl *ActingContext, QualType ObjectType,
3520 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003521 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003522 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003523 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003524 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003525 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003526 assert(!isa<CXXConstructorDecl>(Method) &&
3527 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003528
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003529 if (!CandidateSet.isNewCandidate(Method))
3530 return;
3531
Douglas Gregor27381f32009-11-23 12:27:39 +00003532 // Overload resolution is always an unevaluated context.
3533 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3534
Douglas Gregor436424c2008-11-18 23:14:02 +00003535 // Add this candidate
3536 CandidateSet.push_back(OverloadCandidate());
3537 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003538 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003539 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003540 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003541 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003542
3543 unsigned NumArgsInProto = Proto->getNumArgs();
3544
3545 // (C++ 13.3.2p2): A candidate function having fewer than m
3546 // parameters is viable only if it has an ellipsis in its parameter
3547 // list (8.3.5).
3548 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3549 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003550 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003551 return;
3552 }
3553
3554 // (C++ 13.3.2p2): A candidate function having more than m parameters
3555 // is viable only if the (m+1)st parameter has a default argument
3556 // (8.3.6). For the purposes of overload resolution, the
3557 // parameter list is truncated on the right, so that there are
3558 // exactly m parameters.
3559 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3560 if (NumArgs < MinRequiredArgs) {
3561 // Not enough arguments.
3562 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003563 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003564 return;
3565 }
3566
3567 Candidate.Viable = true;
3568 Candidate.Conversions.resize(NumArgs + 1);
3569
John McCall6e9f8f62009-12-03 04:06:58 +00003570 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003571 // The implicit object argument is ignored.
3572 Candidate.IgnoreObjectArgument = true;
3573 else {
3574 // Determine the implicit conversion sequence for the object
3575 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003576 Candidate.Conversions[0]
3577 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003578 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003579 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003580 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003581 return;
3582 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003583 }
3584
3585 // Determine the implicit conversion sequences for each of the
3586 // arguments.
3587 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3588 if (ArgIdx < NumArgsInProto) {
3589 // (C++ 13.3.2p3): for F to be a viable function, there shall
3590 // exist for each argument an implicit conversion sequence
3591 // (13.3.3.1) that converts that argument to the corresponding
3592 // parameter of F.
3593 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003594 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003595 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003596 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003597 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003598 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003599 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003600 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003601 break;
3602 }
3603 } else {
3604 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3605 // argument for which there is no corresponding parameter is
3606 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003607 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003608 }
3609 }
3610}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003611
Douglas Gregor97628d62009-08-21 00:16:32 +00003612/// \brief Add a C++ member function template as a candidate to the candidate
3613/// set, using template argument deduction to produce an appropriate member
3614/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003615void
Douglas Gregor97628d62009-08-21 00:16:32 +00003616Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003617 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003618 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003619 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003620 QualType ObjectType,
3621 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003622 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003623 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003624 if (!CandidateSet.isNewCandidate(MethodTmpl))
3625 return;
3626
Douglas Gregor97628d62009-08-21 00:16:32 +00003627 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003628 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003629 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003630 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003631 // candidate functions in the usual way.113) A given name can refer to one
3632 // or more function templates and also to a set of overloaded non-template
3633 // functions. In such a case, the candidate functions generated from each
3634 // function template are combined with the set of non-template candidate
3635 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003636 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003637 FunctionDecl *Specialization = 0;
3638 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003639 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003640 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003641 CandidateSet.push_back(OverloadCandidate());
3642 OverloadCandidate &Candidate = CandidateSet.back();
3643 Candidate.FoundDecl = FoundDecl;
3644 Candidate.Function = MethodTmpl->getTemplatedDecl();
3645 Candidate.Viable = false;
3646 Candidate.FailureKind = ovl_fail_bad_deduction;
3647 Candidate.IsSurrogate = false;
3648 Candidate.IgnoreObjectArgument = false;
3649 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3650 Info);
3651 return;
3652 }
Mike Stump11289f42009-09-09 15:08:12 +00003653
Douglas Gregor97628d62009-08-21 00:16:32 +00003654 // Add the function template specialization produced by template argument
3655 // deduction as a candidate.
3656 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003657 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003658 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003659 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003660 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003661 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003662}
3663
Douglas Gregor05155d82009-08-21 23:19:43 +00003664/// \brief Add a C++ function template specialization as a candidate
3665/// in the candidate set, using template argument deduction to produce
3666/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003667void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003668Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003669 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003670 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003671 Expr **Args, unsigned NumArgs,
3672 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003673 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003674 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3675 return;
3676
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003677 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003678 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003679 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003680 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003681 // candidate functions in the usual way.113) A given name can refer to one
3682 // or more function templates and also to a set of overloaded non-template
3683 // functions. In such a case, the candidate functions generated from each
3684 // function template are combined with the set of non-template candidate
3685 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003686 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003687 FunctionDecl *Specialization = 0;
3688 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003689 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003690 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003691 CandidateSet.push_back(OverloadCandidate());
3692 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003693 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003694 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3695 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003696 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003697 Candidate.IsSurrogate = false;
3698 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003699 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3700 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003701 return;
3702 }
Mike Stump11289f42009-09-09 15:08:12 +00003703
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003704 // Add the function template specialization produced by template argument
3705 // deduction as a candidate.
3706 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003707 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003708 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003709}
Mike Stump11289f42009-09-09 15:08:12 +00003710
Douglas Gregora1f013e2008-11-07 22:36:19 +00003711/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003712/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003713/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003714/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003715/// (which may or may not be the same type as the type that the
3716/// conversion function produces).
3717void
3718Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003719 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003720 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003721 Expr *From, QualType ToType,
3722 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003723 assert(!Conversion->getDescribedFunctionTemplate() &&
3724 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003725 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003726 if (!CandidateSet.isNewCandidate(Conversion))
3727 return;
3728
Douglas Gregor27381f32009-11-23 12:27:39 +00003729 // Overload resolution is always an unevaluated context.
3730 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3731
Douglas Gregora1f013e2008-11-07 22:36:19 +00003732 // Add this candidate
3733 CandidateSet.push_back(OverloadCandidate());
3734 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003735 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003736 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003737 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003738 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003739 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003740 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003741 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003742 Candidate.Viable = true;
3743 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003744
Douglas Gregor6affc782010-08-19 15:37:02 +00003745 // C++ [over.match.funcs]p4:
3746 // For conversion functions, the function is considered to be a member of
3747 // the class of the implicit implied object argument for the purpose of
3748 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003749 //
3750 // Determine the implicit conversion sequence for the implicit
3751 // object parameter.
3752 QualType ImplicitParamType = From->getType();
3753 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3754 ImplicitParamType = FromPtrType->getPointeeType();
3755 CXXRecordDecl *ConversionContext
3756 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3757
3758 Candidate.Conversions[0]
3759 = TryObjectArgumentInitialization(From->getType(), Conversion,
3760 ConversionContext);
3761
John McCall0d1da222010-01-12 00:44:57 +00003762 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003763 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003764 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003765 return;
3766 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003767
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003768 // We won't go through a user-define type conversion function to convert a
3769 // derived to base as such conversions are given Conversion Rank. They only
3770 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3771 QualType FromCanon
3772 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3773 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3774 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3775 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003776 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003777 return;
3778 }
3779
Douglas Gregora1f013e2008-11-07 22:36:19 +00003780 // To determine what the conversion from the result of calling the
3781 // conversion function to the type we're eventually trying to
3782 // convert to (ToType), we need to synthesize a call to the
3783 // conversion function and attempt copy initialization from it. This
3784 // makes sure that we get the right semantics with respect to
3785 // lvalues/rvalues and the type. Fortunately, we can allocate this
3786 // call on the stack and we don't need its arguments to be
3787 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003788 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003789 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003790 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3791 Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003792 CastExpr::CK_FunctionToPointerDecay,
John McCallcf142162010-08-07 06:22:56 +00003793 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003794
3795 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003796 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3797 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003798 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003799 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003800 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003801 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003802 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003803 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003804 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003805
John McCall0d1da222010-01-12 00:44:57 +00003806 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003807 case ImplicitConversionSequence::StandardConversion:
3808 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003809
3810 // C++ [over.ics.user]p3:
3811 // If the user-defined conversion is specified by a specialization of a
3812 // conversion function template, the second standard conversion sequence
3813 // shall have exact match rank.
3814 if (Conversion->getPrimaryTemplate() &&
3815 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3816 Candidate.Viable = false;
3817 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3818 }
3819
Douglas Gregora1f013e2008-11-07 22:36:19 +00003820 break;
3821
3822 case ImplicitConversionSequence::BadConversion:
3823 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003824 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003825 break;
3826
3827 default:
Mike Stump11289f42009-09-09 15:08:12 +00003828 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003829 "Can only end up with a standard conversion sequence or failure");
3830 }
3831}
3832
Douglas Gregor05155d82009-08-21 23:19:43 +00003833/// \brief Adds a conversion function template specialization
3834/// candidate to the overload set, using template argument deduction
3835/// to deduce the template arguments of the conversion function
3836/// template from the type that we are converting to (C++
3837/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003838void
Douglas Gregor05155d82009-08-21 23:19:43 +00003839Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003840 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003841 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003842 Expr *From, QualType ToType,
3843 OverloadCandidateSet &CandidateSet) {
3844 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3845 "Only conversion function templates permitted here");
3846
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003847 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3848 return;
3849
John McCallbc077cf2010-02-08 23:07:23 +00003850 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003851 CXXConversionDecl *Specialization = 0;
3852 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003853 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003854 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003855 CandidateSet.push_back(OverloadCandidate());
3856 OverloadCandidate &Candidate = CandidateSet.back();
3857 Candidate.FoundDecl = FoundDecl;
3858 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3859 Candidate.Viable = false;
3860 Candidate.FailureKind = ovl_fail_bad_deduction;
3861 Candidate.IsSurrogate = false;
3862 Candidate.IgnoreObjectArgument = false;
3863 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3864 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003865 return;
3866 }
Mike Stump11289f42009-09-09 15:08:12 +00003867
Douglas Gregor05155d82009-08-21 23:19:43 +00003868 // Add the conversion function template specialization produced by
3869 // template argument deduction as a candidate.
3870 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003871 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003872 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003873}
3874
Douglas Gregorab7897a2008-11-19 22:57:39 +00003875/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3876/// converts the given @c Object to a function pointer via the
3877/// conversion function @c Conversion, and then attempts to call it
3878/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3879/// the type of function that we'll eventually be calling.
3880void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003881 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003882 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003883 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003884 QualType ObjectType,
3885 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003886 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003887 if (!CandidateSet.isNewCandidate(Conversion))
3888 return;
3889
Douglas Gregor27381f32009-11-23 12:27:39 +00003890 // Overload resolution is always an unevaluated context.
3891 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3892
Douglas Gregorab7897a2008-11-19 22:57:39 +00003893 CandidateSet.push_back(OverloadCandidate());
3894 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003895 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003896 Candidate.Function = 0;
3897 Candidate.Surrogate = Conversion;
3898 Candidate.Viable = true;
3899 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003900 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003901 Candidate.Conversions.resize(NumArgs + 1);
3902
3903 // Determine the implicit conversion sequence for the implicit
3904 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003905 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003906 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003907 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003908 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003909 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003910 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003911 return;
3912 }
3913
3914 // The first conversion is actually a user-defined conversion whose
3915 // first conversion is ObjectInit's standard conversion (which is
3916 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003917 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003918 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003919 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003920 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003921 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003922 = Candidate.Conversions[0].UserDefined.Before;
3923 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3924
Mike Stump11289f42009-09-09 15:08:12 +00003925 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003926 unsigned NumArgsInProto = Proto->getNumArgs();
3927
3928 // (C++ 13.3.2p2): A candidate function having fewer than m
3929 // parameters is viable only if it has an ellipsis in its parameter
3930 // list (8.3.5).
3931 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3932 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003933 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003934 return;
3935 }
3936
3937 // Function types don't have any default arguments, so just check if
3938 // we have enough arguments.
3939 if (NumArgs < NumArgsInProto) {
3940 // Not enough arguments.
3941 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003942 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003943 return;
3944 }
3945
3946 // Determine the implicit conversion sequences for each of the
3947 // arguments.
3948 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3949 if (ArgIdx < NumArgsInProto) {
3950 // (C++ 13.3.2p3): for F to be a viable function, there shall
3951 // exist for each argument an implicit conversion sequence
3952 // (13.3.3.1) that converts that argument to the corresponding
3953 // parameter of F.
3954 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003955 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003956 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003957 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003958 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003959 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003960 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003961 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003962 break;
3963 }
3964 } else {
3965 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3966 // argument for which there is no corresponding parameter is
3967 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003968 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003969 }
3970 }
3971}
3972
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003973/// \brief Add overload candidates for overloaded operators that are
3974/// member functions.
3975///
3976/// Add the overloaded operator candidates that are member functions
3977/// for the operator Op that was used in an operator expression such
3978/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3979/// CandidateSet will store the added overload candidates. (C++
3980/// [over.match.oper]).
3981void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3982 SourceLocation OpLoc,
3983 Expr **Args, unsigned NumArgs,
3984 OverloadCandidateSet& CandidateSet,
3985 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003986 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3987
3988 // C++ [over.match.oper]p3:
3989 // For a unary operator @ with an operand of a type whose
3990 // cv-unqualified version is T1, and for a binary operator @ with
3991 // a left operand of a type whose cv-unqualified version is T1 and
3992 // a right operand of a type whose cv-unqualified version is T2,
3993 // three sets of candidate functions, designated member
3994 // candidates, non-member candidates and built-in candidates, are
3995 // constructed as follows:
3996 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00003997
3998 // -- If T1 is a class type, the set of member candidates is the
3999 // result of the qualified lookup of T1::operator@
4000 // (13.3.1.1.1); otherwise, the set of member candidates is
4001 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004002 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004003 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004004 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004005 return;
Mike Stump11289f42009-09-09 15:08:12 +00004006
John McCall27b18f82009-11-17 02:14:36 +00004007 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4008 LookupQualifiedName(Operators, T1Rec->getDecl());
4009 Operators.suppressDiagnostics();
4010
Mike Stump11289f42009-09-09 15:08:12 +00004011 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004012 OperEnd = Operators.end();
4013 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004014 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004015 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004016 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004017 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004018 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004019}
4020
Douglas Gregora11693b2008-11-12 17:17:38 +00004021/// AddBuiltinCandidate - Add a candidate for a built-in
4022/// operator. ResultTy and ParamTys are the result and parameter types
4023/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004024/// arguments being passed to the candidate. IsAssignmentOperator
4025/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004026/// operator. NumContextualBoolArguments is the number of arguments
4027/// (at the beginning of the argument list) that will be contextually
4028/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004029void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004030 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004031 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004032 bool IsAssignmentOperator,
4033 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004034 // Overload resolution is always an unevaluated context.
4035 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4036
Douglas Gregora11693b2008-11-12 17:17:38 +00004037 // Add this candidate
4038 CandidateSet.push_back(OverloadCandidate());
4039 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004040 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004041 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004042 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004043 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004044 Candidate.BuiltinTypes.ResultTy = ResultTy;
4045 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4046 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4047
4048 // Determine the implicit conversion sequences for each of the
4049 // arguments.
4050 Candidate.Viable = true;
4051 Candidate.Conversions.resize(NumArgs);
4052 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004053 // C++ [over.match.oper]p4:
4054 // For the built-in assignment operators, conversions of the
4055 // left operand are restricted as follows:
4056 // -- no temporaries are introduced to hold the left operand, and
4057 // -- no user-defined conversions are applied to the left
4058 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004059 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004060 //
4061 // We block these conversions by turning off user-defined
4062 // conversions, since that is the only way that initialization of
4063 // a reference to a non-class type can occur from something that
4064 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004065 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004066 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004067 "Contextual conversion to bool requires bool type");
4068 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4069 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004070 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004071 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004072 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004073 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004074 }
John McCall0d1da222010-01-12 00:44:57 +00004075 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004076 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004077 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004078 break;
4079 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004080 }
4081}
4082
4083/// BuiltinCandidateTypeSet - A set of types that will be used for the
4084/// candidate operator functions for built-in operators (C++
4085/// [over.built]). The types are separated into pointer types and
4086/// enumeration types.
4087class BuiltinCandidateTypeSet {
4088 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004089 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004090
4091 /// PointerTypes - The set of pointer types that will be used in the
4092 /// built-in candidates.
4093 TypeSet PointerTypes;
4094
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004095 /// MemberPointerTypes - The set of member pointer types that will be
4096 /// used in the built-in candidates.
4097 TypeSet MemberPointerTypes;
4098
Douglas Gregora11693b2008-11-12 17:17:38 +00004099 /// EnumerationTypes - The set of enumeration types that will be
4100 /// used in the built-in candidates.
4101 TypeSet EnumerationTypes;
4102
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004103 /// \brief The set of vector types that will be used in the built-in
4104 /// candidates.
4105 TypeSet VectorTypes;
4106
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004107 /// Sema - The semantic analysis instance where we are building the
4108 /// candidate type set.
4109 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004110
Douglas Gregora11693b2008-11-12 17:17:38 +00004111 /// Context - The AST context in which we will build the type sets.
4112 ASTContext &Context;
4113
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004114 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4115 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004116 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004117
4118public:
4119 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004120 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004121
Mike Stump11289f42009-09-09 15:08:12 +00004122 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004123 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004124
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004125 void AddTypesConvertedFrom(QualType Ty,
4126 SourceLocation Loc,
4127 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004128 bool AllowExplicitConversions,
4129 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004130
4131 /// pointer_begin - First pointer type found;
4132 iterator pointer_begin() { return PointerTypes.begin(); }
4133
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004134 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004135 iterator pointer_end() { return PointerTypes.end(); }
4136
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004137 /// member_pointer_begin - First member pointer type found;
4138 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4139
4140 /// member_pointer_end - Past the last member pointer type found;
4141 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4142
Douglas Gregora11693b2008-11-12 17:17:38 +00004143 /// enumeration_begin - First enumeration type found;
4144 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4145
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004146 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004147 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004148
4149 iterator vector_begin() { return VectorTypes.begin(); }
4150 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004151};
4152
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004153/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004154/// the set of pointer types along with any more-qualified variants of
4155/// that type. For example, if @p Ty is "int const *", this routine
4156/// will add "int const *", "int const volatile *", "int const
4157/// restrict *", and "int const volatile restrict *" to the set of
4158/// pointer types. Returns true if the add of @p Ty itself succeeded,
4159/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004160///
4161/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004162bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004163BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4164 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004165
Douglas Gregora11693b2008-11-12 17:17:38 +00004166 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004167 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004168 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004169
4170 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004171 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004172 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004173 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004174 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004175 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004176 buildObjCPtr = true;
4177 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004178 else
4179 assert(false && "type was not a pointer type!");
4180 }
4181 else
4182 PointeeTy = PointerTy->getPointeeType();
4183
Sebastian Redl4990a632009-11-18 20:39:26 +00004184 // Don't add qualified variants of arrays. For one, they're not allowed
4185 // (the qualifier would sink to the element type), and for another, the
4186 // only overload situation where it matters is subscript or pointer +- int,
4187 // and those shouldn't have qualifier variants anyway.
4188 if (PointeeTy->isArrayType())
4189 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004190 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004191 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004192 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004193 bool hasVolatile = VisibleQuals.hasVolatile();
4194 bool hasRestrict = VisibleQuals.hasRestrict();
4195
John McCall8ccfcb52009-09-24 19:53:00 +00004196 // Iterate through all strict supersets of BaseCVR.
4197 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4198 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004199 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4200 // in the types.
4201 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4202 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004203 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004204 if (!buildObjCPtr)
4205 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4206 else
4207 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004208 }
4209
4210 return true;
4211}
4212
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004213/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4214/// to the set of pointer types along with any more-qualified variants of
4215/// that type. For example, if @p Ty is "int const *", this routine
4216/// will add "int const *", "int const volatile *", "int const
4217/// restrict *", and "int const volatile restrict *" to the set of
4218/// pointer types. Returns true if the add of @p Ty itself succeeded,
4219/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004220///
4221/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004222bool
4223BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4224 QualType Ty) {
4225 // Insert this type.
4226 if (!MemberPointerTypes.insert(Ty))
4227 return false;
4228
John McCall8ccfcb52009-09-24 19:53:00 +00004229 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4230 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004231
John McCall8ccfcb52009-09-24 19:53:00 +00004232 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004233 // Don't add qualified variants of arrays. For one, they're not allowed
4234 // (the qualifier would sink to the element type), and for another, the
4235 // only overload situation where it matters is subscript or pointer +- int,
4236 // and those shouldn't have qualifier variants anyway.
4237 if (PointeeTy->isArrayType())
4238 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004239 const Type *ClassTy = PointerTy->getClass();
4240
4241 // Iterate through all strict supersets of the pointee type's CVR
4242 // qualifiers.
4243 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4244 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4245 if ((CVR | BaseCVR) != CVR) continue;
4246
4247 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4248 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004249 }
4250
4251 return true;
4252}
4253
Douglas Gregora11693b2008-11-12 17:17:38 +00004254/// AddTypesConvertedFrom - Add each of the types to which the type @p
4255/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004256/// primarily interested in pointer types and enumeration types. We also
4257/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004258/// AllowUserConversions is true if we should look at the conversion
4259/// functions of a class type, and AllowExplicitConversions if we
4260/// should also include the explicit conversion functions of a class
4261/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004262void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004263BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004264 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004265 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004266 bool AllowExplicitConversions,
4267 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004268 // Only deal with canonical types.
4269 Ty = Context.getCanonicalType(Ty);
4270
4271 // Look through reference types; they aren't part of the type of an
4272 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004273 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004274 Ty = RefTy->getPointeeType();
4275
4276 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004277 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004278
Sebastian Redl65ae2002009-11-05 16:36:20 +00004279 // If we're dealing with an array type, decay to the pointer.
4280 if (Ty->isArrayType())
4281 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004282 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4283 PointerTypes.insert(Ty);
4284 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004285 // Insert our type, and its more-qualified variants, into the set
4286 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004287 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004288 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004289 } else if (Ty->isMemberPointerType()) {
4290 // Member pointers are far easier, since the pointee can't be converted.
4291 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4292 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004293 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004294 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004295 } else if (Ty->isVectorType()) {
4296 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004297 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004298 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004299 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004300 // No conversion functions in incomplete types.
4301 return;
4302 }
Mike Stump11289f42009-09-09 15:08:12 +00004303
Douglas Gregora11693b2008-11-12 17:17:38 +00004304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004305 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004306 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004307 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004308 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004309 NamedDecl *D = I.getDecl();
4310 if (isa<UsingShadowDecl>(D))
4311 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004312
Mike Stump11289f42009-09-09 15:08:12 +00004313 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004314 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004315 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004316 continue;
4317
John McCallda4458e2010-03-31 01:36:47 +00004318 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004319 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004320 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004321 VisibleQuals);
4322 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004323 }
4324 }
4325 }
4326}
4327
Douglas Gregor84605ae2009-08-24 13:43:27 +00004328/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4329/// the volatile- and non-volatile-qualified assignment operators for the
4330/// given type to the candidate set.
4331static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4332 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004333 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004334 unsigned NumArgs,
4335 OverloadCandidateSet &CandidateSet) {
4336 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004337
Douglas Gregor84605ae2009-08-24 13:43:27 +00004338 // T& operator=(T&, T)
4339 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4340 ParamTypes[1] = T;
4341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4342 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004343
Douglas Gregor84605ae2009-08-24 13:43:27 +00004344 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4345 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004346 ParamTypes[0]
4347 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004348 ParamTypes[1] = T;
4349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004350 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004351 }
4352}
Mike Stump11289f42009-09-09 15:08:12 +00004353
Sebastian Redl1054fae2009-10-25 17:03:50 +00004354/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4355/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004356static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4357 Qualifiers VRQuals;
4358 const RecordType *TyRec;
4359 if (const MemberPointerType *RHSMPType =
4360 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004361 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004362 else
4363 TyRec = ArgExpr->getType()->getAs<RecordType>();
4364 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004365 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004366 VRQuals.addVolatile();
4367 VRQuals.addRestrict();
4368 return VRQuals;
4369 }
4370
4371 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004372 if (!ClassDecl->hasDefinition())
4373 return VRQuals;
4374
John McCallad371252010-01-20 00:46:10 +00004375 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004376 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004377
John McCallad371252010-01-20 00:46:10 +00004378 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004379 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004380 NamedDecl *D = I.getDecl();
4381 if (isa<UsingShadowDecl>(D))
4382 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4383 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004384 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4385 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4386 CanTy = ResTypeRef->getPointeeType();
4387 // Need to go down the pointer/mempointer chain and add qualifiers
4388 // as see them.
4389 bool done = false;
4390 while (!done) {
4391 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4392 CanTy = ResTypePtr->getPointeeType();
4393 else if (const MemberPointerType *ResTypeMPtr =
4394 CanTy->getAs<MemberPointerType>())
4395 CanTy = ResTypeMPtr->getPointeeType();
4396 else
4397 done = true;
4398 if (CanTy.isVolatileQualified())
4399 VRQuals.addVolatile();
4400 if (CanTy.isRestrictQualified())
4401 VRQuals.addRestrict();
4402 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4403 return VRQuals;
4404 }
4405 }
4406 }
4407 return VRQuals;
4408}
4409
Douglas Gregord08452f2008-11-19 15:42:04 +00004410/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4411/// operator overloads to the candidate set (C++ [over.built]), based
4412/// on the operator @p Op and the arguments given. For example, if the
4413/// operator is a binary '+', this routine might add "int
4414/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004415void
Mike Stump11289f42009-09-09 15:08:12 +00004416Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004417 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004418 Expr **Args, unsigned NumArgs,
4419 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004420 // The set of "promoted arithmetic types", which are the arithmetic
4421 // types are that preserved by promotion (C++ [over.built]p2). Note
4422 // that the first few of these types are the promoted integral
4423 // types; these types need to be first.
4424 // FIXME: What about complex?
4425 const unsigned FirstIntegralType = 0;
4426 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004427 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004428 LastPromotedIntegralType = 13;
4429 const unsigned FirstPromotedArithmeticType = 7,
4430 LastPromotedArithmeticType = 16;
4431 const unsigned NumArithmeticTypes = 16;
4432 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004433 Context.BoolTy, Context.CharTy, Context.WCharTy,
4434// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004435 Context.SignedCharTy, Context.ShortTy,
4436 Context.UnsignedCharTy, Context.UnsignedShortTy,
4437 Context.IntTy, Context.LongTy, Context.LongLongTy,
4438 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4439 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4440 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004441 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4442 "Invalid first promoted integral type");
4443 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4444 == Context.UnsignedLongLongTy &&
4445 "Invalid last promoted integral type");
4446 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4447 "Invalid first promoted arithmetic type");
4448 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4449 == Context.LongDoubleTy &&
4450 "Invalid last promoted arithmetic type");
4451
Douglas Gregora11693b2008-11-12 17:17:38 +00004452 // Find all of the types that the arguments can convert to, but only
4453 // if the operator we're looking at has built-in operator candidates
4454 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004455 Qualifiers VisibleTypeConversionsQuals;
4456 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004457 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4458 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4459
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004460 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004461 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4462 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4463 OpLoc,
4464 true,
4465 (Op == OO_Exclaim ||
4466 Op == OO_AmpAmp ||
4467 Op == OO_PipePipe),
4468 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004469
4470 bool isComparison = false;
4471 switch (Op) {
4472 case OO_None:
4473 case NUM_OVERLOADED_OPERATORS:
4474 assert(false && "Expected an overloaded operator");
4475 break;
4476
Douglas Gregord08452f2008-11-19 15:42:04 +00004477 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004478 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004479 goto UnaryStar;
4480 else
4481 goto BinaryStar;
4482 break;
4483
4484 case OO_Plus: // '+' is either unary or binary
4485 if (NumArgs == 1)
4486 goto UnaryPlus;
4487 else
4488 goto BinaryPlus;
4489 break;
4490
4491 case OO_Minus: // '-' is either unary or binary
4492 if (NumArgs == 1)
4493 goto UnaryMinus;
4494 else
4495 goto BinaryMinus;
4496 break;
4497
4498 case OO_Amp: // '&' is either unary or binary
4499 if (NumArgs == 1)
4500 goto UnaryAmp;
4501 else
4502 goto BinaryAmp;
4503
4504 case OO_PlusPlus:
4505 case OO_MinusMinus:
4506 // C++ [over.built]p3:
4507 //
4508 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4509 // is either volatile or empty, there exist candidate operator
4510 // functions of the form
4511 //
4512 // VQ T& operator++(VQ T&);
4513 // T operator++(VQ T&, int);
4514 //
4515 // C++ [over.built]p4:
4516 //
4517 // For every pair (T, VQ), where T is an arithmetic type other
4518 // than bool, and VQ is either volatile or empty, there exist
4519 // candidate operator functions of the form
4520 //
4521 // VQ T& operator--(VQ T&);
4522 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004523 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004524 Arith < NumArithmeticTypes; ++Arith) {
4525 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004526 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004527 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004528
4529 // Non-volatile version.
4530 if (NumArgs == 1)
4531 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4532 else
4533 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004534 // heuristic to reduce number of builtin candidates in the set.
4535 // Add volatile version only if there are conversions to a volatile type.
4536 if (VisibleTypeConversionsQuals.hasVolatile()) {
4537 // Volatile version
4538 ParamTypes[0]
4539 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4540 if (NumArgs == 1)
4541 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4542 else
4543 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4544 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004545 }
4546
4547 // C++ [over.built]p5:
4548 //
4549 // For every pair (T, VQ), where T is a cv-qualified or
4550 // cv-unqualified object type, and VQ is either volatile or
4551 // empty, there exist candidate operator functions of the form
4552 //
4553 // T*VQ& operator++(T*VQ&);
4554 // T*VQ& operator--(T*VQ&);
4555 // T* operator++(T*VQ&, int);
4556 // T* operator--(T*VQ&, int);
4557 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4558 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4559 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004560 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004561 continue;
4562
Mike Stump11289f42009-09-09 15:08:12 +00004563 QualType ParamTypes[2] = {
4564 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004565 };
Mike Stump11289f42009-09-09 15:08:12 +00004566
Douglas Gregord08452f2008-11-19 15:42:04 +00004567 // Without volatile
4568 if (NumArgs == 1)
4569 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4570 else
4571 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4572
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004573 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4574 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004575 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004576 ParamTypes[0]
4577 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004578 if (NumArgs == 1)
4579 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4580 else
4581 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4582 }
4583 }
4584 break;
4585
4586 UnaryStar:
4587 // C++ [over.built]p6:
4588 // For every cv-qualified or cv-unqualified object type T, there
4589 // exist candidate operator functions of the form
4590 //
4591 // T& operator*(T*);
4592 //
4593 // C++ [over.built]p7:
4594 // For every function type T, there exist candidate operator
4595 // functions of the form
4596 // T& operator*(T*);
4597 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4598 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4599 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004600 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004601 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004602 &ParamTy, Args, 1, CandidateSet);
4603 }
4604 break;
4605
4606 UnaryPlus:
4607 // C++ [over.built]p8:
4608 // For every type T, there exist candidate operator functions of
4609 // the form
4610 //
4611 // T* operator+(T*);
4612 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4613 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4614 QualType ParamTy = *Ptr;
4615 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4616 }
Mike Stump11289f42009-09-09 15:08:12 +00004617
Douglas Gregord08452f2008-11-19 15:42:04 +00004618 // Fall through
4619
4620 UnaryMinus:
4621 // C++ [over.built]p9:
4622 // For every promoted arithmetic type T, there exist candidate
4623 // operator functions of the form
4624 //
4625 // T operator+(T);
4626 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004627 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004628 Arith < LastPromotedArithmeticType; ++Arith) {
4629 QualType ArithTy = ArithmeticTypes[Arith];
4630 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4631 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004632
4633 // Extension: We also add these operators for vector types.
4634 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4635 VecEnd = CandidateTypes.vector_end();
4636 Vec != VecEnd; ++Vec) {
4637 QualType VecTy = *Vec;
4638 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4639 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004640 break;
4641
4642 case OO_Tilde:
4643 // C++ [over.built]p10:
4644 // For every promoted integral type T, there exist candidate
4645 // operator functions of the form
4646 //
4647 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004648 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004649 Int < LastPromotedIntegralType; ++Int) {
4650 QualType IntTy = ArithmeticTypes[Int];
4651 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4652 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004653
4654 // Extension: We also add this operator for vector types.
4655 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4656 VecEnd = CandidateTypes.vector_end();
4657 Vec != VecEnd; ++Vec) {
4658 QualType VecTy = *Vec;
4659 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4660 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004661 break;
4662
Douglas Gregora11693b2008-11-12 17:17:38 +00004663 case OO_New:
4664 case OO_Delete:
4665 case OO_Array_New:
4666 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004667 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004668 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004669 break;
4670
4671 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004672 UnaryAmp:
4673 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004674 // C++ [over.match.oper]p3:
4675 // -- For the operator ',', the unary operator '&', or the
4676 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004677 break;
4678
Douglas Gregor84605ae2009-08-24 13:43:27 +00004679 case OO_EqualEqual:
4680 case OO_ExclaimEqual:
4681 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004682 // For every pointer to member type T, there exist candidate operator
4683 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004684 //
4685 // bool operator==(T,T);
4686 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004687 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004688 MemPtr = CandidateTypes.member_pointer_begin(),
4689 MemPtrEnd = CandidateTypes.member_pointer_end();
4690 MemPtr != MemPtrEnd;
4691 ++MemPtr) {
4692 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4693 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4694 }
Mike Stump11289f42009-09-09 15:08:12 +00004695
Douglas Gregor84605ae2009-08-24 13:43:27 +00004696 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004697
Douglas Gregora11693b2008-11-12 17:17:38 +00004698 case OO_Less:
4699 case OO_Greater:
4700 case OO_LessEqual:
4701 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004702 // C++ [over.built]p15:
4703 //
4704 // For every pointer or enumeration type T, there exist
4705 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004706 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004707 // bool operator<(T, T);
4708 // bool operator>(T, T);
4709 // bool operator<=(T, T);
4710 // bool operator>=(T, T);
4711 // bool operator==(T, T);
4712 // bool operator!=(T, T);
4713 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4714 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4715 QualType ParamTypes[2] = { *Ptr, *Ptr };
4716 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4717 }
Mike Stump11289f42009-09-09 15:08:12 +00004718 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004719 = CandidateTypes.enumeration_begin();
4720 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4721 QualType ParamTypes[2] = { *Enum, *Enum };
4722 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4723 }
4724
4725 // Fall through.
4726 isComparison = true;
4727
Douglas Gregord08452f2008-11-19 15:42:04 +00004728 BinaryPlus:
4729 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004730 if (!isComparison) {
4731 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4732
4733 // C++ [over.built]p13:
4734 //
4735 // For every cv-qualified or cv-unqualified object type T
4736 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004737 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004738 // T* operator+(T*, ptrdiff_t);
4739 // T& operator[](T*, ptrdiff_t); [BELOW]
4740 // T* operator-(T*, ptrdiff_t);
4741 // T* operator+(ptrdiff_t, T*);
4742 // T& operator[](ptrdiff_t, T*); [BELOW]
4743 //
4744 // C++ [over.built]p14:
4745 //
4746 // For every T, where T is a pointer to object type, there
4747 // exist candidate operator functions of the form
4748 //
4749 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004750 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004751 = CandidateTypes.pointer_begin();
4752 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4753 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4754
4755 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4756 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4757
4758 if (Op == OO_Plus) {
4759 // T* operator+(ptrdiff_t, T*);
4760 ParamTypes[0] = ParamTypes[1];
4761 ParamTypes[1] = *Ptr;
4762 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4763 } else {
4764 // ptrdiff_t operator-(T, T);
4765 ParamTypes[1] = *Ptr;
4766 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4767 Args, 2, CandidateSet);
4768 }
4769 }
4770 }
4771 // Fall through
4772
Douglas Gregora11693b2008-11-12 17:17:38 +00004773 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004774 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004775 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004776 // C++ [over.built]p12:
4777 //
4778 // For every pair of promoted arithmetic types L and R, there
4779 // exist candidate operator functions of the form
4780 //
4781 // LR operator*(L, R);
4782 // LR operator/(L, R);
4783 // LR operator+(L, R);
4784 // LR operator-(L, R);
4785 // bool operator<(L, R);
4786 // bool operator>(L, R);
4787 // bool operator<=(L, R);
4788 // bool operator>=(L, R);
4789 // bool operator==(L, R);
4790 // bool operator!=(L, R);
4791 //
4792 // where LR is the result of the usual arithmetic conversions
4793 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004794 //
4795 // C++ [over.built]p24:
4796 //
4797 // For every pair of promoted arithmetic types L and R, there exist
4798 // candidate operator functions of the form
4799 //
4800 // LR operator?(bool, L, R);
4801 //
4802 // where LR is the result of the usual arithmetic conversions
4803 // between types L and R.
4804 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004805 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004806 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004807 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004808 Right < LastPromotedArithmeticType; ++Right) {
4809 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004810 QualType Result
4811 = isComparison
4812 ? Context.BoolTy
4813 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004814 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4815 }
4816 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004817
4818 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4819 // conditional operator for vector types.
4820 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4821 Vec1End = CandidateTypes.vector_end();
4822 Vec1 != Vec1End; ++Vec1)
4823 for (BuiltinCandidateTypeSet::iterator
4824 Vec2 = CandidateTypes.vector_begin(),
4825 Vec2End = CandidateTypes.vector_end();
4826 Vec2 != Vec2End; ++Vec2) {
4827 QualType LandR[2] = { *Vec1, *Vec2 };
4828 QualType Result;
4829 if (isComparison)
4830 Result = Context.BoolTy;
4831 else {
4832 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4833 Result = *Vec1;
4834 else
4835 Result = *Vec2;
4836 }
4837
4838 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4839 }
4840
Douglas Gregora11693b2008-11-12 17:17:38 +00004841 break;
4842
4843 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004844 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004845 case OO_Caret:
4846 case OO_Pipe:
4847 case OO_LessLess:
4848 case OO_GreaterGreater:
4849 // C++ [over.built]p17:
4850 //
4851 // For every pair of promoted integral types L and R, there
4852 // exist candidate operator functions of the form
4853 //
4854 // LR operator%(L, R);
4855 // LR operator&(L, R);
4856 // LR operator^(L, R);
4857 // LR operator|(L, R);
4858 // L operator<<(L, R);
4859 // L operator>>(L, R);
4860 //
4861 // where LR is the result of the usual arithmetic conversions
4862 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004863 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004864 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004865 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004866 Right < LastPromotedIntegralType; ++Right) {
4867 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4868 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4869 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004870 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004871 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4872 }
4873 }
4874 break;
4875
4876 case OO_Equal:
4877 // C++ [over.built]p20:
4878 //
4879 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004880 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004881 // empty, there exist candidate operator functions of the form
4882 //
4883 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004884 for (BuiltinCandidateTypeSet::iterator
4885 Enum = CandidateTypes.enumeration_begin(),
4886 EnumEnd = CandidateTypes.enumeration_end();
4887 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004888 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004889 CandidateSet);
4890 for (BuiltinCandidateTypeSet::iterator
4891 MemPtr = CandidateTypes.member_pointer_begin(),
4892 MemPtrEnd = CandidateTypes.member_pointer_end();
4893 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004894 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004895 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004896
4897 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004898
4899 case OO_PlusEqual:
4900 case OO_MinusEqual:
4901 // C++ [over.built]p19:
4902 //
4903 // For every pair (T, VQ), where T is any type and VQ is either
4904 // volatile or empty, there exist candidate operator functions
4905 // of the form
4906 //
4907 // T*VQ& operator=(T*VQ&, T*);
4908 //
4909 // C++ [over.built]p21:
4910 //
4911 // For every pair (T, VQ), where T is a cv-qualified or
4912 // cv-unqualified object type and VQ is either volatile or
4913 // empty, there exist candidate operator functions of the form
4914 //
4915 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4916 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4917 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4918 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4919 QualType ParamTypes[2];
4920 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4921
4922 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004923 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004924 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4925 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004926
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004927 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4928 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004929 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004930 ParamTypes[0]
4931 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004932 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4933 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004934 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004935 }
4936 // Fall through.
4937
4938 case OO_StarEqual:
4939 case OO_SlashEqual:
4940 // C++ [over.built]p18:
4941 //
4942 // For every triple (L, VQ, R), where L is an arithmetic type,
4943 // VQ is either volatile or empty, and R is a promoted
4944 // arithmetic type, there exist candidate operator functions of
4945 // the form
4946 //
4947 // VQ L& operator=(VQ L&, R);
4948 // VQ L& operator*=(VQ L&, R);
4949 // VQ L& operator/=(VQ L&, R);
4950 // VQ L& operator+=(VQ L&, R);
4951 // VQ L& operator-=(VQ L&, R);
4952 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004953 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004954 Right < LastPromotedArithmeticType; ++Right) {
4955 QualType ParamTypes[2];
4956 ParamTypes[1] = ArithmeticTypes[Right];
4957
4958 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004959 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004960 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4961 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004962
4963 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004964 if (VisibleTypeConversionsQuals.hasVolatile()) {
4965 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4966 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4967 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4968 /*IsAssigmentOperator=*/Op == OO_Equal);
4969 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004970 }
4971 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004972
4973 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4974 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4975 Vec1End = CandidateTypes.vector_end();
4976 Vec1 != Vec1End; ++Vec1)
4977 for (BuiltinCandidateTypeSet::iterator
4978 Vec2 = CandidateTypes.vector_begin(),
4979 Vec2End = CandidateTypes.vector_end();
4980 Vec2 != Vec2End; ++Vec2) {
4981 QualType ParamTypes[2];
4982 ParamTypes[1] = *Vec2;
4983 // Add this built-in operator as a candidate (VQ is empty).
4984 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4985 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4986 /*IsAssigmentOperator=*/Op == OO_Equal);
4987
4988 // Add this built-in operator as a candidate (VQ is 'volatile').
4989 if (VisibleTypeConversionsQuals.hasVolatile()) {
4990 ParamTypes[0] = Context.getVolatileType(*Vec1);
4991 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4992 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4993 /*IsAssigmentOperator=*/Op == OO_Equal);
4994 }
4995 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004996 break;
4997
4998 case OO_PercentEqual:
4999 case OO_LessLessEqual:
5000 case OO_GreaterGreaterEqual:
5001 case OO_AmpEqual:
5002 case OO_CaretEqual:
5003 case OO_PipeEqual:
5004 // C++ [over.built]p22:
5005 //
5006 // For every triple (L, VQ, R), where L is an integral type, VQ
5007 // is either volatile or empty, and R is a promoted integral
5008 // type, there exist candidate operator functions of the form
5009 //
5010 // VQ L& operator%=(VQ L&, R);
5011 // VQ L& operator<<=(VQ L&, R);
5012 // VQ L& operator>>=(VQ L&, R);
5013 // VQ L& operator&=(VQ L&, R);
5014 // VQ L& operator^=(VQ L&, R);
5015 // VQ L& operator|=(VQ L&, R);
5016 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005017 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005018 Right < LastPromotedIntegralType; ++Right) {
5019 QualType ParamTypes[2];
5020 ParamTypes[1] = ArithmeticTypes[Right];
5021
5022 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005023 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005024 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005025 if (VisibleTypeConversionsQuals.hasVolatile()) {
5026 // Add this built-in operator as a candidate (VQ is 'volatile').
5027 ParamTypes[0] = ArithmeticTypes[Left];
5028 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5029 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5030 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5031 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005032 }
5033 }
5034 break;
5035
Douglas Gregord08452f2008-11-19 15:42:04 +00005036 case OO_Exclaim: {
5037 // C++ [over.operator]p23:
5038 //
5039 // There also exist candidate operator functions of the form
5040 //
Mike Stump11289f42009-09-09 15:08:12 +00005041 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005042 // bool operator&&(bool, bool); [BELOW]
5043 // bool operator||(bool, bool); [BELOW]
5044 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005045 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5046 /*IsAssignmentOperator=*/false,
5047 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005048 break;
5049 }
5050
Douglas Gregora11693b2008-11-12 17:17:38 +00005051 case OO_AmpAmp:
5052 case OO_PipePipe: {
5053 // C++ [over.operator]p23:
5054 //
5055 // There also exist candidate operator functions of the form
5056 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005057 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005058 // bool operator&&(bool, bool);
5059 // bool operator||(bool, bool);
5060 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005061 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5062 /*IsAssignmentOperator=*/false,
5063 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005064 break;
5065 }
5066
5067 case OO_Subscript:
5068 // C++ [over.built]p13:
5069 //
5070 // For every cv-qualified or cv-unqualified object type T there
5071 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005072 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005073 // T* operator+(T*, ptrdiff_t); [ABOVE]
5074 // T& operator[](T*, ptrdiff_t);
5075 // T* operator-(T*, ptrdiff_t); [ABOVE]
5076 // T* operator+(ptrdiff_t, T*); [ABOVE]
5077 // T& operator[](ptrdiff_t, T*);
5078 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5079 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5080 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005081 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005082 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005083
5084 // T& operator[](T*, ptrdiff_t)
5085 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5086
5087 // T& operator[](ptrdiff_t, T*);
5088 ParamTypes[0] = ParamTypes[1];
5089 ParamTypes[1] = *Ptr;
5090 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005091 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005092 break;
5093
5094 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005095 // C++ [over.built]p11:
5096 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5097 // C1 is the same type as C2 or is a derived class of C2, T is an object
5098 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5099 // there exist candidate operator functions of the form
5100 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5101 // where CV12 is the union of CV1 and CV2.
5102 {
5103 for (BuiltinCandidateTypeSet::iterator Ptr =
5104 CandidateTypes.pointer_begin();
5105 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5106 QualType C1Ty = (*Ptr);
5107 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005108 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005109 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5110 if (!isa<RecordType>(C1))
5111 continue;
5112 // heuristic to reduce number of builtin candidates in the set.
5113 // Add volatile/restrict version only if there are conversions to a
5114 // volatile/restrict type.
5115 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5116 continue;
5117 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5118 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005119 for (BuiltinCandidateTypeSet::iterator
5120 MemPtr = CandidateTypes.member_pointer_begin(),
5121 MemPtrEnd = CandidateTypes.member_pointer_end();
5122 MemPtr != MemPtrEnd; ++MemPtr) {
5123 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5124 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005125 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005126 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5127 break;
5128 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5129 // build CV12 T&
5130 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005131 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5132 T.isVolatileQualified())
5133 continue;
5134 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5135 T.isRestrictQualified())
5136 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005137 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005138 QualType ResultTy = Context.getLValueReferenceType(T);
5139 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5140 }
5141 }
5142 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005143 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005144
5145 case OO_Conditional:
5146 // Note that we don't consider the first argument, since it has been
5147 // contextually converted to bool long ago. The candidates below are
5148 // therefore added as binary.
5149 //
5150 // C++ [over.built]p24:
5151 // For every type T, where T is a pointer or pointer-to-member type,
5152 // there exist candidate operator functions of the form
5153 //
5154 // T operator?(bool, T, T);
5155 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005156 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5157 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5158 QualType ParamTypes[2] = { *Ptr, *Ptr };
5159 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5160 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005161 for (BuiltinCandidateTypeSet::iterator Ptr =
5162 CandidateTypes.member_pointer_begin(),
5163 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5164 QualType ParamTypes[2] = { *Ptr, *Ptr };
5165 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5166 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005167 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005168 }
5169}
5170
Douglas Gregore254f902009-02-04 00:32:51 +00005171/// \brief Add function candidates found via argument-dependent lookup
5172/// to the set of overloading candidates.
5173///
5174/// This routine performs argument-dependent name lookup based on the
5175/// given function name (which may also be an operator name) and adds
5176/// all of the overload candidates found by ADL to the overload
5177/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005178void
Douglas Gregore254f902009-02-04 00:32:51 +00005179Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005180 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005181 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005182 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005183 OverloadCandidateSet& CandidateSet,
5184 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005185 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005186
John McCall91f61fc2010-01-26 06:04:06 +00005187 // FIXME: This approach for uniquing ADL results (and removing
5188 // redundant candidates from the set) relies on pointer-equality,
5189 // which means we need to key off the canonical decl. However,
5190 // always going back to the canonical decl might not get us the
5191 // right set of default arguments. What default arguments are
5192 // we supposed to consider on ADL candidates, anyway?
5193
Douglas Gregorcabea402009-09-22 15:41:20 +00005194 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005195 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005196
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005197 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005198 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5199 CandEnd = CandidateSet.end();
5200 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005201 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005202 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005203 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005204 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005205 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005206
5207 // For each of the ADL candidates we found, add it to the overload
5208 // set.
John McCall8fe68082010-01-26 07:16:45 +00005209 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005210 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005211 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005212 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005213 continue;
5214
John McCalla0296f72010-03-19 07:35:19 +00005215 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005216 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005217 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005218 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005219 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005220 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005221 }
Douglas Gregore254f902009-02-04 00:32:51 +00005222}
5223
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005224/// isBetterOverloadCandidate - Determines whether the first overload
5225/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005226bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005227Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00005228 const OverloadCandidate& Cand2,
5229 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005230 // Define viable functions to be better candidates than non-viable
5231 // functions.
5232 if (!Cand2.Viable)
5233 return Cand1.Viable;
5234 else if (!Cand1.Viable)
5235 return false;
5236
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005237 // C++ [over.match.best]p1:
5238 //
5239 // -- if F is a static member function, ICS1(F) is defined such
5240 // that ICS1(F) is neither better nor worse than ICS1(G) for
5241 // any function G, and, symmetrically, ICS1(G) is neither
5242 // better nor worse than ICS1(F).
5243 unsigned StartArg = 0;
5244 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5245 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005246
Douglas Gregord3cb3562009-07-07 23:38:56 +00005247 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005248 // A viable function F1 is defined to be a better function than another
5249 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005250 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005251 unsigned NumArgs = Cand1.Conversions.size();
5252 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5253 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005254 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005255 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5256 Cand2.Conversions[ArgIdx])) {
5257 case ImplicitConversionSequence::Better:
5258 // Cand1 has a better conversion sequence.
5259 HasBetterConversion = true;
5260 break;
5261
5262 case ImplicitConversionSequence::Worse:
5263 // Cand1 can't be better than Cand2.
5264 return false;
5265
5266 case ImplicitConversionSequence::Indistinguishable:
5267 // Do nothing.
5268 break;
5269 }
5270 }
5271
Mike Stump11289f42009-09-09 15:08:12 +00005272 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005273 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005274 if (HasBetterConversion)
5275 return true;
5276
Mike Stump11289f42009-09-09 15:08:12 +00005277 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005278 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005279 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005280 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5281 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005282
5283 // -- F1 and F2 are function template specializations, and the function
5284 // template for F1 is more specialized than the template for F2
5285 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005286 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005287 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5288 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005289 if (FunctionTemplateDecl *BetterTemplate
5290 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5291 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005292 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005293 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5294 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005295 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005296
Douglas Gregora1f013e2008-11-07 22:36:19 +00005297 // -- the context is an initialization by user-defined conversion
5298 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5299 // from the return type of F1 to the destination type (i.e.,
5300 // the type of the entity being initialized) is a better
5301 // conversion sequence than the standard conversion sequence
5302 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005303 if (Cand1.Function && Cand2.Function &&
5304 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005305 isa<CXXConversionDecl>(Cand2.Function)) {
5306 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5307 Cand2.FinalConversion)) {
5308 case ImplicitConversionSequence::Better:
5309 // Cand1 has a better conversion sequence.
5310 return true;
5311
5312 case ImplicitConversionSequence::Worse:
5313 // Cand1 can't be better than Cand2.
5314 return false;
5315
5316 case ImplicitConversionSequence::Indistinguishable:
5317 // Do nothing
5318 break;
5319 }
5320 }
5321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005322 return false;
5323}
5324
Mike Stump11289f42009-09-09 15:08:12 +00005325/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005326/// within an overload candidate set.
5327///
5328/// \param CandidateSet the set of candidate functions.
5329///
5330/// \param Loc the location of the function name (or operator symbol) for
5331/// which overload resolution occurs.
5332///
Mike Stump11289f42009-09-09 15:08:12 +00005333/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005334/// function, Best points to the candidate function found.
5335///
5336/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005337OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5338 SourceLocation Loc,
5339 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005340 // Find the best viable function.
5341 Best = CandidateSet.end();
5342 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5343 Cand != CandidateSet.end(); ++Cand) {
5344 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005345 if (Best == CandidateSet.end() ||
5346 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005347 Best = Cand;
5348 }
5349 }
5350
5351 // If we didn't find any viable functions, abort.
5352 if (Best == CandidateSet.end())
5353 return OR_No_Viable_Function;
5354
5355 // Make sure that this function is better than every other viable
5356 // function. If not, we have an ambiguity.
5357 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5358 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005359 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005360 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005361 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005362 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005363 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005364 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005365 }
Mike Stump11289f42009-09-09 15:08:12 +00005366
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005367 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005368 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005369 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005370 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005371 return OR_Deleted;
5372
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005373 // C++ [basic.def.odr]p2:
5374 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005375 // when referred to from a potentially-evaluated expression. [Note: this
5376 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005377 // (clause 13), user-defined conversions (12.3.2), allocation function for
5378 // placement new (5.3.4), as well as non-default initialization (8.5).
5379 if (Best->Function)
5380 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005381 return OR_Success;
5382}
5383
John McCall53262c92010-01-12 02:15:36 +00005384namespace {
5385
5386enum OverloadCandidateKind {
5387 oc_function,
5388 oc_method,
5389 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005390 oc_function_template,
5391 oc_method_template,
5392 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005393 oc_implicit_default_constructor,
5394 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005395 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005396};
5397
John McCalle1ac8d12010-01-13 00:25:19 +00005398OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5399 FunctionDecl *Fn,
5400 std::string &Description) {
5401 bool isTemplate = false;
5402
5403 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5404 isTemplate = true;
5405 Description = S.getTemplateArgumentBindingsText(
5406 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5407 }
John McCallfd0b2f82010-01-06 09:43:14 +00005408
5409 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005410 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005411 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005412
John McCall53262c92010-01-12 02:15:36 +00005413 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5414 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005415 }
5416
5417 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5418 // This actually gets spelled 'candidate function' for now, but
5419 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005420 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005421 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005422
5423 assert(Meth->isCopyAssignment()
5424 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005425 return oc_implicit_copy_assignment;
5426 }
5427
John McCalle1ac8d12010-01-13 00:25:19 +00005428 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005429}
5430
5431} // end anonymous namespace
5432
5433// Notes the location of an overload candidate.
5434void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005435 std::string FnDesc;
5436 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5437 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5438 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005439}
5440
John McCall0d1da222010-01-12 00:44:57 +00005441/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5442/// "lead" diagnostic; it will be given two arguments, the source and
5443/// target types of the conversion.
5444void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5445 SourceLocation CaretLoc,
5446 const PartialDiagnostic &PDiag) {
5447 Diag(CaretLoc, PDiag)
5448 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5449 for (AmbiguousConversionSequence::const_iterator
5450 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5451 NoteOverloadCandidate(*I);
5452 }
John McCall12f97bc2010-01-08 04:41:39 +00005453}
5454
John McCall0d1da222010-01-12 00:44:57 +00005455namespace {
5456
John McCall6a61b522010-01-13 09:16:55 +00005457void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5458 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5459 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005460 assert(Cand->Function && "for now, candidate must be a function");
5461 FunctionDecl *Fn = Cand->Function;
5462
5463 // There's a conversion slot for the object argument if this is a
5464 // non-constructor method. Note that 'I' corresponds the
5465 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005466 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005467 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005468 if (I == 0)
5469 isObjectArgument = true;
5470 else
5471 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005472 }
5473
John McCalle1ac8d12010-01-13 00:25:19 +00005474 std::string FnDesc;
5475 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5476
John McCall6a61b522010-01-13 09:16:55 +00005477 Expr *FromExpr = Conv.Bad.FromExpr;
5478 QualType FromTy = Conv.Bad.getFromType();
5479 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005480
John McCallfb7ad0f2010-02-02 02:42:52 +00005481 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005482 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005483 Expr *E = FromExpr->IgnoreParens();
5484 if (isa<UnaryOperator>(E))
5485 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005486 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005487
5488 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5489 << (unsigned) FnKind << FnDesc
5490 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5491 << ToTy << Name << I+1;
5492 return;
5493 }
5494
John McCall6d174642010-01-23 08:10:49 +00005495 // Do some hand-waving analysis to see if the non-viability is due
5496 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005497 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5498 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5499 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5500 CToTy = RT->getPointeeType();
5501 else {
5502 // TODO: detect and diagnose the full richness of const mismatches.
5503 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5504 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5505 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5506 }
5507
5508 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5509 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5510 // It is dumb that we have to do this here.
5511 while (isa<ArrayType>(CFromTy))
5512 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5513 while (isa<ArrayType>(CToTy))
5514 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5515
5516 Qualifiers FromQs = CFromTy.getQualifiers();
5517 Qualifiers ToQs = CToTy.getQualifiers();
5518
5519 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5520 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5521 << (unsigned) FnKind << FnDesc
5522 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5523 << FromTy
5524 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5525 << (unsigned) isObjectArgument << I+1;
5526 return;
5527 }
5528
5529 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5530 assert(CVR && "unexpected qualifiers mismatch");
5531
5532 if (isObjectArgument) {
5533 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5534 << (unsigned) FnKind << FnDesc
5535 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5536 << FromTy << (CVR - 1);
5537 } else {
5538 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5539 << (unsigned) FnKind << FnDesc
5540 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5541 << FromTy << (CVR - 1) << I+1;
5542 }
5543 return;
5544 }
5545
John McCall6d174642010-01-23 08:10:49 +00005546 // Diagnose references or pointers to incomplete types differently,
5547 // since it's far from impossible that the incompleteness triggered
5548 // the failure.
5549 QualType TempFromTy = FromTy.getNonReferenceType();
5550 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5551 TempFromTy = PTy->getPointeeType();
5552 if (TempFromTy->isIncompleteType()) {
5553 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5554 << (unsigned) FnKind << FnDesc
5555 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5556 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5557 return;
5558 }
5559
Douglas Gregor56f2e342010-06-30 23:01:39 +00005560 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005561 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005562 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5563 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5564 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5565 FromPtrTy->getPointeeType()) &&
5566 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5567 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5568 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5569 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005570 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005571 }
5572 } else if (const ObjCObjectPointerType *FromPtrTy
5573 = FromTy->getAs<ObjCObjectPointerType>()) {
5574 if (const ObjCObjectPointerType *ToPtrTy
5575 = ToTy->getAs<ObjCObjectPointerType>())
5576 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5577 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5578 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5579 FromPtrTy->getPointeeType()) &&
5580 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005581 BaseToDerivedConversion = 2;
5582 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5583 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5584 !FromTy->isIncompleteType() &&
5585 !ToRefTy->getPointeeType()->isIncompleteType() &&
5586 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5587 BaseToDerivedConversion = 3;
5588 }
5589
5590 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005591 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005592 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005593 << (unsigned) FnKind << FnDesc
5594 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005595 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005596 << FromTy << ToTy << I+1;
5597 return;
5598 }
5599
John McCall47000992010-01-14 03:28:57 +00005600 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005601 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5602 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005603 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005604 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005605}
5606
5607void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5608 unsigned NumFormalArgs) {
5609 // TODO: treat calls to a missing default constructor as a special case
5610
5611 FunctionDecl *Fn = Cand->Function;
5612 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5613
5614 unsigned MinParams = Fn->getMinRequiredArguments();
5615
5616 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005617 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005618 unsigned mode, modeCount;
5619 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005620 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5621 (Cand->FailureKind == ovl_fail_bad_deduction &&
5622 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005623 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5624 mode = 0; // "at least"
5625 else
5626 mode = 2; // "exactly"
5627 modeCount = MinParams;
5628 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005629 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5630 (Cand->FailureKind == ovl_fail_bad_deduction &&
5631 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005632 if (MinParams != FnTy->getNumArgs())
5633 mode = 1; // "at most"
5634 else
5635 mode = 2; // "exactly"
5636 modeCount = FnTy->getNumArgs();
5637 }
5638
5639 std::string Description;
5640 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5641
5642 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005643 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5644 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005645}
5646
John McCall8b9ed552010-02-01 18:53:26 +00005647/// Diagnose a failed template-argument deduction.
5648void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5649 Expr **Args, unsigned NumArgs) {
5650 FunctionDecl *Fn = Cand->Function; // pattern
5651
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005652 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005653 NamedDecl *ParamD;
5654 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5655 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5656 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005657 switch (Cand->DeductionFailure.Result) {
5658 case Sema::TDK_Success:
5659 llvm_unreachable("TDK_success while diagnosing bad deduction");
5660
5661 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005662 assert(ParamD && "no parameter found for incomplete deduction result");
5663 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5664 << ParamD->getDeclName();
5665 return;
5666 }
5667
John McCall42d7d192010-08-05 09:05:08 +00005668 case Sema::TDK_Underqualified: {
5669 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5670 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5671
5672 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5673
5674 // Param will have been canonicalized, but it should just be a
5675 // qualified version of ParamD, so move the qualifiers to that.
5676 QualifierCollector Qs(S.Context);
5677 Qs.strip(Param);
5678 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5679 assert(S.Context.hasSameType(Param, NonCanonParam));
5680
5681 // Arg has also been canonicalized, but there's nothing we can do
5682 // about that. It also doesn't matter as much, because it won't
5683 // have any template parameters in it (because deduction isn't
5684 // done on dependent types).
5685 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5686
5687 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5688 << ParamD->getDeclName() << Arg << NonCanonParam;
5689 return;
5690 }
5691
5692 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005693 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005694 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005695 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005696 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005697 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005698 which = 1;
5699 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005700 which = 2;
5701 }
5702
5703 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5704 << which << ParamD->getDeclName()
5705 << *Cand->DeductionFailure.getFirstArg()
5706 << *Cand->DeductionFailure.getSecondArg();
5707 return;
5708 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005709
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005710 case Sema::TDK_InvalidExplicitArguments:
5711 assert(ParamD && "no parameter found for invalid explicit arguments");
5712 if (ParamD->getDeclName())
5713 S.Diag(Fn->getLocation(),
5714 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5715 << ParamD->getDeclName();
5716 else {
5717 int index = 0;
5718 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5719 index = TTP->getIndex();
5720 else if (NonTypeTemplateParmDecl *NTTP
5721 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5722 index = NTTP->getIndex();
5723 else
5724 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5725 S.Diag(Fn->getLocation(),
5726 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5727 << (index + 1);
5728 }
5729 return;
5730
Douglas Gregor02eb4832010-05-08 18:13:28 +00005731 case Sema::TDK_TooManyArguments:
5732 case Sema::TDK_TooFewArguments:
5733 DiagnoseArityMismatch(S, Cand, NumArgs);
5734 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005735
5736 case Sema::TDK_InstantiationDepth:
5737 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5738 return;
5739
5740 case Sema::TDK_SubstitutionFailure: {
5741 std::string ArgString;
5742 if (TemplateArgumentList *Args
5743 = Cand->DeductionFailure.getTemplateArgumentList())
5744 ArgString = S.getTemplateArgumentBindingsText(
5745 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5746 *Args);
5747 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5748 << ArgString;
5749 return;
5750 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005751
John McCall8b9ed552010-02-01 18:53:26 +00005752 // TODO: diagnose these individually, then kill off
5753 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005754 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005755 case Sema::TDK_FailedOverloadResolution:
5756 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5757 return;
5758 }
5759}
5760
5761/// Generates a 'note' diagnostic for an overload candidate. We've
5762/// already generated a primary error at the call site.
5763///
5764/// It really does need to be a single diagnostic with its caret
5765/// pointed at the candidate declaration. Yes, this creates some
5766/// major challenges of technical writing. Yes, this makes pointing
5767/// out problems with specific arguments quite awkward. It's still
5768/// better than generating twenty screens of text for every failed
5769/// overload.
5770///
5771/// It would be great to be able to express per-candidate problems
5772/// more richly for those diagnostic clients that cared, but we'd
5773/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005774void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5775 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005776 FunctionDecl *Fn = Cand->Function;
5777
John McCall12f97bc2010-01-08 04:41:39 +00005778 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005779 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005780 std::string FnDesc;
5781 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005782
5783 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005784 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005785 return;
John McCall12f97bc2010-01-08 04:41:39 +00005786 }
5787
John McCalle1ac8d12010-01-13 00:25:19 +00005788 // We don't really have anything else to say about viable candidates.
5789 if (Cand->Viable) {
5790 S.NoteOverloadCandidate(Fn);
5791 return;
5792 }
John McCall0d1da222010-01-12 00:44:57 +00005793
John McCall6a61b522010-01-13 09:16:55 +00005794 switch (Cand->FailureKind) {
5795 case ovl_fail_too_many_arguments:
5796 case ovl_fail_too_few_arguments:
5797 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005798
John McCall6a61b522010-01-13 09:16:55 +00005799 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005800 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5801
John McCallfe796dd2010-01-23 05:17:32 +00005802 case ovl_fail_trivial_conversion:
5803 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005804 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005805 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005806
John McCall65eb8792010-02-25 01:37:24 +00005807 case ovl_fail_bad_conversion: {
5808 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5809 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005810 if (Cand->Conversions[I].isBad())
5811 return DiagnoseBadConversion(S, Cand, I);
5812
5813 // FIXME: this currently happens when we're called from SemaInit
5814 // when user-conversion overload fails. Figure out how to handle
5815 // those conditions and diagnose them well.
5816 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005817 }
John McCall65eb8792010-02-25 01:37:24 +00005818 }
John McCalld3224162010-01-08 00:58:21 +00005819}
5820
5821void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5822 // Desugar the type of the surrogate down to a function type,
5823 // retaining as many typedefs as possible while still showing
5824 // the function type (and, therefore, its parameter types).
5825 QualType FnType = Cand->Surrogate->getConversionType();
5826 bool isLValueReference = false;
5827 bool isRValueReference = false;
5828 bool isPointer = false;
5829 if (const LValueReferenceType *FnTypeRef =
5830 FnType->getAs<LValueReferenceType>()) {
5831 FnType = FnTypeRef->getPointeeType();
5832 isLValueReference = true;
5833 } else if (const RValueReferenceType *FnTypeRef =
5834 FnType->getAs<RValueReferenceType>()) {
5835 FnType = FnTypeRef->getPointeeType();
5836 isRValueReference = true;
5837 }
5838 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5839 FnType = FnTypePtr->getPointeeType();
5840 isPointer = true;
5841 }
5842 // Desugar down to a function type.
5843 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5844 // Reconstruct the pointer/reference as appropriate.
5845 if (isPointer) FnType = S.Context.getPointerType(FnType);
5846 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5847 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5848
5849 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5850 << FnType;
5851}
5852
5853void NoteBuiltinOperatorCandidate(Sema &S,
5854 const char *Opc,
5855 SourceLocation OpLoc,
5856 OverloadCandidate *Cand) {
5857 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5858 std::string TypeStr("operator");
5859 TypeStr += Opc;
5860 TypeStr += "(";
5861 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5862 if (Cand->Conversions.size() == 1) {
5863 TypeStr += ")";
5864 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5865 } else {
5866 TypeStr += ", ";
5867 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5868 TypeStr += ")";
5869 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5870 }
5871}
5872
5873void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5874 OverloadCandidate *Cand) {
5875 unsigned NoOperands = Cand->Conversions.size();
5876 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5877 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005878 if (ICS.isBad()) break; // all meaningless after first invalid
5879 if (!ICS.isAmbiguous()) continue;
5880
5881 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005882 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005883 }
5884}
5885
John McCall3712d9e2010-01-15 23:32:50 +00005886SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5887 if (Cand->Function)
5888 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005889 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005890 return Cand->Surrogate->getLocation();
5891 return SourceLocation();
5892}
5893
John McCallad2587a2010-01-12 00:48:53 +00005894struct CompareOverloadCandidatesForDisplay {
5895 Sema &S;
5896 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005897
5898 bool operator()(const OverloadCandidate *L,
5899 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005900 // Fast-path this check.
5901 if (L == R) return false;
5902
John McCall12f97bc2010-01-08 04:41:39 +00005903 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005904 if (L->Viable) {
5905 if (!R->Viable) return true;
5906
5907 // TODO: introduce a tri-valued comparison for overload
5908 // candidates. Would be more worthwhile if we had a sort
5909 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005910 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5911 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005912 } else if (R->Viable)
5913 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005914
John McCall3712d9e2010-01-15 23:32:50 +00005915 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005916
John McCall3712d9e2010-01-15 23:32:50 +00005917 // Criteria by which we can sort non-viable candidates:
5918 if (!L->Viable) {
5919 // 1. Arity mismatches come after other candidates.
5920 if (L->FailureKind == ovl_fail_too_many_arguments ||
5921 L->FailureKind == ovl_fail_too_few_arguments)
5922 return false;
5923 if (R->FailureKind == ovl_fail_too_many_arguments ||
5924 R->FailureKind == ovl_fail_too_few_arguments)
5925 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005926
John McCallfe796dd2010-01-23 05:17:32 +00005927 // 2. Bad conversions come first and are ordered by the number
5928 // of bad conversions and quality of good conversions.
5929 if (L->FailureKind == ovl_fail_bad_conversion) {
5930 if (R->FailureKind != ovl_fail_bad_conversion)
5931 return true;
5932
5933 // If there's any ordering between the defined conversions...
5934 // FIXME: this might not be transitive.
5935 assert(L->Conversions.size() == R->Conversions.size());
5936
5937 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005938 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5939 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005940 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5941 R->Conversions[I])) {
5942 case ImplicitConversionSequence::Better:
5943 leftBetter++;
5944 break;
5945
5946 case ImplicitConversionSequence::Worse:
5947 leftBetter--;
5948 break;
5949
5950 case ImplicitConversionSequence::Indistinguishable:
5951 break;
5952 }
5953 }
5954 if (leftBetter > 0) return true;
5955 if (leftBetter < 0) return false;
5956
5957 } else if (R->FailureKind == ovl_fail_bad_conversion)
5958 return false;
5959
John McCall3712d9e2010-01-15 23:32:50 +00005960 // TODO: others?
5961 }
5962
5963 // Sort everything else by location.
5964 SourceLocation LLoc = GetLocationForCandidate(L);
5965 SourceLocation RLoc = GetLocationForCandidate(R);
5966
5967 // Put candidates without locations (e.g. builtins) at the end.
5968 if (LLoc.isInvalid()) return false;
5969 if (RLoc.isInvalid()) return true;
5970
5971 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005972 }
5973};
5974
John McCallfe796dd2010-01-23 05:17:32 +00005975/// CompleteNonViableCandidate - Normally, overload resolution only
5976/// computes up to the first
5977void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5978 Expr **Args, unsigned NumArgs) {
5979 assert(!Cand->Viable);
5980
5981 // Don't do anything on failures other than bad conversion.
5982 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5983
5984 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005985 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005986 unsigned ConvCount = Cand->Conversions.size();
5987 while (true) {
5988 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5989 ConvIdx++;
5990 if (Cand->Conversions[ConvIdx - 1].isBad())
5991 break;
5992 }
5993
5994 if (ConvIdx == ConvCount)
5995 return;
5996
John McCall65eb8792010-02-25 01:37:24 +00005997 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5998 "remaining conversion is initialized?");
5999
Douglas Gregoradc7a702010-04-16 17:45:54 +00006000 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006001 // operation somehow.
6002 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006003
6004 const FunctionProtoType* Proto;
6005 unsigned ArgIdx = ConvIdx;
6006
6007 if (Cand->IsSurrogate) {
6008 QualType ConvType
6009 = Cand->Surrogate->getConversionType().getNonReferenceType();
6010 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6011 ConvType = ConvPtrType->getPointeeType();
6012 Proto = ConvType->getAs<FunctionProtoType>();
6013 ArgIdx--;
6014 } else if (Cand->Function) {
6015 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6016 if (isa<CXXMethodDecl>(Cand->Function) &&
6017 !isa<CXXConstructorDecl>(Cand->Function))
6018 ArgIdx--;
6019 } else {
6020 // Builtin binary operator with a bad first conversion.
6021 assert(ConvCount <= 3);
6022 for (; ConvIdx != ConvCount; ++ConvIdx)
6023 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006024 = TryCopyInitialization(S, Args[ConvIdx],
6025 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6026 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006027 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006028 return;
6029 }
6030
6031 // Fill in the rest of the conversions.
6032 unsigned NumArgsInProto = Proto->getNumArgs();
6033 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6034 if (ArgIdx < NumArgsInProto)
6035 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006036 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6037 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006038 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006039 else
6040 Cand->Conversions[ConvIdx].setEllipsis();
6041 }
6042}
6043
John McCalld3224162010-01-08 00:58:21 +00006044} // end anonymous namespace
6045
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006046/// PrintOverloadCandidates - When overload resolution fails, prints
6047/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006048/// set.
Mike Stump11289f42009-09-09 15:08:12 +00006049void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006050Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00006051 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00006052 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006053 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00006054 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006055 // Sort the candidates by viability and position. Sorting directly would
6056 // be prohibitive, so we make a set of pointers and sort those.
6057 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6058 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
6059 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6060 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00006061 Cand != LastCand; ++Cand) {
6062 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006063 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006064 else if (OCD == OCD_AllCandidates) {
6065 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006066 if (Cand->Function || Cand->IsSurrogate)
6067 Cands.push_back(Cand);
6068 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6069 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006070 }
6071 }
6072
John McCallad2587a2010-01-12 00:48:53 +00006073 std::sort(Cands.begin(), Cands.end(),
6074 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00006075
John McCall0d1da222010-01-12 00:44:57 +00006076 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006077
John McCall12f97bc2010-01-08 04:41:39 +00006078 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006079 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6080 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006081 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6082 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006083
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006084 // Set an arbitrary limit on the number of candidate functions we'll spam
6085 // the user with. FIXME: This limit should depend on details of the
6086 // candidate list.
6087 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6088 break;
6089 }
6090 ++CandsShown;
6091
John McCalld3224162010-01-08 00:58:21 +00006092 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00006093 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006094 else if (Cand->IsSurrogate)
6095 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006096 else {
6097 assert(Cand->Viable &&
6098 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006099 // Generally we only see ambiguities including viable builtin
6100 // operators if overload resolution got screwed up by an
6101 // ambiguous user-defined conversion.
6102 //
6103 // FIXME: It's quite possible for different conversions to see
6104 // different ambiguities, though.
6105 if (!ReportedAmbiguousConversions) {
6106 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6107 ReportedAmbiguousConversions = true;
6108 }
John McCalld3224162010-01-08 00:58:21 +00006109
John McCall0d1da222010-01-12 00:44:57 +00006110 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00006111 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006112 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006113 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006114
6115 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00006116 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006117}
6118
John McCalla0296f72010-03-19 07:35:19 +00006119static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006120 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006121 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006122
John McCalla0296f72010-03-19 07:35:19 +00006123 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006124}
6125
Douglas Gregorcd695e52008-11-10 20:40:00 +00006126/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6127/// an overloaded function (C++ [over.over]), where @p From is an
6128/// expression with overloaded function type and @p ToType is the type
6129/// we're trying to resolve to. For example:
6130///
6131/// @code
6132/// int f(double);
6133/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006134///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006135/// int (*pfd)(double) = f; // selects f(double)
6136/// @endcode
6137///
6138/// This routine returns the resulting FunctionDecl if it could be
6139/// resolved, and NULL otherwise. When @p Complain is true, this
6140/// routine will emit diagnostics if there is an error.
6141FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006142Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006143 bool Complain,
6144 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006145 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006146 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006147 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006148 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006149 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006150 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006151 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006152 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006153 FunctionType = MemTypePtr->getPointeeType();
6154 IsMember = true;
6155 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006156
Douglas Gregorcd695e52008-11-10 20:40:00 +00006157 // C++ [over.over]p1:
6158 // [...] [Note: any redundant set of parentheses surrounding the
6159 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006160 // C++ [over.over]p1:
6161 // [...] The overloaded function name can be preceded by the &
6162 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006163 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6164 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6165 if (OvlExpr->hasExplicitTemplateArgs()) {
6166 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6167 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006168 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00006169
6170 // We expect a pointer or reference to function, or a function pointer.
6171 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6172 if (!FunctionType->isFunctionType()) {
6173 if (Complain)
6174 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6175 << OvlExpr->getName() << ToType;
6176
6177 return 0;
6178 }
6179
6180 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006181
Douglas Gregorcd695e52008-11-10 20:40:00 +00006182 // Look through all of the overloaded functions, searching for one
6183 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006184 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006185 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6186
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006187 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006188 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6189 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006190 // Look through any using declarations to find the underlying function.
6191 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6192
Douglas Gregorcd695e52008-11-10 20:40:00 +00006193 // C++ [over.over]p3:
6194 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006195 // targets of type "pointer-to-function" or "reference-to-function."
6196 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006197 // type "pointer-to-member-function."
6198 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006199
Mike Stump11289f42009-09-09 15:08:12 +00006200 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006201 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006202 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006203 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006204 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006205 // static when converting to member pointer.
6206 if (Method->isStatic() == IsMember)
6207 continue;
6208 } else if (IsMember)
6209 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006210
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006211 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006212 // If the name is a function template, template argument deduction is
6213 // done (14.8.2.2), and if the argument deduction succeeds, the
6214 // resulting template argument list is used to generate a single
6215 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006216 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006217 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006218 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006219 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006220 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006221 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006222 FunctionType, Specialization, Info)) {
6223 // FIXME: make a note of the failed deduction for diagnostics.
6224 (void)Result;
6225 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006226 // FIXME: If the match isn't exact, shouldn't we just drop this as
6227 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006228 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006229 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006230 Matches.push_back(std::make_pair(I.getPair(),
6231 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006232 }
John McCalld14a8642009-11-21 08:51:07 +00006233
6234 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006235 }
Mike Stump11289f42009-09-09 15:08:12 +00006236
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006237 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006238 // Skip non-static functions when converting to pointer, and static
6239 // when converting to member pointer.
6240 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006241 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006242
6243 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006244 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006245 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006246 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006247 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006248
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006249 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006250 QualType ResultTy;
6251 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6252 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6253 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006254 Matches.push_back(std::make_pair(I.getPair(),
6255 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006256 FoundNonTemplateFunction = true;
6257 }
Mike Stump11289f42009-09-09 15:08:12 +00006258 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006259 }
6260
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006261 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006262 if (Matches.empty()) {
6263 if (Complain) {
6264 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6265 << OvlExpr->getName() << FunctionType;
6266 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6267 E = OvlExpr->decls_end();
6268 I != E; ++I)
6269 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6270 NoteOverloadCandidate(F);
6271 }
6272
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006273 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006274 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006275 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006276 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006277 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006278 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006279 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006280 return Result;
6281 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006282
6283 // C++ [over.over]p4:
6284 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006285 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006286 // [...] and any given function template specialization F1 is
6287 // eliminated if the set contains a second function template
6288 // specialization whose function template is more specialized
6289 // than the function template of F1 according to the partial
6290 // ordering rules of 14.5.5.2.
6291
6292 // The algorithm specified above is quadratic. We instead use a
6293 // two-pass algorithm (similar to the one used to identify the
6294 // best viable function in an overload set) that identifies the
6295 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006296
6297 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6298 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6299 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006300
6301 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006302 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006303 TPOC_Other, From->getLocStart(),
6304 PDiag(),
6305 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006306 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006307 PDiag(diag::note_ovl_candidate)
6308 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006309 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006310 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006311 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006312 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006313 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006314 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6315 }
John McCall58cc69d2010-01-27 01:50:18 +00006316 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006317 }
Mike Stump11289f42009-09-09 15:08:12 +00006318
Douglas Gregorfae1d712009-09-26 03:56:17 +00006319 // [...] any function template specializations in the set are
6320 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006321 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006322 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006323 ++I;
6324 else {
John McCalla0296f72010-03-19 07:35:19 +00006325 Matches[I] = Matches[--N];
6326 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006327 }
6328 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006329
Mike Stump11289f42009-09-09 15:08:12 +00006330 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006331 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006332 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006333 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006334 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006335 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006336 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006337 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6338 }
John McCalla0296f72010-03-19 07:35:19 +00006339 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006340 }
Mike Stump11289f42009-09-09 15:08:12 +00006341
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006342 // FIXME: We should probably return the same thing that BestViableFunction
6343 // returns (even if we issue the diagnostics here).
6344 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006345 << Matches[0].second->getDeclName();
6346 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6347 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006348 return 0;
6349}
6350
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006351/// \brief Given an expression that refers to an overloaded function, try to
6352/// resolve that overloaded function expression down to a single function.
6353///
6354/// This routine can only resolve template-ids that refer to a single function
6355/// template, where that template-id refers to a single template whose template
6356/// arguments are either provided by the template-id or have defaults,
6357/// as described in C++0x [temp.arg.explicit]p3.
6358FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6359 // C++ [over.over]p1:
6360 // [...] [Note: any redundant set of parentheses surrounding the
6361 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006362 // C++ [over.over]p1:
6363 // [...] The overloaded function name can be preceded by the &
6364 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006365
6366 if (From->getType() != Context.OverloadTy)
6367 return 0;
6368
6369 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006370
6371 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006372 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006373 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006374
6375 TemplateArgumentListInfo ExplicitTemplateArgs;
6376 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006377
6378 // Look through all of the overloaded functions, searching for one
6379 // whose type matches exactly.
6380 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006381 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6382 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006383 // C++0x [temp.arg.explicit]p3:
6384 // [...] In contexts where deduction is done and fails, or in contexts
6385 // where deduction is not done, if a template argument list is
6386 // specified and it, along with any default template arguments,
6387 // identifies a single function template specialization, then the
6388 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006389 FunctionTemplateDecl *FunctionTemplate
6390 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006391
6392 // C++ [over.over]p2:
6393 // If the name is a function template, template argument deduction is
6394 // done (14.8.2.2), and if the argument deduction succeeds, the
6395 // resulting template argument list is used to generate a single
6396 // function template specialization, which is added to the set of
6397 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006398 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006399 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006400 if (TemplateDeductionResult Result
6401 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6402 Specialization, Info)) {
6403 // FIXME: make a note of the failed deduction for diagnostics.
6404 (void)Result;
6405 continue;
6406 }
6407
6408 // Multiple matches; we can't resolve to a single declaration.
6409 if (Matched)
6410 return 0;
6411
6412 Matched = Specialization;
6413 }
6414
6415 return Matched;
6416}
6417
Douglas Gregorcabea402009-09-22 15:41:20 +00006418/// \brief Add a single candidate to the overload set.
6419static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006420 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006421 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006422 Expr **Args, unsigned NumArgs,
6423 OverloadCandidateSet &CandidateSet,
6424 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006425 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006426 if (isa<UsingShadowDecl>(Callee))
6427 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6428
Douglas Gregorcabea402009-09-22 15:41:20 +00006429 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006430 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006431 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006432 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006433 return;
John McCalld14a8642009-11-21 08:51:07 +00006434 }
6435
6436 if (FunctionTemplateDecl *FuncTemplate
6437 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006438 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6439 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006440 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006441 return;
6442 }
6443
6444 assert(false && "unhandled case in overloaded call candidate");
6445
6446 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006447}
6448
6449/// \brief Add the overload candidates named by callee and/or found by argument
6450/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006451void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006452 Expr **Args, unsigned NumArgs,
6453 OverloadCandidateSet &CandidateSet,
6454 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006455
6456#ifndef NDEBUG
6457 // Verify that ArgumentDependentLookup is consistent with the rules
6458 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006459 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006460 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6461 // and let Y be the lookup set produced by argument dependent
6462 // lookup (defined as follows). If X contains
6463 //
6464 // -- a declaration of a class member, or
6465 //
6466 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006467 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006468 //
6469 // -- a declaration that is neither a function or a function
6470 // template
6471 //
6472 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006473
John McCall57500772009-12-16 12:17:52 +00006474 if (ULE->requiresADL()) {
6475 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6476 E = ULE->decls_end(); I != E; ++I) {
6477 assert(!(*I)->getDeclContext()->isRecord());
6478 assert(isa<UsingShadowDecl>(*I) ||
6479 !(*I)->getDeclContext()->isFunctionOrMethod());
6480 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006481 }
6482 }
6483#endif
6484
John McCall57500772009-12-16 12:17:52 +00006485 // It would be nice to avoid this copy.
6486 TemplateArgumentListInfo TABuffer;
6487 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6488 if (ULE->hasExplicitTemplateArgs()) {
6489 ULE->copyTemplateArgumentsInto(TABuffer);
6490 ExplicitTemplateArgs = &TABuffer;
6491 }
6492
6493 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6494 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006495 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006496 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006497 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006498
John McCall57500772009-12-16 12:17:52 +00006499 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006500 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6501 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006502 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006503 CandidateSet,
6504 PartialOverloading);
6505}
John McCalld681c392009-12-16 08:11:27 +00006506
6507/// Attempts to recover from a call where no functions were found.
6508///
6509/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006510static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006511BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006512 UnresolvedLookupExpr *ULE,
6513 SourceLocation LParenLoc,
6514 Expr **Args, unsigned NumArgs,
6515 SourceLocation *CommaLocs,
6516 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006517
6518 CXXScopeSpec SS;
6519 if (ULE->getQualifier()) {
6520 SS.setScopeRep(ULE->getQualifier());
6521 SS.setRange(ULE->getQualifierRange());
6522 }
6523
John McCall57500772009-12-16 12:17:52 +00006524 TemplateArgumentListInfo TABuffer;
6525 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6526 if (ULE->hasExplicitTemplateArgs()) {
6527 ULE->copyTemplateArgumentsInto(TABuffer);
6528 ExplicitTemplateArgs = &TABuffer;
6529 }
6530
John McCalld681c392009-12-16 08:11:27 +00006531 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6532 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006533 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorb412e172010-07-25 18:17:45 +00006534 return SemaRef.ExprError();
John McCalld681c392009-12-16 08:11:27 +00006535
John McCall57500772009-12-16 12:17:52 +00006536 assert(!R.empty() && "lookup results empty despite recovery");
6537
6538 // Build an implicit member call if appropriate. Just drop the
6539 // casts and such from the call, we don't really care.
John McCalldadc5752010-08-24 06:29:42 +00006540 ExprResult NewFn = SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006541 if ((*R.begin())->isCXXClassMember())
6542 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6543 else if (ExplicitTemplateArgs)
6544 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6545 else
6546 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6547
6548 if (NewFn.isInvalid())
Douglas Gregorb412e172010-07-25 18:17:45 +00006549 return SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006550
6551 // This shouldn't cause an infinite loop because we're giving it
6552 // an expression with non-empty lookup results, which should never
6553 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006554 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
John McCall37ad5512010-08-23 06:44:23 +00006555 Sema::MultiExprArg(SemaRef, Args, NumArgs),
John McCall57500772009-12-16 12:17:52 +00006556 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006557}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006558
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006559/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006560/// (which eventually refers to the declaration Func) and the call
6561/// arguments Args/NumArgs, attempt to resolve the function call down
6562/// to a specific function. If overload resolution succeeds, returns
6563/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006564/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006565/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006566ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006567Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006568 SourceLocation LParenLoc,
6569 Expr **Args, unsigned NumArgs,
6570 SourceLocation *CommaLocs,
6571 SourceLocation RParenLoc) {
6572#ifndef NDEBUG
6573 if (ULE->requiresADL()) {
6574 // To do ADL, we must have found an unqualified name.
6575 assert(!ULE->getQualifier() && "qualified name with ADL");
6576
6577 // We don't perform ADL for implicit declarations of builtins.
6578 // Verify that this was correctly set up.
6579 FunctionDecl *F;
6580 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6581 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6582 F->getBuiltinID() && F->isImplicit())
6583 assert(0 && "performing ADL for builtin");
6584
6585 // We don't perform ADL in C.
6586 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6587 }
6588#endif
6589
John McCallbc077cf2010-02-08 23:07:23 +00006590 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006591
John McCall57500772009-12-16 12:17:52 +00006592 // Add the functions denoted by the callee to the set of candidate
6593 // functions, including those from argument-dependent lookup.
6594 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006595
6596 // If we found nothing, try to recover.
6597 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6598 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006599 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006600 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006601 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006602
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006603 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006604 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006605 case OR_Success: {
6606 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006607 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006608 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006609 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006610 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6611 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006612
6613 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006614 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006615 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006616 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006617 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006618 break;
6619
6620 case OR_Ambiguous:
6621 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006622 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006623 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006624 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006625
6626 case OR_Deleted:
6627 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6628 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006629 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006630 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006631 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006632 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006633 }
6634
Douglas Gregorb412e172010-07-25 18:17:45 +00006635 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006636 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006637}
6638
John McCall4c4c1df2010-01-26 03:27:55 +00006639static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006640 return Functions.size() > 1 ||
6641 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6642}
6643
Douglas Gregor084d8552009-03-13 23:49:33 +00006644/// \brief Create a unary operation that may resolve to an overloaded
6645/// operator.
6646///
6647/// \param OpLoc The location of the operator itself (e.g., '*').
6648///
6649/// \param OpcIn The UnaryOperator::Opcode that describes this
6650/// operator.
6651///
6652/// \param Functions The set of non-member functions that will be
6653/// considered by overload resolution. The caller needs to build this
6654/// set based on the context using, e.g.,
6655/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6656/// set should not contain any member functions; those will be added
6657/// by CreateOverloadedUnaryOp().
6658///
6659/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00006660ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00006661Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6662 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00006663 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006664 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00006665
6666 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6667 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6668 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006669 // TODO: provide better source location info.
6670 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006671
6672 Expr *Args[2] = { Input, 0 };
6673 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006674
Douglas Gregor084d8552009-03-13 23:49:33 +00006675 // For post-increment and post-decrement, add the implicit '0' as
6676 // the second argument, so that we know this is a post-increment or
6677 // post-decrement.
6678 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6679 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006680 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006681 SourceLocation());
6682 NumArgs = 2;
6683 }
6684
6685 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006686 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00006687 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00006688 Opc,
6689 Context.DependentTy,
6690 OpLoc));
6691
John McCall58cc69d2010-01-27 01:50:18 +00006692 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006693 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006694 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006695 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006696 /*ADL*/ true, IsOverloaded(Fns),
6697 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006698 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6699 &Args[0], NumArgs,
6700 Context.DependentTy,
6701 OpLoc));
6702 }
6703
6704 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006705 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006706
6707 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006708 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006709
6710 // Add operator candidates that are member functions.
6711 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6712
John McCall4c4c1df2010-01-26 03:27:55 +00006713 // Add candidates from ADL.
6714 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006715 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006716 /*ExplicitTemplateArgs*/ 0,
6717 CandidateSet);
6718
Douglas Gregor084d8552009-03-13 23:49:33 +00006719 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006720 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006721
6722 // Perform overload resolution.
6723 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006724 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006725 case OR_Success: {
6726 // We found a built-in operator or an overloaded operator.
6727 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006728
Douglas Gregor084d8552009-03-13 23:49:33 +00006729 if (FnDecl) {
6730 // We matched an overloaded operator. Build a call to that
6731 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006732
Douglas Gregor084d8552009-03-13 23:49:33 +00006733 // Convert the arguments.
6734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006735 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006736
John McCall16df1e52010-03-30 21:47:33 +00006737 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6738 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006739 return ExprError();
6740 } else {
6741 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00006742 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00006743 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006744 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006745 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00006746 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00006747 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006748 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00006749 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00006750 }
6751
John McCall4fa0d5f2010-05-06 18:15:07 +00006752 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6753
Douglas Gregor084d8552009-03-13 23:49:33 +00006754 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006755 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006756
Douglas Gregor084d8552009-03-13 23:49:33 +00006757 // Build the actual expression node.
6758 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6759 SourceLocation());
6760 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006761
Eli Friedman030eee42009-11-18 03:58:17 +00006762 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00006763 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006764 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallb268a282010-08-23 23:25:46 +00006765 Args, NumArgs, ResultTy, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00006766
John McCallb268a282010-08-23 23:25:46 +00006767 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006768 FnDecl))
6769 return ExprError();
6770
John McCallb268a282010-08-23 23:25:46 +00006771 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00006772 } else {
6773 // We matched a built-in operator. Convert the arguments, then
6774 // break out so that we will build the appropriate built-in
6775 // operator node.
6776 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006777 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006778 return ExprError();
6779
6780 break;
6781 }
6782 }
6783
6784 case OR_No_Viable_Function:
6785 // No viable function; fall through to handling this as a
6786 // built-in operator, which will produce an error message for us.
6787 break;
6788
6789 case OR_Ambiguous:
6790 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6791 << UnaryOperator::getOpcodeStr(Opc)
6792 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006793 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006794 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006795 return ExprError();
6796
6797 case OR_Deleted:
6798 Diag(OpLoc, diag::err_ovl_deleted_oper)
6799 << Best->Function->isDeleted()
6800 << UnaryOperator::getOpcodeStr(Opc)
6801 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006802 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006803 return ExprError();
6804 }
6805
6806 // Either we found no viable overloaded operator or we matched a
6807 // built-in operator. In either case, fall through to trying to
6808 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00006809 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006810}
6811
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006812/// \brief Create a binary operation that may resolve to an overloaded
6813/// operator.
6814///
6815/// \param OpLoc The location of the operator itself (e.g., '+').
6816///
6817/// \param OpcIn The BinaryOperator::Opcode that describes this
6818/// operator.
6819///
6820/// \param Functions The set of non-member functions that will be
6821/// considered by overload resolution. The caller needs to build this
6822/// set based on the context using, e.g.,
6823/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6824/// set should not contain any member functions; those will be added
6825/// by CreateOverloadedBinOp().
6826///
6827/// \param LHS Left-hand argument.
6828/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00006829ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006830Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006831 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006832 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006833 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006834 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006835 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006836
6837 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6838 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6839 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6840
6841 // If either side is type-dependent, create an appropriate dependent
6842 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006843 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006844 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006845 // If there are no functions to store, just build a dependent
6846 // BinaryOperator or CompoundAssignment.
6847 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6848 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6849 Context.DependentTy, OpLoc));
6850
6851 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6852 Context.DependentTy,
6853 Context.DependentTy,
6854 Context.DependentTy,
6855 OpLoc));
6856 }
John McCall4c4c1df2010-01-26 03:27:55 +00006857
6858 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006859 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006860 // TODO: provide better source location info in DNLoc component.
6861 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006862 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006863 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006864 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006865 /*ADL*/ true, IsOverloaded(Fns),
6866 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006867 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006868 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006869 Context.DependentTy,
6870 OpLoc));
6871 }
6872
6873 // If this is the .* operator, which is not overloadable, just
6874 // create a built-in binary operator.
6875 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006876 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006877
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006878 // If this is the assignment operator, we only perform overload resolution
6879 // if the left-hand side is a class or enumeration type. This is actually
6880 // a hack. The standard requires that we do overload resolution between the
6881 // various built-in candidates, but as DR507 points out, this can lead to
6882 // problems. So we do it this way, which pretty much follows what GCC does.
6883 // Note that we go the traditional code path for compound assignment forms.
6884 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006885 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006886
Douglas Gregor084d8552009-03-13 23:49:33 +00006887 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006888 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006889
6890 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006891 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006892
6893 // Add operator candidates that are member functions.
6894 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6895
John McCall4c4c1df2010-01-26 03:27:55 +00006896 // Add candidates from ADL.
6897 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6898 Args, 2,
6899 /*ExplicitTemplateArgs*/ 0,
6900 CandidateSet);
6901
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006902 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006903 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006904
6905 // Perform overload resolution.
6906 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006907 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006908 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006909 // We found a built-in operator or an overloaded operator.
6910 FunctionDecl *FnDecl = Best->Function;
6911
6912 if (FnDecl) {
6913 // We matched an overloaded operator. Build a call to that
6914 // operator.
6915
6916 // Convert the arguments.
6917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006918 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006919 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006920
John McCalldadc5752010-08-24 06:29:42 +00006921 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006922 = PerformCopyInitialization(
6923 InitializedEntity::InitializeParameter(
6924 FnDecl->getParamDecl(0)),
6925 SourceLocation(),
6926 Owned(Args[1]));
6927 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006928 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006929
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006930 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006931 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006932 return ExprError();
6933
6934 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006935 } else {
6936 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00006937 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006938 = PerformCopyInitialization(
6939 InitializedEntity::InitializeParameter(
6940 FnDecl->getParamDecl(0)),
6941 SourceLocation(),
6942 Owned(Args[0]));
6943 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006944 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006945
John McCalldadc5752010-08-24 06:29:42 +00006946 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006947 = PerformCopyInitialization(
6948 InitializedEntity::InitializeParameter(
6949 FnDecl->getParamDecl(1)),
6950 SourceLocation(),
6951 Owned(Args[1]));
6952 if (Arg1.isInvalid())
6953 return ExprError();
6954 Args[0] = LHS = Arg0.takeAs<Expr>();
6955 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006956 }
6957
John McCall4fa0d5f2010-05-06 18:15:07 +00006958 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6959
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006960 // Determine the result type
6961 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00006962 = FnDecl->getType()->getAs<FunctionType>()
6963 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006964
6965 // Build the actual expression node.
6966 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006967 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006968 UsualUnaryConversions(FnExpr);
6969
John McCallb268a282010-08-23 23:25:46 +00006970 CXXOperatorCallExpr *TheCall =
6971 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6972 Args, 2, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006973
John McCallb268a282010-08-23 23:25:46 +00006974 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006975 FnDecl))
6976 return ExprError();
6977
John McCallb268a282010-08-23 23:25:46 +00006978 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006979 } else {
6980 // We matched a built-in operator. Convert the arguments, then
6981 // break out so that we will build the appropriate built-in
6982 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006983 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006984 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006985 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006986 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006987 return ExprError();
6988
6989 break;
6990 }
6991 }
6992
Douglas Gregor66950a32009-09-30 21:46:01 +00006993 case OR_No_Viable_Function: {
6994 // C++ [over.match.oper]p9:
6995 // If the operator is the operator , [...] and there are no
6996 // viable functions, then the operator is assumed to be the
6997 // built-in operator and interpreted according to clause 5.
6998 if (Opc == BinaryOperator::Comma)
6999 break;
7000
Sebastian Redl027de2a2009-05-21 11:50:50 +00007001 // For class as left operand for assignment or compound assigment operator
7002 // do not fall through to handling in built-in, but report that no overloaded
7003 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007004 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007005 if (Args[0]->getType()->isRecordType() &&
7006 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007007 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7008 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007009 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007010 } else {
7011 // No viable function; try to create a built-in operation, which will
7012 // produce an error. Then, show the non-viable candidates.
7013 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007014 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007015 assert(Result.isInvalid() &&
7016 "C++ binary operator overloading is missing candidates!");
7017 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00007018 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007019 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007020 return move(Result);
7021 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007022
7023 case OR_Ambiguous:
7024 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7025 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007026 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007027 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007028 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007029 return ExprError();
7030
7031 case OR_Deleted:
7032 Diag(OpLoc, diag::err_ovl_deleted_oper)
7033 << Best->Function->isDeleted()
7034 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007035 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007036 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007037 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007038 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007039
Douglas Gregor66950a32009-09-30 21:46:01 +00007040 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007041 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007042}
7043
John McCalldadc5752010-08-24 06:29:42 +00007044ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007045Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7046 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007047 Expr *Base, Expr *Idx) {
7048 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007049 DeclarationName OpName =
7050 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7051
7052 // If either side is type-dependent, create an appropriate dependent
7053 // expression.
7054 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7055
John McCall58cc69d2010-01-27 01:50:18 +00007056 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007057 // CHECKME: no 'operator' keyword?
7058 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7059 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007060 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007061 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007062 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007063 /*ADL*/ true, /*Overloaded*/ false,
7064 UnresolvedSetIterator(),
7065 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007066 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007067
Sebastian Redladba46e2009-10-29 20:17:01 +00007068 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7069 Args, 2,
7070 Context.DependentTy,
7071 RLoc));
7072 }
7073
7074 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007075 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007076
7077 // Subscript can only be overloaded as a member function.
7078
7079 // Add operator candidates that are member functions.
7080 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7081
7082 // Add builtin operator candidates.
7083 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7084
7085 // Perform overload resolution.
7086 OverloadCandidateSet::iterator Best;
7087 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7088 case OR_Success: {
7089 // We found a built-in operator or an overloaded operator.
7090 FunctionDecl *FnDecl = Best->Function;
7091
7092 if (FnDecl) {
7093 // We matched an overloaded operator. Build a call to that
7094 // operator.
7095
John McCalla0296f72010-03-19 07:35:19 +00007096 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007097 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007098
Sebastian Redladba46e2009-10-29 20:17:01 +00007099 // Convert the arguments.
7100 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007101 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007102 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007103 return ExprError();
7104
Anders Carlssona68e51e2010-01-29 18:37:50 +00007105 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007106 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007107 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7108 FnDecl->getParamDecl(0)),
7109 SourceLocation(),
7110 Owned(Args[1]));
7111 if (InputInit.isInvalid())
7112 return ExprError();
7113
7114 Args[1] = InputInit.takeAs<Expr>();
7115
Sebastian Redladba46e2009-10-29 20:17:01 +00007116 // Determine the result type
7117 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007118 = FnDecl->getType()->getAs<FunctionType>()
7119 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007120
7121 // Build the actual expression node.
7122 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7123 LLoc);
7124 UsualUnaryConversions(FnExpr);
7125
John McCallb268a282010-08-23 23:25:46 +00007126 CXXOperatorCallExpr *TheCall =
7127 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7128 FnExpr, Args, 2,
7129 ResultTy, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007130
John McCallb268a282010-08-23 23:25:46 +00007131 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007132 FnDecl))
7133 return ExprError();
7134
John McCallb268a282010-08-23 23:25:46 +00007135 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007136 } else {
7137 // We matched a built-in operator. Convert the arguments, then
7138 // break out so that we will build the appropriate built-in
7139 // operator node.
7140 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007141 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007142 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007143 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007144 return ExprError();
7145
7146 break;
7147 }
7148 }
7149
7150 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007151 if (CandidateSet.empty())
7152 Diag(LLoc, diag::err_ovl_no_oper)
7153 << Args[0]->getType() << /*subscript*/ 0
7154 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7155 else
7156 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7157 << Args[0]->getType()
7158 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007159 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00007160 "[]", LLoc);
7161 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007162 }
7163
7164 case OR_Ambiguous:
7165 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7166 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007167 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00007168 "[]", LLoc);
7169 return ExprError();
7170
7171 case OR_Deleted:
7172 Diag(LLoc, diag::err_ovl_deleted_oper)
7173 << Best->Function->isDeleted() << "[]"
7174 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007175 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00007176 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007177 return ExprError();
7178 }
7179
7180 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007181 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007182}
7183
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007184/// BuildCallToMemberFunction - Build a call to a member
7185/// function. MemExpr is the expression that refers to the member
7186/// function (and includes the object parameter), Args/NumArgs are the
7187/// arguments to the function call (not including the object
7188/// parameter). The caller needs to validate that the member
7189/// expression refers to a member function or an overloaded member
7190/// function.
John McCalldadc5752010-08-24 06:29:42 +00007191ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007192Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7193 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007194 unsigned NumArgs, SourceLocation *CommaLocs,
7195 SourceLocation RParenLoc) {
7196 // Dig out the member expression. This holds both the object
7197 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007198 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7199
John McCall10eae182009-11-30 22:42:35 +00007200 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007201 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007202 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007203 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007204 if (isa<MemberExpr>(NakedMemExpr)) {
7205 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007206 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007207 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007208 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007209 } else {
7210 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007211 Qualifier = UnresExpr->getQualifier();
7212
John McCall6e9f8f62009-12-03 04:06:58 +00007213 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007214
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007215 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007216 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007217
John McCall2d74de92009-12-01 22:10:20 +00007218 // FIXME: avoid copy.
7219 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7220 if (UnresExpr->hasExplicitTemplateArgs()) {
7221 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7222 TemplateArgs = &TemplateArgsBuffer;
7223 }
7224
John McCall10eae182009-11-30 22:42:35 +00007225 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7226 E = UnresExpr->decls_end(); I != E; ++I) {
7227
John McCall6e9f8f62009-12-03 04:06:58 +00007228 NamedDecl *Func = *I;
7229 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7230 if (isa<UsingShadowDecl>(Func))
7231 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7232
John McCall10eae182009-11-30 22:42:35 +00007233 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007234 // If explicit template arguments were provided, we can't call a
7235 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007236 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007237 continue;
7238
John McCalla0296f72010-03-19 07:35:19 +00007239 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007240 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007241 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007242 } else {
John McCall10eae182009-11-30 22:42:35 +00007243 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007244 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007245 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007246 CandidateSet,
7247 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007248 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007249 }
Mike Stump11289f42009-09-09 15:08:12 +00007250
John McCall10eae182009-11-30 22:42:35 +00007251 DeclarationName DeclName = UnresExpr->getMemberName();
7252
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007253 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00007254 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007255 case OR_Success:
7256 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007257 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007258 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007259 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007260 break;
7261
7262 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007263 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007264 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007265 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007266 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007267 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007268 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007269
7270 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007271 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007272 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007273 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007274 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007275 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007276
7277 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007278 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007279 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007280 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007281 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007282 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007283 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007284 }
7285
John McCall16df1e52010-03-30 21:47:33 +00007286 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007287
John McCall2d74de92009-12-01 22:10:20 +00007288 // If overload resolution picked a static member, build a
7289 // non-member call based on that function.
7290 if (Method->isStatic()) {
7291 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7292 Args, NumArgs, RParenLoc);
7293 }
7294
John McCall10eae182009-11-30 22:42:35 +00007295 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007296 }
7297
7298 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007299 CXXMemberCallExpr *TheCall =
7300 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7301 Method->getCallResultType(),
7302 RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007303
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007304 // Check for a valid return type.
7305 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007306 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007307 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007308
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007309 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007310 // We only need to do this if there was actually an overload; otherwise
7311 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007312 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007313 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007314 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7315 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007316 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007317 MemExpr->setBase(ObjectArg);
7318
7319 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007320 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007321 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007322 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007323 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007324
John McCallb268a282010-08-23 23:25:46 +00007325 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007326 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007327
John McCallb268a282010-08-23 23:25:46 +00007328 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007329}
7330
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007331/// BuildCallToObjectOfClassType - Build a call to an object of class
7332/// type (C++ [over.call.object]), which can end up invoking an
7333/// overloaded function call operator (@c operator()) or performing a
7334/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007335Sema::ExprResult
7336Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007337 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007338 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007339 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007340 SourceLocation RParenLoc) {
7341 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007342 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007343
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007344 // C++ [over.call.object]p1:
7345 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007346 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007347 // candidate functions includes at least the function call
7348 // operators of T. The function call operators of T are obtained by
7349 // ordinary lookup of the name operator() in the context of
7350 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007351 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007352 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007353
7354 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007355 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007356 << Object->getSourceRange()))
7357 return true;
7358
John McCall27b18f82009-11-17 02:14:36 +00007359 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7360 LookupQualifiedName(R, Record->getDecl());
7361 R.suppressDiagnostics();
7362
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007363 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007364 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007365 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007366 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007367 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007368 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007369
Douglas Gregorab7897a2008-11-19 22:57:39 +00007370 // C++ [over.call.object]p2:
7371 // In addition, for each conversion function declared in T of the
7372 // form
7373 //
7374 // operator conversion-type-id () cv-qualifier;
7375 //
7376 // where cv-qualifier is the same cv-qualification as, or a
7377 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007378 // denotes the type "pointer to function of (P1,...,Pn) returning
7379 // R", or the type "reference to pointer to function of
7380 // (P1,...,Pn) returning R", or the type "reference to function
7381 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007382 // is also considered as a candidate function. Similarly,
7383 // surrogate call functions are added to the set of candidate
7384 // functions for each conversion function declared in an
7385 // accessible base class provided the function is not hidden
7386 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007387 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007388 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007389 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007390 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007391 NamedDecl *D = *I;
7392 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7393 if (isa<UsingShadowDecl>(D))
7394 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7395
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007396 // Skip over templated conversion functions; they aren't
7397 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007398 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007399 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007400
John McCall6e9f8f62009-12-03 04:06:58 +00007401 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007402
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007403 // Strip the reference type (if any) and then the pointer type (if
7404 // any) to get down to what might be a function type.
7405 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7406 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7407 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007408
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007409 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007410 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007411 Object->getType(), Args, NumArgs,
7412 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007413 }
Mike Stump11289f42009-09-09 15:08:12 +00007414
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007415 // Perform overload resolution.
7416 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007417 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007418 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007419 // Overload resolution succeeded; we'll build the appropriate call
7420 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007421 break;
7422
7423 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007424 if (CandidateSet.empty())
7425 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7426 << Object->getType() << /*call*/ 1
7427 << Object->getSourceRange();
7428 else
7429 Diag(Object->getSourceRange().getBegin(),
7430 diag::err_ovl_no_viable_object_call)
7431 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007432 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007433 break;
7434
7435 case OR_Ambiguous:
7436 Diag(Object->getSourceRange().getBegin(),
7437 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007438 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007439 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007440 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007441
7442 case OR_Deleted:
7443 Diag(Object->getSourceRange().getBegin(),
7444 diag::err_ovl_deleted_object_call)
7445 << Best->Function->isDeleted()
7446 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007447 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007448 break;
Mike Stump11289f42009-09-09 15:08:12 +00007449 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007450
Douglas Gregorb412e172010-07-25 18:17:45 +00007451 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007452 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007453
Douglas Gregorab7897a2008-11-19 22:57:39 +00007454 if (Best->Function == 0) {
7455 // Since there is no function declaration, this is one of the
7456 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007457 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007458 = cast<CXXConversionDecl>(
7459 Best->Conversions[0].UserDefined.ConversionFunction);
7460
John McCalla0296f72010-03-19 07:35:19 +00007461 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007462 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007463
Douglas Gregorab7897a2008-11-19 22:57:39 +00007464 // We selected one of the surrogate functions that converts the
7465 // object parameter to a function pointer. Perform the conversion
7466 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007467
7468 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007469 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007470 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7471 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007472
John McCallb268a282010-08-23 23:25:46 +00007473 return ActOnCallExpr(S, CE, LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007474 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
John McCalle172be52010-08-24 06:09:16 +00007475 CommaLocs, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007476 }
7477
John McCalla0296f72010-03-19 07:35:19 +00007478 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007479 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007480
Douglas Gregorab7897a2008-11-19 22:57:39 +00007481 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7482 // that calls this method, using Object for the implicit object
7483 // parameter and passing along the remaining arguments.
7484 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007485 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007486
7487 unsigned NumArgsInProto = Proto->getNumArgs();
7488 unsigned NumArgsToCheck = NumArgs;
7489
7490 // Build the full argument list for the method call (the
7491 // implicit object parameter is placed at the beginning of the
7492 // list).
7493 Expr **MethodArgs;
7494 if (NumArgs < NumArgsInProto) {
7495 NumArgsToCheck = NumArgsInProto;
7496 MethodArgs = new Expr*[NumArgsInProto + 1];
7497 } else {
7498 MethodArgs = new Expr*[NumArgs + 1];
7499 }
7500 MethodArgs[0] = Object;
7501 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7502 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007503
7504 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007505 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007506 UsualUnaryConversions(NewFn);
7507
7508 // Once we've built TheCall, all of the expressions are properly
7509 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007510 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007511 CXXOperatorCallExpr *TheCall =
7512 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7513 MethodArgs, NumArgs + 1,
7514 ResultTy, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007515 delete [] MethodArgs;
7516
John McCallb268a282010-08-23 23:25:46 +00007517 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007518 Method))
7519 return true;
7520
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007521 // We may have default arguments. If so, we need to allocate more
7522 // slots in the call for them.
7523 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007524 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007525 else if (NumArgs > NumArgsInProto)
7526 NumArgsToCheck = NumArgsInProto;
7527
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007528 bool IsError = false;
7529
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007530 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007531 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007532 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007533 TheCall->setArg(0, Object);
7534
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007535
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007536 // Check the argument types.
7537 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007538 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007539 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007540 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007541
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007542 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007543
John McCalldadc5752010-08-24 06:29:42 +00007544 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007545 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7546 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007547 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007548
7549 IsError |= InputInit.isInvalid();
7550 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007551 } else {
John McCalldadc5752010-08-24 06:29:42 +00007552 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007553 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7554 if (DefArg.isInvalid()) {
7555 IsError = true;
7556 break;
7557 }
7558
7559 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007560 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007561
7562 TheCall->setArg(i + 1, Arg);
7563 }
7564
7565 // If this is a variadic call, handle args passed through "...".
7566 if (Proto->isVariadic()) {
7567 // Promote the arguments (C99 6.5.2.2p7).
7568 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7569 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007570 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007571 TheCall->setArg(i + 1, Arg);
7572 }
7573 }
7574
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007575 if (IsError) return true;
7576
John McCallb268a282010-08-23 23:25:46 +00007577 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007578 return true;
7579
John McCalle172be52010-08-24 06:09:16 +00007580 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007581}
7582
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007583/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007584/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007585/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00007586ExprResult
John McCallb268a282010-08-23 23:25:46 +00007587Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007588 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007589
John McCallbc077cf2010-02-08 23:07:23 +00007590 SourceLocation Loc = Base->getExprLoc();
7591
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007592 // C++ [over.ref]p1:
7593 //
7594 // [...] An expression x->m is interpreted as (x.operator->())->m
7595 // for a class object x of type T if T::operator->() exists and if
7596 // the operator is selected as the best match function by the
7597 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007598 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007599 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007600 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007601
John McCallbc077cf2010-02-08 23:07:23 +00007602 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007603 PDiag(diag::err_typecheck_incomplete_tag)
7604 << Base->getSourceRange()))
7605 return ExprError();
7606
John McCall27b18f82009-11-17 02:14:36 +00007607 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7608 LookupQualifiedName(R, BaseRecord->getDecl());
7609 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007610
7611 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007612 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007613 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007614 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007615 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007616
7617 // Perform overload resolution.
7618 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007619 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007620 case OR_Success:
7621 // Overload resolution succeeded; we'll build the call below.
7622 break;
7623
7624 case OR_No_Viable_Function:
7625 if (CandidateSet.empty())
7626 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007627 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007628 else
7629 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007630 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007631 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007632 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007633
7634 case OR_Ambiguous:
7635 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007636 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007637 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007638 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007639
7640 case OR_Deleted:
7641 Diag(OpLoc, diag::err_ovl_deleted_oper)
7642 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007643 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007644 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007645 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007646 }
7647
John McCalla0296f72010-03-19 07:35:19 +00007648 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007649 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007650
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007651 // Convert the object parameter.
7652 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007653 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7654 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007655 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007656
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007657 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007658 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7659 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007660 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007661
Douglas Gregor603d81b2010-07-13 08:18:22 +00007662 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007663 CXXOperatorCallExpr *TheCall =
7664 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7665 &Base, 1, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007666
John McCallb268a282010-08-23 23:25:46 +00007667 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007668 Method))
7669 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007670 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007671}
7672
Douglas Gregorcd695e52008-11-10 20:40:00 +00007673/// FixOverloadedFunctionReference - E is an expression that refers to
7674/// a C++ overloaded function (possibly with some parentheses and
7675/// perhaps a '&' around it). We have resolved the overloaded function
7676/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007677/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007678Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007679 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007680 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007681 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7682 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007683 if (SubExpr == PE->getSubExpr())
7684 return PE->Retain();
7685
7686 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7687 }
7688
7689 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007690 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7691 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007692 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007693 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007694 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007695 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007696 if (SubExpr == ICE->getSubExpr())
7697 return ICE->Retain();
7698
John McCallcf142162010-08-07 06:22:56 +00007699 return ImplicitCastExpr::Create(Context, ICE->getType(),
7700 ICE->getCastKind(),
7701 SubExpr, 0,
7702 ICE->getCategory());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007703 }
7704
7705 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007706 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007707 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007708 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7709 if (Method->isStatic()) {
7710 // Do nothing: static member functions aren't any different
7711 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007712 } else {
John McCalle66edc12009-11-24 19:00:30 +00007713 // Fix the sub expression, which really has to be an
7714 // UnresolvedLookupExpr holding an overloaded member function
7715 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007716 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7717 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007718 if (SubExpr == UnOp->getSubExpr())
7719 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007720
John McCalld14a8642009-11-21 08:51:07 +00007721 assert(isa<DeclRefExpr>(SubExpr)
7722 && "fixed to something other than a decl ref");
7723 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7724 && "fixed to a member ref with no nested name qualifier");
7725
7726 // We have taken the address of a pointer to member
7727 // function. Perform the computation here so that we get the
7728 // appropriate pointer to member type.
7729 QualType ClassType
7730 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7731 QualType MemPtrType
7732 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7733
7734 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7735 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007736 }
7737 }
John McCall16df1e52010-03-30 21:47:33 +00007738 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7739 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007740 if (SubExpr == UnOp->getSubExpr())
7741 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007742
Douglas Gregor51c538b2009-11-20 19:42:02 +00007743 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7744 Context.getPointerType(SubExpr->getType()),
7745 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007746 }
John McCalld14a8642009-11-21 08:51:07 +00007747
7748 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007749 // FIXME: avoid copy.
7750 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007751 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007752 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7753 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007754 }
7755
John McCalld14a8642009-11-21 08:51:07 +00007756 return DeclRefExpr::Create(Context,
7757 ULE->getQualifier(),
7758 ULE->getQualifierRange(),
7759 Fn,
7760 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007761 Fn->getType(),
7762 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007763 }
7764
John McCall10eae182009-11-30 22:42:35 +00007765 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007766 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007767 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7768 if (MemExpr->hasExplicitTemplateArgs()) {
7769 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7770 TemplateArgs = &TemplateArgsBuffer;
7771 }
John McCall6b51f282009-11-23 01:53:49 +00007772
John McCall2d74de92009-12-01 22:10:20 +00007773 Expr *Base;
7774
7775 // If we're filling in
7776 if (MemExpr->isImplicitAccess()) {
7777 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7778 return DeclRefExpr::Create(Context,
7779 MemExpr->getQualifier(),
7780 MemExpr->getQualifierRange(),
7781 Fn,
7782 MemExpr->getMemberLoc(),
7783 Fn->getType(),
7784 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007785 } else {
7786 SourceLocation Loc = MemExpr->getMemberLoc();
7787 if (MemExpr->getQualifier())
7788 Loc = MemExpr->getQualifierRange().getBegin();
7789 Base = new (Context) CXXThisExpr(Loc,
7790 MemExpr->getBaseType(),
7791 /*isImplicit=*/true);
7792 }
John McCall2d74de92009-12-01 22:10:20 +00007793 } else
7794 Base = MemExpr->getBase()->Retain();
7795
7796 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007797 MemExpr->isArrow(),
7798 MemExpr->getQualifier(),
7799 MemExpr->getQualifierRange(),
7800 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007801 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007802 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00007803 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007804 Fn->getType());
7805 }
7806
Douglas Gregor51c538b2009-11-20 19:42:02 +00007807 assert(false && "Invalid reference to overloaded function");
7808 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007809}
7810
John McCalldadc5752010-08-24 06:29:42 +00007811ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7812 DeclAccessPair Found,
7813 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007814 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007815}
7816
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007817} // end namespace clang