blob: 6c64905561bfc4c32d818a2b9f101161b56cb62e [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
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000055 ICC_Conversion,
56 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000057 ICC_Conversion
58 };
59 return Category[(int)Kind];
60}
61
62/// GetConversionRank - Retrieve the implicit conversion rank
63/// corresponding to the given implicit conversion kind.
64ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
65 static const ImplicitConversionRank
66 Rank[(int)ICK_Num_Conversion_Kinds] = {
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Exact_Match,
71 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000072 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000073 ICR_Promotion,
74 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000075 ICR_Promotion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000078 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000083 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000084 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000085 ICR_Conversion,
86 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000087 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000088 };
89 return Rank[(int)Kind];
90}
91
92/// GetImplicitConversionName - Return the name of this kind of
93/// implicit conversion.
94const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000095 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000096 "No conversion",
97 "Lvalue-to-rvalue",
98 "Array-to-pointer",
99 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000100 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Qualification",
102 "Integral promotion",
103 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 "Integral conversion",
106 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000107 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 "Floating-integral conversion",
109 "Pointer conversion",
110 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000113 "Derived-to-base conversion",
114 "Vector conversion",
115 "Vector splat",
116 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 };
118 return Name[Kind];
119}
120
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000121/// StandardConversionSequence - Set the standard conversion
122/// sequence to the identity conversion.
123void StandardConversionSequence::setAsIdentityConversion() {
124 First = ICK_Identity;
125 Second = ICK_Identity;
126 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000127 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000128 ReferenceBinding = false;
129 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000130 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000131 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000132}
133
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134/// getRank - Retrieve the rank of this standard conversion sequence
135/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
136/// implicit conversions.
137ImplicitConversionRank StandardConversionSequence::getRank() const {
138 ImplicitConversionRank Rank = ICR_Exact_Match;
139 if (GetConversionRank(First) > Rank)
140 Rank = GetConversionRank(First);
141 if (GetConversionRank(Second) > Rank)
142 Rank = GetConversionRank(Second);
143 if (GetConversionRank(Third) > Rank)
144 Rank = GetConversionRank(Third);
145 return Rank;
146}
147
148/// isPointerConversionToBool - Determines whether this conversion is
149/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000150/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000152bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 // Note that FromType has not necessarily been transformed by the
154 // array-to-pointer or function-to-pointer implicit conversions, so
155 // check for their presence as well as checking whether FromType is
156 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000157 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000158 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
160 return true;
161
162 return false;
163}
164
Douglas Gregor5c407d92008-10-23 00:40:37 +0000165/// isPointerConversionToVoidPointer - Determines whether this
166/// conversion is a conversion of a pointer to a void pointer. This is
167/// used as part of the ranking of standard conversion sequences (C++
168/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000169bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000170StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000171isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000172 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000173 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000174
175 // Note that FromType has not necessarily been transformed by the
176 // array-to-pointer implicit conversion, so check for its presence
177 // and redo the conversion to get a pointer.
178 if (First == ICK_Array_To_Pointer)
179 FromType = Context.getArrayDecayedType(FromType);
180
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000181 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000182 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000183 return ToPtrType->getPointeeType()->isVoidType();
184
185 return false;
186}
187
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000188/// DebugPrint - Print this standard conversion sequence to standard
189/// error. Useful for debugging overloading issues.
190void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000191 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000192 bool PrintedSomething = false;
193 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 PrintedSomething = true;
196 }
197
198 if (Second != ICK_Identity) {
199 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000200 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000202 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000203
204 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000205 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000206 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000207 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000208 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000209 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000210 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 PrintedSomething = true;
212 }
213
214 if (Third != ICK_Identity) {
215 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000216 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000217 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000218 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 PrintedSomething = true;
220 }
221
222 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000223 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000224 }
225}
226
227/// DebugPrint - Print this user-defined conversion sequence to standard
228/// error. Useful for debugging overloading issues.
229void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000230 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000231 if (Before.First || Before.Second || Before.Third) {
232 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000233 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000234 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000235 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000237 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238 After.DebugPrint();
239 }
240}
241
242/// DebugPrint - Print this implicit conversion sequence to standard
243/// error. Useful for debugging overloading issues.
244void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000245 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000246 switch (ConversionKind) {
247 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000248 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000249 Standard.DebugPrint();
250 break;
251 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000252 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000253 UserDefined.DebugPrint();
254 break;
255 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
John McCall0d1da222010-01-12 00:44:57 +0000258 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000259 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000260 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000262 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 break;
264 }
265
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000266 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000267}
268
John McCall0d1da222010-01-12 00:44:57 +0000269void AmbiguousConversionSequence::construct() {
270 new (&conversions()) ConversionSet();
271}
272
273void AmbiguousConversionSequence::destruct() {
274 conversions().~ConversionSet();
275}
276
277void
278AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
279 FromTypePtr = O.FromTypePtr;
280 ToTypePtr = O.ToTypePtr;
281 new (&conversions()) ConversionSet(O.conversions());
282}
283
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000284namespace {
285 // Structure used by OverloadCandidate::DeductionFailureInfo to store
286 // template parameter and template argument information.
287 struct DFIParamWithArguments {
288 TemplateParameter Param;
289 TemplateArgument FirstArg;
290 TemplateArgument SecondArg;
291 };
292}
293
294/// \brief Convert from Sema's representation of template deduction information
295/// to the form used in overload-candidate information.
296OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000297static MakeDeductionFailureInfo(ASTContext &Context,
298 Sema::TemplateDeductionResult TDK,
Douglas Gregord09efd42010-05-08 20:07:26 +0000299 Sema::TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000300 OverloadCandidate::DeductionFailureInfo Result;
301 Result.Result = static_cast<unsigned>(TDK);
302 Result.Data = 0;
303 switch (TDK) {
304 case Sema::TDK_Success:
305 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000306 case Sema::TDK_TooManyArguments:
307 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000308 break;
309
310 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000311 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000312 Result.Data = Info.Param.getOpaqueValue();
313 break;
314
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000315 case Sema::TDK_Inconsistent:
316 case Sema::TDK_InconsistentQuals: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000317 // FIXME: Should allocate from normal heap so that we can free this later.
318 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000319 Saved->Param = Info.Param;
320 Saved->FirstArg = Info.FirstArg;
321 Saved->SecondArg = Info.SecondArg;
322 Result.Data = Saved;
323 break;
324 }
325
326 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000327 Result.Data = Info.take();
328 break;
329
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000330 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000331 case Sema::TDK_FailedOverloadResolution:
332 break;
333 }
334
335 return Result;
336}
John McCall0d1da222010-01-12 00:44:57 +0000337
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000338void OverloadCandidate::DeductionFailureInfo::Destroy() {
339 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
340 case Sema::TDK_Success:
341 case Sema::TDK_InstantiationDepth:
342 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000343 case Sema::TDK_TooManyArguments:
344 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000345 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346 break;
347
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000348 case Sema::TDK_Inconsistent:
349 case Sema::TDK_InconsistentQuals:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000350 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000351 Data = 0;
352 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000353
354 case Sema::TDK_SubstitutionFailure:
355 // FIXME: Destroy the template arugment list?
356 Data = 0;
357 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000358
Douglas Gregor461761d2010-05-08 18:20:53 +0000359 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000361 case Sema::TDK_FailedOverloadResolution:
362 break;
363 }
364}
365
366TemplateParameter
367OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
368 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
369 case Sema::TDK_Success:
370 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000371 case Sema::TDK_TooManyArguments:
372 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000373 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000374 return TemplateParameter();
375
376 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000377 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000378 return TemplateParameter::getFromOpaqueValue(Data);
379
380 case Sema::TDK_Inconsistent:
381 case Sema::TDK_InconsistentQuals:
382 return static_cast<DFIParamWithArguments*>(Data)->Param;
383
384 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 case Sema::TDK_FailedOverloadResolution:
387 break;
388 }
389
390 return TemplateParameter();
391}
Douglas Gregord09efd42010-05-08 20:07:26 +0000392
393TemplateArgumentList *
394OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
395 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
396 case Sema::TDK_Success:
397 case Sema::TDK_InstantiationDepth:
398 case Sema::TDK_TooManyArguments:
399 case Sema::TDK_TooFewArguments:
400 case Sema::TDK_Incomplete:
401 case Sema::TDK_InvalidExplicitArguments:
402 case Sema::TDK_Inconsistent:
403 case Sema::TDK_InconsistentQuals:
404 return 0;
405
406 case Sema::TDK_SubstitutionFailure:
407 return static_cast<TemplateArgumentList*>(Data);
408
409 // Unhandled
410 case Sema::TDK_NonDeducedMismatch:
411 case Sema::TDK_FailedOverloadResolution:
412 break;
413 }
414
415 return 0;
416}
417
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000418const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
419 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
420 case Sema::TDK_Success:
421 case Sema::TDK_InstantiationDepth:
422 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000423 case Sema::TDK_TooManyArguments:
424 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000425 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000426 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000427 return 0;
428
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429 case Sema::TDK_Inconsistent:
430 case Sema::TDK_InconsistentQuals:
431 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
432
Douglas Gregor461761d2010-05-08 18:20:53 +0000433 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000434 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000435 case Sema::TDK_FailedOverloadResolution:
436 break;
437 }
438
439 return 0;
440}
441
442const TemplateArgument *
443OverloadCandidate::DeductionFailureInfo::getSecondArg() {
444 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
445 case Sema::TDK_Success:
446 case Sema::TDK_InstantiationDepth:
447 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000448 case Sema::TDK_TooManyArguments:
449 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000450 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000451 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 return 0;
453
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 case Sema::TDK_Inconsistent:
455 case Sema::TDK_InconsistentQuals:
456 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
457
Douglas Gregor461761d2010-05-08 18:20:53 +0000458 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000459 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 case Sema::TDK_FailedOverloadResolution:
461 break;
462 }
463
464 return 0;
465}
466
467void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000468 inherited::clear();
469 Functions.clear();
470}
471
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000473// overload of the declarations in Old. This routine returns false if
474// New and Old cannot be overloaded, e.g., if New has the same
475// signature as some function in Old (C++ 1.3.10) or if the Old
476// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000477// it does return false, MatchedDecl will point to the decl that New
478// cannot be overloaded with. This decl may be a UsingShadowDecl on
479// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480//
481// Example: Given the following input:
482//
483// void f(int, float); // #1
484// void f(int, int); // #2
485// int f(int, int); // #3
486//
487// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000488// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489//
John McCall3d988d92009-12-02 08:47:38 +0000490// When we process #2, Old contains only the FunctionDecl for #1. By
491// comparing the parameter types, we see that #1 and #2 are overloaded
492// (since they have different signatures), so this routine returns
493// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494//
John McCall3d988d92009-12-02 08:47:38 +0000495// When we process #3, Old is an overload set containing #1 and #2. We
496// compare the signatures of #3 to #1 (they're overloaded, so we do
497// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
498// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499// signature), IsOverload returns false and MatchedDecl will be set to
500// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000501Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000502Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
503 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000504 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000505 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000506 NamedDecl *OldD = (*I)->getUnderlyingDecl();
507 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000508 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000509 Match = *I;
510 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511 }
John McCall3d988d92009-12-02 08:47:38 +0000512 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000513 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000514 Match = *I;
515 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000516 }
John McCall84d87672009-12-10 09:41:52 +0000517 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
518 // We can overload with these, which can show up when doing
519 // redeclaration checks for UsingDecls.
520 assert(Old.getLookupKind() == LookupUsingDeclName);
521 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
522 // Optimistically assume that an unresolved using decl will
523 // overload; if it doesn't, we'll have to diagnose during
524 // template instantiation.
525 } else {
John McCall1f82f242009-11-18 22:49:29 +0000526 // (C++ 13p1):
527 // Only function declarations can be overloaded; object and type
528 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000529 Match = *I;
530 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000531 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 }
John McCall1f82f242009-11-18 22:49:29 +0000533
John McCalldaa3d6b2009-12-09 03:35:25 +0000534 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000535}
536
537bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
538 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
539 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
540
541 // C++ [temp.fct]p2:
542 // A function template can be overloaded with other function templates
543 // and with normal (non-template) functions.
544 if ((OldTemplate == 0) != (NewTemplate == 0))
545 return true;
546
547 // Is the function New an overload of the function Old?
548 QualType OldQType = Context.getCanonicalType(Old->getType());
549 QualType NewQType = Context.getCanonicalType(New->getType());
550
551 // Compare the signatures (C++ 1.3.10) of the two functions to
552 // determine whether they are overloads. If we find any mismatch
553 // in the signature, they are overloads.
554
555 // If either of these functions is a K&R-style function (no
556 // prototype), then we consider them to have matching signatures.
557 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
558 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
559 return false;
560
561 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
562 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
563
564 // The signature of a function includes the types of its
565 // parameters (C++ 1.3.10), which includes the presence or absence
566 // of the ellipsis; see C++ DR 357).
567 if (OldQType != NewQType &&
568 (OldType->getNumArgs() != NewType->getNumArgs() ||
569 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000570 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000571 return true;
572
573 // C++ [temp.over.link]p4:
574 // The signature of a function template consists of its function
575 // signature, its return type and its template parameter list. The names
576 // of the template parameters are significant only for establishing the
577 // relationship between the template parameters and the rest of the
578 // signature.
579 //
580 // We check the return type and template parameter lists for function
581 // templates first; the remaining checks follow.
582 if (NewTemplate &&
583 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
584 OldTemplate->getTemplateParameters(),
585 false, TPL_TemplateMatch) ||
586 OldType->getResultType() != NewType->getResultType()))
587 return true;
588
589 // If the function is a class member, its signature includes the
590 // cv-qualifiers (if any) on the function itself.
591 //
592 // As part of this, also check whether one of the member functions
593 // is static, in which case they are not overloads (C++
594 // 13.1p2). While not part of the definition of the signature,
595 // this check is important to determine whether these functions
596 // can be overloaded.
597 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
598 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
599 if (OldMethod && NewMethod &&
600 !OldMethod->isStatic() && !NewMethod->isStatic() &&
601 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
602 return true;
603
604 // The signatures match; this is not an overload.
605 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000606}
607
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000608/// TryImplicitConversion - Attempt to perform an implicit conversion
609/// from the given expression (Expr) to the given type (ToType). This
610/// function returns an implicit conversion sequence that can be used
611/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612///
613/// void f(float f);
614/// void g(int i) { f(i); }
615///
616/// this routine would produce an implicit conversion sequence to
617/// describe the initialization of f from i, which will be a standard
618/// conversion sequence containing an lvalue-to-rvalue conversion (C++
619/// 4.1) followed by a floating-integral conversion (C++ 4.9).
620//
621/// Note that this routine only determines how the conversion can be
622/// performed; it does not actually perform the conversion. As such,
623/// it will not produce any diagnostics if no conversion is available,
624/// but will instead return an implicit conversion sequence of kind
625/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000626///
627/// If @p SuppressUserConversions, then user-defined conversions are
628/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000629/// If @p AllowExplicit, then explicit user-defined conversions are
630/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000631ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000632Sema::TryImplicitConversion(Expr* From, QualType ToType,
633 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000634 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000635 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000636 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000637 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000638 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000639 return ICS;
640 }
641
642 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000643 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000644 return ICS;
645 }
646
Douglas Gregor5ab11652010-04-17 22:01:05 +0000647 if (SuppressUserConversions) {
648 // C++ [over.ics.user]p4:
649 // A conversion of an expression of class type to the same class
650 // type is given Exact Match rank, and a conversion of an
651 // expression of class type to a base class of that type is
652 // given Conversion rank, in spite of the fact that a copy/move
653 // constructor (i.e., a user-defined conversion function) is
654 // called for those cases.
655 QualType FromType = From->getType();
656 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
657 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
658 IsDerivedFrom(FromType, ToType))) {
659 // We're not in the case above, so there is no conversion that
660 // we can perform.
661 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
662 return ICS;
663 }
664
665 ICS.setStandard();
666 ICS.Standard.setAsIdentityConversion();
667 ICS.Standard.setFromType(FromType);
668 ICS.Standard.setAllToTypes(ToType);
669
670 // We don't actually check at this point whether there is a valid
671 // copy/move constructor, since overloading just assumes that it
672 // exists. When we actually perform initialization, we'll find the
673 // appropriate constructor to copy the returned object, if needed.
674 ICS.Standard.CopyConstructor = 0;
675
676 // Determine whether this is considered a derived-to-base conversion.
677 if (!Context.hasSameUnqualifiedType(FromType, ToType))
678 ICS.Standard.Second = ICK_Derived_To_Base;
679
680 return ICS;
681 }
682
683 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000684 OverloadCandidateSet Conversions(From->getExprLoc());
685 OverloadingResult UserDefResult
686 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000687 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000688
689 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000690 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000691 // C++ [over.ics.user]p4:
692 // A conversion of an expression of class type to the same class
693 // type is given Exact Match rank, and a conversion of an
694 // expression of class type to a base class of that type is
695 // given Conversion rank, in spite of the fact that a copy
696 // constructor (i.e., a user-defined conversion function) is
697 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000698 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000699 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000700 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000701 = Context.getCanonicalType(From->getType().getUnqualifiedType());
702 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000703 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000704 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000705 // Turn this into a "standard" conversion sequence, so that it
706 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000707 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000708 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000709 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000710 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000711 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000712 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000713 ICS.Standard.Second = ICK_Derived_To_Base;
714 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000715 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000716
717 // C++ [over.best.ics]p4:
718 // However, when considering the argument of a user-defined
719 // conversion function that is a candidate by 13.3.1.3 when
720 // invoked for the copying of the temporary in the second step
721 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
722 // 13.3.1.6 in all cases, only standard conversion sequences and
723 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000724 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000725 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000726 }
John McCalle8c8cd22010-01-13 22:30:33 +0000727 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000728 ICS.setAmbiguous();
729 ICS.Ambiguous.setFromType(From->getType());
730 ICS.Ambiguous.setToType(ToType);
731 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
732 Cand != Conversions.end(); ++Cand)
733 if (Cand->Viable)
734 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000735 } else {
John McCall65eb8792010-02-25 01:37:24 +0000736 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000737 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000738
739 return ICS;
740}
741
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000742/// PerformImplicitConversion - Perform an implicit conversion of the
743/// expression From to the type ToType. Returns true if there was an
744/// error, false otherwise. The expression From is replaced with the
745/// converted expression. Flavor is the kind of conversion we're
746/// performing, used in the error message. If @p AllowExplicit,
747/// explicit user-defined conversions are permitted.
748bool
749Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
750 AssignmentAction Action, bool AllowExplicit) {
751 ImplicitConversionSequence ICS;
752 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
753}
754
755bool
756Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
757 AssignmentAction Action, bool AllowExplicit,
758 ImplicitConversionSequence& ICS) {
759 ICS = TryImplicitConversion(From, ToType,
760 /*SuppressUserConversions=*/false,
761 AllowExplicit,
762 /*InOverloadResolution=*/false);
763 return PerformImplicitConversion(From, ToType, ICS, Action);
764}
765
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000766/// \brief Determine whether the conversion from FromType to ToType is a valid
767/// conversion that strips "noreturn" off the nested function type.
768static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
769 QualType ToType, QualType &ResultTy) {
770 if (Context.hasSameUnqualifiedType(FromType, ToType))
771 return false;
772
773 // Strip the noreturn off the type we're converting from; noreturn can
774 // safely be removed.
775 FromType = Context.getNoReturnType(FromType, false);
776 if (!Context.hasSameUnqualifiedType(FromType, ToType))
777 return false;
778
779 ResultTy = FromType;
780 return true;
781}
Douglas Gregor46188682010-05-18 22:42:18 +0000782
783/// \brief Determine whether the conversion from FromType to ToType is a valid
784/// vector conversion.
785///
786/// \param ICK Will be set to the vector conversion kind, if this is a vector
787/// conversion.
788static bool IsVectorConversion(ASTContext &Context, QualType FromType,
789 QualType ToType, ImplicitConversionKind &ICK) {
790 // We need at least one of these types to be a vector type to have a vector
791 // conversion.
792 if (!ToType->isVectorType() && !FromType->isVectorType())
793 return false;
794
795 // Identical types require no conversions.
796 if (Context.hasSameUnqualifiedType(FromType, ToType))
797 return false;
798
799 // There are no conversions between extended vector types, only identity.
800 if (ToType->isExtVectorType()) {
801 // There are no conversions between extended vector types other than the
802 // identity conversion.
803 if (FromType->isExtVectorType())
804 return false;
805
806 // Vector splat from any arithmetic type to a vector.
807 if (!FromType->isVectorType() && FromType->isArithmeticType()) {
808 ICK = ICK_Vector_Splat;
809 return true;
810 }
811 }
812
813 // If lax vector conversions are permitted and the vector types are of the
814 // same size, we can perform the conversion.
815 if (Context.getLangOptions().LaxVectorConversions &&
816 FromType->isVectorType() && ToType->isVectorType() &&
817 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
818 ICK = ICK_Vector_Conversion;
819 return true;
820 }
821
822 return false;
823}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000824
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000825/// IsStandardConversion - Determines whether there is a standard
826/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
827/// expression From to the type ToType. Standard conversion sequences
828/// only consider non-class types; for conversions that involve class
829/// types, use TryImplicitConversion. If a conversion exists, SCS will
830/// contain the standard conversion sequence required to perform this
831/// conversion and this routine will return true. Otherwise, this
832/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000833bool
834Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000835 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000836 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000837 QualType FromType = From->getType();
838
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000839 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000840 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000841 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000842 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000843 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000844 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000845
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000846 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000847 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000848 if (FromType->isRecordType() || ToType->isRecordType()) {
849 if (getLangOptions().CPlusPlus)
850 return false;
851
Mike Stump11289f42009-09-09 15:08:12 +0000852 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000853 }
854
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000855 // The first conversion can be an lvalue-to-rvalue conversion,
856 // array-to-pointer conversion, or function-to-pointer conversion
857 // (C++ 4p1).
858
Douglas Gregor980fb162010-04-29 18:24:40 +0000859 if (FromType == Context.OverloadTy) {
860 DeclAccessPair AccessPair;
861 if (FunctionDecl *Fn
862 = ResolveAddressOfOverloadedFunction(From, ToType, false,
863 AccessPair)) {
864 // We were able to resolve the address of the overloaded function,
865 // so we can convert to the type of that function.
866 FromType = Fn->getType();
867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
868 if (!Method->isStatic()) {
869 Type *ClassType
870 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
871 FromType = Context.getMemberPointerType(FromType, ClassType);
872 }
873 }
874
875 // If the "from" expression takes the address of the overloaded
876 // function, update the type of the resulting expression accordingly.
877 if (FromType->getAs<FunctionType>())
878 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
879 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
880 FromType = Context.getPointerType(FromType);
881
882 // Check that we've computed the proper type after overload resolution.
883 assert(Context.hasSameType(FromType,
884 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
885 } else {
886 return false;
887 }
888 }
Mike Stump11289f42009-09-09 15:08:12 +0000889 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000890 // An lvalue (3.10) of a non-function, non-array type T can be
891 // converted to an rvalue.
892 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000893 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000894 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000895 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000896 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000897
898 // If T is a non-class type, the type of the rvalue is the
899 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000900 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
901 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000902 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000903 } else if (FromType->isArrayType()) {
904 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000905 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000906
907 // An lvalue or rvalue of type "array of N T" or "array of unknown
908 // bound of T" can be converted to an rvalue of type "pointer to
909 // T" (C++ 4.2p1).
910 FromType = Context.getArrayDecayedType(FromType);
911
912 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
913 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000914 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000915
916 // For the purpose of ranking in overload resolution
917 // (13.3.3.1.1), this conversion is considered an
918 // array-to-pointer conversion followed by a qualification
919 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000920 SCS.Second = ICK_Identity;
921 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000922 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000923 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000924 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000925 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
926 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000927 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000928
929 // An lvalue of function type T can be converted to an rvalue of
930 // type "pointer to T." The result is a pointer to the
931 // function. (C++ 4.3p1).
932 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000933 } else {
934 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000935 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000936 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000937 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938
939 // The second conversion can be an integral promotion, floating
940 // point promotion, integral conversion, floating point conversion,
941 // floating-integral conversion, pointer conversion,
942 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000943 // For overloading in C, this can also be a "compatible-type"
944 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000945 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000946 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000947 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000948 // The unqualified versions of the types are the same: there's no
949 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000950 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000951 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000952 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000953 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000954 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000955 } else if (IsFloatingPointPromotion(FromType, ToType)) {
956 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000957 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000958 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000959 } else if (IsComplexPromotion(FromType, ToType)) {
960 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000961 SCS.Second = ICK_Complex_Promotion;
962 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000963 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000964 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000965 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000966 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000968 } else if (FromType->isComplexType() && ToType->isComplexType()) {
969 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000970 SCS.Second = ICK_Complex_Conversion;
971 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000972 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
973 (ToType->isComplexType() && FromType->isArithmeticType())) {
974 // Complex-real conversions (C99 6.3.1.7)
975 SCS.Second = ICK_Complex_Real;
976 FromType = ToType.getUnqualifiedType();
977 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
978 // Floating point conversions (C++ 4.8).
979 SCS.Second = ICK_Floating_Conversion;
980 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000981 } else if ((FromType->isFloatingType() &&
982 ToType->isIntegralType() && (!ToType->isBooleanType() &&
983 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000984 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000985 ToType->isFloatingType())) {
986 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000987 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000988 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000989 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
990 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000991 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000992 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000993 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000994 } else if (IsMemberPointerConversion(From, FromType, ToType,
995 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000996 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000997 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000998 } else if (ToType->isBooleanType() &&
999 (FromType->isArithmeticType() ||
1000 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001001 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001002 FromType->isBlockPointerType() ||
1003 FromType->isMemberPointerType() ||
1004 FromType->isNullPtrType())) {
1005 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001006 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001007 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001008 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1009 SCS.Second = SecondICK;
1010 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001011 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001012 Context.typesAreCompatible(ToType, FromType)) {
1013 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001014 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001015 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001016 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1017 // Treat a conversion that strips "noreturn" as an identity conversion.
1018 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001019 } else {
1020 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001021 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001022 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001023 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001024
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001025 QualType CanonFrom;
1026 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001028 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001029 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001030 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001031 CanonFrom = Context.getCanonicalType(FromType);
1032 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001033 } else {
1034 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001035 SCS.Third = ICK_Identity;
1036
Mike Stump11289f42009-09-09 15:08:12 +00001037 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001038 // [...] Any difference in top-level cv-qualification is
1039 // subsumed by the initialization itself and does not constitute
1040 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001041 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001042 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001043 if (CanonFrom.getLocalUnqualifiedType()
1044 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001045 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1046 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001047 FromType = ToType;
1048 CanonFrom = CanonTo;
1049 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001050 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001051 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001052
1053 // If we have not converted the argument type to the parameter type,
1054 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001055 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001056 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001057
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001058 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059}
1060
1061/// IsIntegralPromotion - Determines whether the conversion from the
1062/// expression From (whose potentially-adjusted type is FromType) to
1063/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1064/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001065bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001066 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001067 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001068 if (!To) {
1069 return false;
1070 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071
1072 // An rvalue of type char, signed char, unsigned char, short int, or
1073 // unsigned short int can be converted to an rvalue of type int if
1074 // int can represent all the values of the source type; otherwise,
1075 // the source rvalue can be converted to an rvalue of type unsigned
1076 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001077 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1078 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001079 if (// We can promote any signed, promotable integer type to an int
1080 (FromType->isSignedIntegerType() ||
1081 // We can promote any unsigned integer type whose size is
1082 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001083 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001084 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001085 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001086 }
1087
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001088 return To->getKind() == BuiltinType::UInt;
1089 }
1090
1091 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1092 // can be converted to an rvalue of the first of the following types
1093 // that can represent all the values of its underlying type: int,
1094 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001095
1096 // We pre-calculate the promotion type for enum types.
1097 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1098 if (ToType->isIntegerType())
1099 return Context.hasSameUnqualifiedType(ToType,
1100 FromEnumType->getDecl()->getPromotionType());
1101
1102 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103 // Determine whether the type we're converting from is signed or
1104 // unsigned.
1105 bool FromIsSigned;
1106 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001107
1108 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1109 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110
1111 // The types we'll try to promote to, in the appropriate
1112 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001113 QualType PromoteTypes[6] = {
1114 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001115 Context.LongTy, Context.UnsignedLongTy ,
1116 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001117 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001118 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1120 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001121 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1123 // We found the type that we can promote to. If this is the
1124 // type we wanted, we have a promotion. Otherwise, no
1125 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001126 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127 }
1128 }
1129 }
1130
1131 // An rvalue for an integral bit-field (9.6) can be converted to an
1132 // rvalue of type int if int can represent all the values of the
1133 // bit-field; otherwise, it can be converted to unsigned int if
1134 // unsigned int can represent all the values of the bit-field. If
1135 // the bit-field is larger yet, no integral promotion applies to
1136 // it. If the bit-field has an enumerated type, it is treated as any
1137 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001138 // FIXME: We should delay checking of bit-fields until we actually perform the
1139 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001140 using llvm::APSInt;
1141 if (From)
1142 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001143 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +00001144 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1145 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1146 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1147 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001148
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001149 // Are we promoting to an int from a bitfield that fits in an int?
1150 if (BitWidth < ToSize ||
1151 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1152 return To->getKind() == BuiltinType::Int;
1153 }
Mike Stump11289f42009-09-09 15:08:12 +00001154
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001155 // Are we promoting to an unsigned int from an unsigned bitfield
1156 // that fits into an unsigned int?
1157 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1158 return To->getKind() == BuiltinType::UInt;
1159 }
Mike Stump11289f42009-09-09 15:08:12 +00001160
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001161 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001162 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 }
Mike Stump11289f42009-09-09 15:08:12 +00001164
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001165 // An rvalue of type bool can be converted to an rvalue of type int,
1166 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001167 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001169 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
1171 return false;
1172}
1173
1174/// IsFloatingPointPromotion - Determines whether the conversion from
1175/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1176/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001177bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001178 /// An rvalue of type float can be converted to an rvalue of type
1179 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001180 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1181 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001182 if (FromBuiltin->getKind() == BuiltinType::Float &&
1183 ToBuiltin->getKind() == BuiltinType::Double)
1184 return true;
1185
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001186 // C99 6.3.1.5p1:
1187 // When a float is promoted to double or long double, or a
1188 // double is promoted to long double [...].
1189 if (!getLangOptions().CPlusPlus &&
1190 (FromBuiltin->getKind() == BuiltinType::Float ||
1191 FromBuiltin->getKind() == BuiltinType::Double) &&
1192 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1193 return true;
1194 }
1195
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001196 return false;
1197}
1198
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001199/// \brief Determine if a conversion is a complex promotion.
1200///
1201/// A complex promotion is defined as a complex -> complex conversion
1202/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001203/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001204bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001205 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001206 if (!FromComplex)
1207 return false;
1208
John McCall9dd450b2009-09-21 23:43:11 +00001209 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001210 if (!ToComplex)
1211 return false;
1212
1213 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001214 ToComplex->getElementType()) ||
1215 IsIntegralPromotion(0, FromComplex->getElementType(),
1216 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001217}
1218
Douglas Gregor237f96c2008-11-26 23:31:11 +00001219/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1220/// the pointer type FromPtr to a pointer to type ToPointee, with the
1221/// same type qualifiers as FromPtr has on its pointee type. ToType,
1222/// if non-empty, will be a pointer to ToType that may or may not have
1223/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001224static QualType
1225BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001226 QualType ToPointee, QualType ToType,
1227 ASTContext &Context) {
1228 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1229 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001230 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001231
1232 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001233 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001234 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001235 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +00001236 return ToType;
1237
1238 // Build a pointer to ToPointee. It has the right qualifiers
1239 // already.
1240 return Context.getPointerType(ToPointee);
1241 }
1242
1243 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001244 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001245 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1246 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001247}
1248
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001249/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1250/// the FromType, which is an objective-c pointer, to ToType, which may or may
1251/// not have the right set of qualifiers.
1252static QualType
1253BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1254 QualType ToType,
1255 ASTContext &Context) {
1256 QualType CanonFromType = Context.getCanonicalType(FromType);
1257 QualType CanonToType = Context.getCanonicalType(ToType);
1258 Qualifiers Quals = CanonFromType.getQualifiers();
1259
1260 // Exact qualifier match -> return the pointer type we're converting to.
1261 if (CanonToType.getLocalQualifiers() == Quals)
1262 return ToType;
1263
1264 // Just build a canonical type that has the right qualifiers.
1265 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1266}
1267
Mike Stump11289f42009-09-09 15:08:12 +00001268static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001269 bool InOverloadResolution,
1270 ASTContext &Context) {
1271 // Handle value-dependent integral null pointer constants correctly.
1272 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1273 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1274 Expr->getType()->isIntegralType())
1275 return !InOverloadResolution;
1276
Douglas Gregor56751b52009-09-25 04:25:58 +00001277 return Expr->isNullPointerConstant(Context,
1278 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1279 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001280}
Mike Stump11289f42009-09-09 15:08:12 +00001281
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001282/// IsPointerConversion - Determines whether the conversion of the
1283/// expression From, which has the (possibly adjusted) type FromType,
1284/// can be converted to the type ToType via a pointer conversion (C++
1285/// 4.10). If so, returns true and places the converted type (that
1286/// might differ from ToType in its cv-qualifiers at some level) into
1287/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001288///
Douglas Gregora29dc052008-11-27 01:19:21 +00001289/// This routine also supports conversions to and from block pointers
1290/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1291/// pointers to interfaces. FIXME: Once we've determined the
1292/// appropriate overloading rules for Objective-C, we may want to
1293/// split the Objective-C checks into a different routine; however,
1294/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001295/// conversions, so for now they live here. IncompatibleObjC will be
1296/// set if the conversion is an allowed Objective-C conversion that
1297/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001298bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001299 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001300 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001301 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001302 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001303 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1304 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001305
Mike Stump11289f42009-09-09 15:08:12 +00001306 // Conversion from a null pointer constant to any Objective-C pointer type.
1307 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001308 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001309 ConvertedType = ToType;
1310 return true;
1311 }
1312
Douglas Gregor231d1c62008-11-27 00:15:41 +00001313 // Blocks: Block pointers can be converted to void*.
1314 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001315 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001316 ConvertedType = ToType;
1317 return true;
1318 }
1319 // Blocks: A null pointer constant can be converted to a block
1320 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001321 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001322 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001323 ConvertedType = ToType;
1324 return true;
1325 }
1326
Sebastian Redl576fd422009-05-10 18:38:11 +00001327 // If the left-hand-side is nullptr_t, the right side can be a null
1328 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001329 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001330 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001331 ConvertedType = ToType;
1332 return true;
1333 }
1334
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001335 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001336 if (!ToTypePtr)
1337 return false;
1338
1339 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001340 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001341 ConvertedType = ToType;
1342 return true;
1343 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001344
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001345 // Beyond this point, both types need to be pointers
1346 // , including objective-c pointers.
1347 QualType ToPointeeType = ToTypePtr->getPointeeType();
1348 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1349 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1350 ToType, Context);
1351 return true;
1352
1353 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001354 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001355 if (!FromTypePtr)
1356 return false;
1357
1358 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001359
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001360 // An rvalue of type "pointer to cv T," where T is an object type,
1361 // can be converted to an rvalue of type "pointer to cv void" (C++
1362 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001363 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001364 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001365 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001366 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001367 return true;
1368 }
1369
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001370 // When we're overloading in C, we allow a special kind of pointer
1371 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001372 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001373 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001374 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001375 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001376 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001377 return true;
1378 }
1379
Douglas Gregor5c407d92008-10-23 00:40:37 +00001380 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001381 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001382 // An rvalue of type "pointer to cv D," where D is a class type,
1383 // can be converted to an rvalue of type "pointer to cv B," where
1384 // B is a base class (clause 10) of D. If B is an inaccessible
1385 // (clause 11) or ambiguous (10.2) base class of D, a program that
1386 // necessitates this conversion is ill-formed. The result of the
1387 // conversion is a pointer to the base class sub-object of the
1388 // derived class object. The null pointer value is converted to
1389 // the null pointer value of the destination type.
1390 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001391 // Note that we do not check for ambiguity or inaccessibility
1392 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001393 if (getLangOptions().CPlusPlus &&
1394 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001395 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001396 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001397 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001398 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001399 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001400 ToType, Context);
1401 return true;
1402 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001403
Douglas Gregora119f102008-12-19 19:13:09 +00001404 return false;
1405}
1406
1407/// isObjCPointerConversion - Determines whether this is an
1408/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1409/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001410bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001411 QualType& ConvertedType,
1412 bool &IncompatibleObjC) {
1413 if (!getLangOptions().ObjC1)
1414 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001415
Steve Naroff7cae42b2009-07-10 23:34:53 +00001416 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001417 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001418 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001419 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001420
Steve Naroff7cae42b2009-07-10 23:34:53 +00001421 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001422 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001423 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001424 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001425 ConvertedType = ToType;
1426 return true;
1427 }
1428 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001429 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001430 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001431 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001432 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001433 ConvertedType = ToType;
1434 return true;
1435 }
1436 // Objective C++: We're able to convert from a pointer to an
1437 // interface to a pointer to a different interface.
1438 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001439 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1440 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1441 if (getLangOptions().CPlusPlus && LHS && RHS &&
1442 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1443 FromObjCPtr->getPointeeType()))
1444 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001445 ConvertedType = ToType;
1446 return true;
1447 }
1448
1449 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1450 // Okay: this is some kind of implicit downcast of Objective-C
1451 // interfaces, which is permitted. However, we're going to
1452 // complain about it.
1453 IncompatibleObjC = true;
1454 ConvertedType = FromType;
1455 return true;
1456 }
Mike Stump11289f42009-09-09 15:08:12 +00001457 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001458 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001459 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001460 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001461 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001462 else if (const BlockPointerType *ToBlockPtr =
1463 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001464 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001465 // to a block pointer type.
1466 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1467 ConvertedType = ToType;
1468 return true;
1469 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001470 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001471 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001472 else if (FromType->getAs<BlockPointerType>() &&
1473 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1474 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001475 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001476 ConvertedType = ToType;
1477 return true;
1478 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001479 else
Douglas Gregora119f102008-12-19 19:13:09 +00001480 return false;
1481
Douglas Gregor033f56d2008-12-23 00:53:59 +00001482 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001483 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001484 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001485 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001486 FromPointeeType = FromBlockPtr->getPointeeType();
1487 else
Douglas Gregora119f102008-12-19 19:13:09 +00001488 return false;
1489
Douglas Gregora119f102008-12-19 19:13:09 +00001490 // If we have pointers to pointers, recursively check whether this
1491 // is an Objective-C conversion.
1492 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1493 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1494 IncompatibleObjC)) {
1495 // We always complain about this conversion.
1496 IncompatibleObjC = true;
1497 ConvertedType = ToType;
1498 return true;
1499 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001500 // Allow conversion of pointee being objective-c pointer to another one;
1501 // as in I* to id.
1502 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1503 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1504 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1505 IncompatibleObjC)) {
1506 ConvertedType = ToType;
1507 return true;
1508 }
1509
Douglas Gregor033f56d2008-12-23 00:53:59 +00001510 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001511 // differences in the argument and result types are in Objective-C
1512 // pointer conversions. If so, we permit the conversion (but
1513 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001514 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001515 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001516 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001517 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001518 if (FromFunctionType && ToFunctionType) {
1519 // If the function types are exactly the same, this isn't an
1520 // Objective-C pointer conversion.
1521 if (Context.getCanonicalType(FromPointeeType)
1522 == Context.getCanonicalType(ToPointeeType))
1523 return false;
1524
1525 // Perform the quick checks that will tell us whether these
1526 // function types are obviously different.
1527 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1528 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1529 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1530 return false;
1531
1532 bool HasObjCConversion = false;
1533 if (Context.getCanonicalType(FromFunctionType->getResultType())
1534 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1535 // Okay, the types match exactly. Nothing to do.
1536 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1537 ToFunctionType->getResultType(),
1538 ConvertedType, IncompatibleObjC)) {
1539 // Okay, we have an Objective-C pointer conversion.
1540 HasObjCConversion = true;
1541 } else {
1542 // Function types are too different. Abort.
1543 return false;
1544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
Douglas Gregora119f102008-12-19 19:13:09 +00001546 // Check argument types.
1547 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1548 ArgIdx != NumArgs; ++ArgIdx) {
1549 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1550 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1551 if (Context.getCanonicalType(FromArgType)
1552 == Context.getCanonicalType(ToArgType)) {
1553 // Okay, the types match exactly. Nothing to do.
1554 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1555 ConvertedType, IncompatibleObjC)) {
1556 // Okay, we have an Objective-C pointer conversion.
1557 HasObjCConversion = true;
1558 } else {
1559 // Argument types are too different. Abort.
1560 return false;
1561 }
1562 }
1563
1564 if (HasObjCConversion) {
1565 // We had an Objective-C conversion. Allow this pointer
1566 // conversion, but complain about it.
1567 ConvertedType = ToType;
1568 IncompatibleObjC = true;
1569 return true;
1570 }
1571 }
1572
Sebastian Redl72b597d2009-01-25 19:43:20 +00001573 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001575
1576/// FunctionArgTypesAreEqual - This routine checks two function proto types
1577/// for equlity of their argument types. Caller has already checked that
1578/// they have same number of arguments. This routine assumes that Objective-C
1579/// pointer types which only differ in their protocol qualifiers are equal.
1580bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1581 FunctionProtoType* NewType){
1582 if (!getLangOptions().ObjC1)
1583 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1584 NewType->arg_type_begin());
1585
1586 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1587 N = NewType->arg_type_begin(),
1588 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1589 QualType ToType = (*O);
1590 QualType FromType = (*N);
1591 if (ToType != FromType) {
1592 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1593 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001594 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1595 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1596 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1597 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001598 continue;
1599 }
John McCall8b07ec22010-05-15 11:32:37 +00001600 else if (const ObjCObjectPointerType *PTTo =
1601 ToType->getAs<ObjCObjectPointerType>()) {
1602 if (const ObjCObjectPointerType *PTFr =
1603 FromType->getAs<ObjCObjectPointerType>())
1604 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1605 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001606 }
1607 return false;
1608 }
1609 }
1610 return true;
1611}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612
Douglas Gregor39c16d42008-10-24 04:54:22 +00001613/// CheckPointerConversion - Check the pointer conversion from the
1614/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001615/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001616/// conversions for which IsPointerConversion has already returned
1617/// true. It returns true and produces a diagnostic if there was an
1618/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001619bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001620 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001621 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001622 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001623 QualType FromType = From->getType();
1624
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001625 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1626 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001627 QualType FromPointeeType = FromPtrType->getPointeeType(),
1628 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001629
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001630 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1631 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001632 // We must have a derived-to-base conversion. Check an
1633 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001634 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1635 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001636 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001637 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001638 return true;
1639
1640 // The conversion was successful.
1641 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001642 }
1643 }
Mike Stump11289f42009-09-09 15:08:12 +00001644 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001645 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001646 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001647 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001648 // Objective-C++ conversions are always okay.
1649 // FIXME: We should have a different class of conversions for the
1650 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001651 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001652 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001653
Steve Naroff7cae42b2009-07-10 23:34:53 +00001654 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001655 return false;
1656}
1657
Sebastian Redl72b597d2009-01-25 19:43:20 +00001658/// IsMemberPointerConversion - Determines whether the conversion of the
1659/// expression From, which has the (possibly adjusted) type FromType, can be
1660/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1661/// If so, returns true and places the converted type (that might differ from
1662/// ToType in its cv-qualifiers at some level) into ConvertedType.
1663bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001664 QualType ToType,
1665 bool InOverloadResolution,
1666 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001667 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001668 if (!ToTypePtr)
1669 return false;
1670
1671 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001672 if (From->isNullPointerConstant(Context,
1673 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1674 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001675 ConvertedType = ToType;
1676 return true;
1677 }
1678
1679 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001680 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001681 if (!FromTypePtr)
1682 return false;
1683
1684 // A pointer to member of B can be converted to a pointer to member of D,
1685 // where D is derived from B (C++ 4.11p2).
1686 QualType FromClass(FromTypePtr->getClass(), 0);
1687 QualType ToClass(ToTypePtr->getClass(), 0);
1688 // FIXME: What happens when these are dependent? Is this function even called?
1689
1690 if (IsDerivedFrom(ToClass, FromClass)) {
1691 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1692 ToClass.getTypePtr());
1693 return true;
1694 }
1695
1696 return false;
1697}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001698
Sebastian Redl72b597d2009-01-25 19:43:20 +00001699/// CheckMemberPointerConversion - Check the member pointer conversion from the
1700/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001701/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001702/// for which IsMemberPointerConversion has already returned true. It returns
1703/// true and produces a diagnostic if there was an error, or returns false
1704/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001705bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001706 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001707 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001708 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001709 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001710 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001711 if (!FromPtrType) {
1712 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001713 assert(From->isNullPointerConstant(Context,
1714 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001715 "Expr must be null pointer constant!");
1716 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001717 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001718 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001719
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001720 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001721 assert(ToPtrType && "No member pointer cast has a target type "
1722 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001723
Sebastian Redled8f2002009-01-28 18:33:18 +00001724 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1725 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001726
Sebastian Redled8f2002009-01-28 18:33:18 +00001727 // FIXME: What about dependent types?
1728 assert(FromClass->isRecordType() && "Pointer into non-class.");
1729 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001730
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001731 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001732 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001733 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1734 assert(DerivationOkay &&
1735 "Should not have been called if derivation isn't OK.");
1736 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001737
Sebastian Redled8f2002009-01-28 18:33:18 +00001738 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1739 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001740 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1741 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1742 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1743 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001744 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001745
Douglas Gregor89ee6822009-02-28 01:32:25 +00001746 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001747 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1748 << FromClass << ToClass << QualType(VBase, 0)
1749 << From->getSourceRange();
1750 return true;
1751 }
1752
John McCall5b0829a2010-02-10 09:31:12 +00001753 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001754 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1755 Paths.front(),
1756 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001757
Anders Carlssond7923c62009-08-22 23:33:40 +00001758 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001759 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001760 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001761 return false;
1762}
1763
Douglas Gregor9a657932008-10-21 23:43:52 +00001764/// IsQualificationConversion - Determines whether the conversion from
1765/// an rvalue of type FromType to ToType is a qualification conversion
1766/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001767bool
1768Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001769 FromType = Context.getCanonicalType(FromType);
1770 ToType = Context.getCanonicalType(ToType);
1771
1772 // If FromType and ToType are the same type, this is not a
1773 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001774 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001775 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001776
Douglas Gregor9a657932008-10-21 23:43:52 +00001777 // (C++ 4.4p4):
1778 // A conversion can add cv-qualifiers at levels other than the first
1779 // in multi-level pointers, subject to the following rules: [...]
1780 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001781 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001782 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001783 // Within each iteration of the loop, we check the qualifiers to
1784 // determine if this still looks like a qualification
1785 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001786 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001787 // until there are no more pointers or pointers-to-members left to
1788 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001789 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001790
1791 // -- for every j > 0, if const is in cv 1,j then const is in cv
1792 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001793 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001794 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001795
Douglas Gregor9a657932008-10-21 23:43:52 +00001796 // -- if the cv 1,j and cv 2,j are different, then const is in
1797 // every cv for 0 < k < j.
1798 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001799 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001800 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001801
Douglas Gregor9a657932008-10-21 23:43:52 +00001802 // Keep track of whether all prior cv-qualifiers in the "to" type
1803 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001804 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001805 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001806 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001807
1808 // We are left with FromType and ToType being the pointee types
1809 // after unwrapping the original FromType and ToType the same number
1810 // of types. If we unwrapped any pointers, and if FromType and
1811 // ToType have the same unqualified type (since we checked
1812 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001813 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001814}
1815
Douglas Gregor576e98c2009-01-30 23:27:23 +00001816/// Determines whether there is a user-defined conversion sequence
1817/// (C++ [over.ics.user]) that converts expression From to the type
1818/// ToType. If such a conversion exists, User will contain the
1819/// user-defined conversion sequence that performs such a conversion
1820/// and this routine will return true. Otherwise, this routine returns
1821/// false and User is unspecified.
1822///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001823/// \param AllowExplicit true if the conversion should consider C++0x
1824/// "explicit" conversion functions as well as non-explicit conversion
1825/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001826OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1827 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001828 OverloadCandidateSet& CandidateSet,
1829 bool AllowExplicit) {
1830 // Whether we will only visit constructors.
1831 bool ConstructorsOnly = false;
1832
1833 // If the type we are conversion to is a class type, enumerate its
1834 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001835 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001836 // C++ [over.match.ctor]p1:
1837 // When objects of class type are direct-initialized (8.5), or
1838 // copy-initialized from an expression of the same or a
1839 // derived class type (8.5), overload resolution selects the
1840 // constructor. [...] For copy-initialization, the candidate
1841 // functions are all the converting constructors (12.3.1) of
1842 // that class. The argument list is the expression-list within
1843 // the parentheses of the initializer.
1844 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1845 (From->getType()->getAs<RecordType>() &&
1846 IsDerivedFrom(From->getType(), ToType)))
1847 ConstructorsOnly = true;
1848
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001849 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1850 // We're not going to find any constructors.
1851 } else if (CXXRecordDecl *ToRecordDecl
1852 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001853 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001854 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001855 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001856 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001857 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001858 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001859 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001860 NamedDecl *D = *Con;
1861 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1862
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001863 // Find the constructor (which may be a template).
1864 CXXConstructorDecl *Constructor = 0;
1865 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001866 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001867 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001868 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001869 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1870 else
John McCalla0296f72010-03-19 07:35:19 +00001871 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001872
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001873 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001874 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001875 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001876 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001877 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001878 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001879 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001880 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001881 // Allow one user-defined conversion when user specifies a
1882 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001883 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001884 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001885 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001886 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001887 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001888 }
1889 }
1890
Douglas Gregor5ab11652010-04-17 22:01:05 +00001891 // Enumerate conversion functions, if we're allowed to.
1892 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001893 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001894 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001895 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001896 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001897 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001898 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001899 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1900 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001901 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001902 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001903 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001904 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001905 DeclAccessPair FoundDecl = I.getPair();
1906 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001907 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1908 if (isa<UsingShadowDecl>(D))
1909 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1910
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001911 CXXConversionDecl *Conv;
1912 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001913 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1914 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001915 else
John McCallda4458e2010-03-31 01:36:47 +00001916 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001917
1918 if (AllowExplicit || !Conv->isExplicit()) {
1919 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001920 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001921 ActingContext, From, ToType,
1922 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001923 else
John McCalla0296f72010-03-19 07:35:19 +00001924 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001925 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001926 }
1927 }
1928 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001929 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001930
1931 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001932 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001933 case OR_Success:
1934 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001935 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001936 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1937 // C++ [over.ics.user]p1:
1938 // If the user-defined conversion is specified by a
1939 // constructor (12.3.1), the initial standard conversion
1940 // sequence converts the source type to the type required by
1941 // the argument of the constructor.
1942 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001943 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001944 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001945 User.EllipsisConversion = true;
1946 else {
1947 User.Before = Best->Conversions[0].Standard;
1948 User.EllipsisConversion = false;
1949 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001950 User.ConversionFunction = Constructor;
1951 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001952 User.After.setFromType(
1953 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001954 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001955 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001956 } else if (CXXConversionDecl *Conversion
1957 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1958 // C++ [over.ics.user]p1:
1959 //
1960 // [...] If the user-defined conversion is specified by a
1961 // conversion function (12.3.2), the initial standard
1962 // conversion sequence converts the source type to the
1963 // implicit object parameter of the conversion function.
1964 User.Before = Best->Conversions[0].Standard;
1965 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001966 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001967
1968 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001969 // The second standard conversion sequence converts the
1970 // result of the user-defined conversion to the target type
1971 // for the sequence. Since an implicit conversion sequence
1972 // is an initialization, the special rules for
1973 // initialization by user-defined conversion apply when
1974 // selecting the best user-defined conversion for a
1975 // user-defined conversion sequence (see 13.3.3 and
1976 // 13.3.3.1).
1977 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001978 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001979 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001980 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001981 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001984 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001985 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001986 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001987 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001988 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001989
1990 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001991 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001992 }
1993
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001994 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001995}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001996
1997bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001998Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001999 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002000 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002001 OverloadingResult OvResult =
2002 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002003 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002004 if (OvResult == OR_Ambiguous)
2005 Diag(From->getSourceRange().getBegin(),
2006 diag::err_typecheck_ambiguous_condition)
2007 << From->getType() << ToType << From->getSourceRange();
2008 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2009 Diag(From->getSourceRange().getBegin(),
2010 diag::err_typecheck_nonviable_condition)
2011 << From->getType() << ToType << From->getSourceRange();
2012 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002013 return false;
John McCallad907772010-01-12 07:18:19 +00002014 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002015 return true;
2016}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002017
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018/// CompareImplicitConversionSequences - Compare two implicit
2019/// conversion sequences to determine whether one is better than the
2020/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002021ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002022Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2023 const ImplicitConversionSequence& ICS2)
2024{
2025 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2026 // conversion sequences (as defined in 13.3.3.1)
2027 // -- a standard conversion sequence (13.3.3.1.1) is a better
2028 // conversion sequence than a user-defined conversion sequence or
2029 // an ellipsis conversion sequence, and
2030 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2031 // conversion sequence than an ellipsis conversion sequence
2032 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002033 //
John McCall0d1da222010-01-12 00:44:57 +00002034 // C++0x [over.best.ics]p10:
2035 // For the purpose of ranking implicit conversion sequences as
2036 // described in 13.3.3.2, the ambiguous conversion sequence is
2037 // treated as a user-defined sequence that is indistinguishable
2038 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002039 if (ICS1.getKindRank() < ICS2.getKindRank())
2040 return ImplicitConversionSequence::Better;
2041 else if (ICS2.getKindRank() < ICS1.getKindRank())
2042 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002043
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002044 // The following checks require both conversion sequences to be of
2045 // the same kind.
2046 if (ICS1.getKind() != ICS2.getKind())
2047 return ImplicitConversionSequence::Indistinguishable;
2048
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002049 // Two implicit conversion sequences of the same form are
2050 // indistinguishable conversion sequences unless one of the
2051 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002052 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002053 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002054 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055 // User-defined conversion sequence U1 is a better conversion
2056 // sequence than another user-defined conversion sequence U2 if
2057 // they contain the same user-defined conversion function or
2058 // constructor and if the second standard conversion sequence of
2059 // U1 is better than the second standard conversion sequence of
2060 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002061 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002062 ICS2.UserDefined.ConversionFunction)
2063 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2064 ICS2.UserDefined.After);
2065 }
2066
2067 return ImplicitConversionSequence::Indistinguishable;
2068}
2069
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002070// Per 13.3.3.2p3, compare the given standard conversion sequences to
2071// determine if one is a proper subset of the other.
2072static ImplicitConversionSequence::CompareKind
2073compareStandardConversionSubsets(ASTContext &Context,
2074 const StandardConversionSequence& SCS1,
2075 const StandardConversionSequence& SCS2) {
2076 ImplicitConversionSequence::CompareKind Result
2077 = ImplicitConversionSequence::Indistinguishable;
2078
Douglas Gregore87561a2010-05-23 22:10:15 +00002079 // the identity conversion sequence is considered to be a subsequence of
2080 // any non-identity conversion sequence
2081 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2082 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2083 return ImplicitConversionSequence::Better;
2084 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2085 return ImplicitConversionSequence::Worse;
2086 }
2087
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002088 if (SCS1.Second != SCS2.Second) {
2089 if (SCS1.Second == ICK_Identity)
2090 Result = ImplicitConversionSequence::Better;
2091 else if (SCS2.Second == ICK_Identity)
2092 Result = ImplicitConversionSequence::Worse;
2093 else
2094 return ImplicitConversionSequence::Indistinguishable;
2095 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
2096 return ImplicitConversionSequence::Indistinguishable;
2097
2098 if (SCS1.Third == SCS2.Third) {
2099 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2100 : ImplicitConversionSequence::Indistinguishable;
2101 }
2102
2103 if (SCS1.Third == ICK_Identity)
2104 return Result == ImplicitConversionSequence::Worse
2105 ? ImplicitConversionSequence::Indistinguishable
2106 : ImplicitConversionSequence::Better;
2107
2108 if (SCS2.Third == ICK_Identity)
2109 return Result == ImplicitConversionSequence::Better
2110 ? ImplicitConversionSequence::Indistinguishable
2111 : ImplicitConversionSequence::Worse;
2112
2113 return ImplicitConversionSequence::Indistinguishable;
2114}
2115
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002116/// CompareStandardConversionSequences - Compare two standard
2117/// conversion sequences to determine whether one is better than the
2118/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002119ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002120Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2121 const StandardConversionSequence& SCS2)
2122{
2123 // Standard conversion sequence S1 is a better conversion sequence
2124 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2125
2126 // -- S1 is a proper subsequence of S2 (comparing the conversion
2127 // sequences in the canonical form defined by 13.3.3.1.1,
2128 // excluding any Lvalue Transformation; the identity conversion
2129 // sequence is considered to be a subsequence of any
2130 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002131 if (ImplicitConversionSequence::CompareKind CK
2132 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2133 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002134
2135 // -- the rank of S1 is better than the rank of S2 (by the rules
2136 // defined below), or, if not that,
2137 ImplicitConversionRank Rank1 = SCS1.getRank();
2138 ImplicitConversionRank Rank2 = SCS2.getRank();
2139 if (Rank1 < Rank2)
2140 return ImplicitConversionSequence::Better;
2141 else if (Rank2 < Rank1)
2142 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002143
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002144 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2145 // are indistinguishable unless one of the following rules
2146 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002147
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002148 // A conversion that is not a conversion of a pointer, or
2149 // pointer to member, to bool is better than another conversion
2150 // that is such a conversion.
2151 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2152 return SCS2.isPointerConversionToBool()
2153 ? ImplicitConversionSequence::Better
2154 : ImplicitConversionSequence::Worse;
2155
Douglas Gregor5c407d92008-10-23 00:40:37 +00002156 // C++ [over.ics.rank]p4b2:
2157 //
2158 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002159 // conversion of B* to A* is better than conversion of B* to
2160 // void*, and conversion of A* to void* is better than conversion
2161 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002162 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002163 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002164 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002165 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002166 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2167 // Exactly one of the conversion sequences is a conversion to
2168 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002169 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2170 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002171 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2172 // Neither conversion sequence converts to a void pointer; compare
2173 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002174 if (ImplicitConversionSequence::CompareKind DerivedCK
2175 = CompareDerivedToBaseConversions(SCS1, SCS2))
2176 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002177 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2178 // Both conversion sequences are conversions to void
2179 // pointers. Compare the source types to determine if there's an
2180 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002181 QualType FromType1 = SCS1.getFromType();
2182 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002183
2184 // Adjust the types we're converting from via the array-to-pointer
2185 // conversion, if we need to.
2186 if (SCS1.First == ICK_Array_To_Pointer)
2187 FromType1 = Context.getArrayDecayedType(FromType1);
2188 if (SCS2.First == ICK_Array_To_Pointer)
2189 FromType2 = Context.getArrayDecayedType(FromType2);
2190
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002191 QualType FromPointee1
2192 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2193 QualType FromPointee2
2194 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002195
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002196 if (IsDerivedFrom(FromPointee2, FromPointee1))
2197 return ImplicitConversionSequence::Better;
2198 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2199 return ImplicitConversionSequence::Worse;
2200
2201 // Objective-C++: If one interface is more specific than the
2202 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002203 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2204 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002205 if (FromIface1 && FromIface1) {
2206 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2207 return ImplicitConversionSequence::Better;
2208 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2209 return ImplicitConversionSequence::Worse;
2210 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002211 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002212
2213 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2214 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002215 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002216 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002217 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002218
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002219 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002220 // C++0x [over.ics.rank]p3b4:
2221 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2222 // implicit object parameter of a non-static member function declared
2223 // without a ref-qualifier, and S1 binds an rvalue reference to an
2224 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002225 // FIXME: We don't know if we're dealing with the implicit object parameter,
2226 // or if the member function in this case has a ref qualifier.
2227 // (Of course, we don't have ref qualifiers yet.)
2228 if (SCS1.RRefBinding != SCS2.RRefBinding)
2229 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2230 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002231
2232 // C++ [over.ics.rank]p3b4:
2233 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2234 // which the references refer are the same type except for
2235 // top-level cv-qualifiers, and the type to which the reference
2236 // initialized by S2 refers is more cv-qualified than the type
2237 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002238 QualType T1 = SCS1.getToType(2);
2239 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002240 T1 = Context.getCanonicalType(T1);
2241 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002242 Qualifiers T1Quals, T2Quals;
2243 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2244 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2245 if (UnqualT1 == UnqualT2) {
2246 // If the type is an array type, promote the element qualifiers to the type
2247 // for comparison.
2248 if (isa<ArrayType>(T1) && T1Quals)
2249 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2250 if (isa<ArrayType>(T2) && T2Quals)
2251 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002252 if (T2.isMoreQualifiedThan(T1))
2253 return ImplicitConversionSequence::Better;
2254 else if (T1.isMoreQualifiedThan(T2))
2255 return ImplicitConversionSequence::Worse;
2256 }
2257 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002258
2259 return ImplicitConversionSequence::Indistinguishable;
2260}
2261
2262/// CompareQualificationConversions - Compares two standard conversion
2263/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002264/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2265ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002266Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002267 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002268 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002269 // -- S1 and S2 differ only in their qualification conversion and
2270 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2271 // cv-qualification signature of type T1 is a proper subset of
2272 // the cv-qualification signature of type T2, and S1 is not the
2273 // deprecated string literal array-to-pointer conversion (4.2).
2274 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2275 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2276 return ImplicitConversionSequence::Indistinguishable;
2277
2278 // FIXME: the example in the standard doesn't use a qualification
2279 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002280 QualType T1 = SCS1.getToType(2);
2281 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002282 T1 = Context.getCanonicalType(T1);
2283 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002284 Qualifiers T1Quals, T2Quals;
2285 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2286 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002287
2288 // If the types are the same, we won't learn anything by unwrapped
2289 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002290 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002291 return ImplicitConversionSequence::Indistinguishable;
2292
Chandler Carruth607f38e2009-12-29 07:16:59 +00002293 // If the type is an array type, promote the element qualifiers to the type
2294 // for comparison.
2295 if (isa<ArrayType>(T1) && T1Quals)
2296 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2297 if (isa<ArrayType>(T2) && T2Quals)
2298 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2299
Mike Stump11289f42009-09-09 15:08:12 +00002300 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002301 = ImplicitConversionSequence::Indistinguishable;
2302 while (UnwrapSimilarPointerTypes(T1, T2)) {
2303 // Within each iteration of the loop, we check the qualifiers to
2304 // determine if this still looks like a qualification
2305 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002306 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002307 // until there are no more pointers or pointers-to-members left
2308 // to unwrap. This essentially mimics what
2309 // IsQualificationConversion does, but here we're checking for a
2310 // strict subset of qualifiers.
2311 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2312 // The qualifiers are the same, so this doesn't tell us anything
2313 // about how the sequences rank.
2314 ;
2315 else if (T2.isMoreQualifiedThan(T1)) {
2316 // T1 has fewer qualifiers, so it could be the better sequence.
2317 if (Result == ImplicitConversionSequence::Worse)
2318 // Neither has qualifiers that are a subset of the other's
2319 // qualifiers.
2320 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002321
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002322 Result = ImplicitConversionSequence::Better;
2323 } else if (T1.isMoreQualifiedThan(T2)) {
2324 // T2 has fewer qualifiers, so it could be the better sequence.
2325 if (Result == ImplicitConversionSequence::Better)
2326 // Neither has qualifiers that are a subset of the other's
2327 // qualifiers.
2328 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002329
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002330 Result = ImplicitConversionSequence::Worse;
2331 } else {
2332 // Qualifiers are disjoint.
2333 return ImplicitConversionSequence::Indistinguishable;
2334 }
2335
2336 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002337 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002338 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002339 }
2340
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002341 // Check that the winning standard conversion sequence isn't using
2342 // the deprecated string literal array to pointer conversion.
2343 switch (Result) {
2344 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002345 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002346 Result = ImplicitConversionSequence::Indistinguishable;
2347 break;
2348
2349 case ImplicitConversionSequence::Indistinguishable:
2350 break;
2351
2352 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002353 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002354 Result = ImplicitConversionSequence::Indistinguishable;
2355 break;
2356 }
2357
2358 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002359}
2360
Douglas Gregor5c407d92008-10-23 00:40:37 +00002361/// CompareDerivedToBaseConversions - Compares two standard conversion
2362/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002363/// various kinds of derived-to-base conversions (C++
2364/// [over.ics.rank]p4b3). As part of these checks, we also look at
2365/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002366ImplicitConversionSequence::CompareKind
2367Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2368 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002369 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002370 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002371 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002372 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002373
2374 // Adjust the types we're converting from via the array-to-pointer
2375 // conversion, if we need to.
2376 if (SCS1.First == ICK_Array_To_Pointer)
2377 FromType1 = Context.getArrayDecayedType(FromType1);
2378 if (SCS2.First == ICK_Array_To_Pointer)
2379 FromType2 = Context.getArrayDecayedType(FromType2);
2380
2381 // Canonicalize all of the types.
2382 FromType1 = Context.getCanonicalType(FromType1);
2383 ToType1 = Context.getCanonicalType(ToType1);
2384 FromType2 = Context.getCanonicalType(FromType2);
2385 ToType2 = Context.getCanonicalType(ToType2);
2386
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002387 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002388 //
2389 // If class B is derived directly or indirectly from class A and
2390 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002391 //
2392 // For Objective-C, we let A, B, and C also be Objective-C
2393 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002394
2395 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002396 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002397 SCS2.Second == ICK_Pointer_Conversion &&
2398 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2399 FromType1->isPointerType() && FromType2->isPointerType() &&
2400 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002401 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002402 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002403 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002404 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002405 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002406 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002407 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002408 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002409
John McCall8b07ec22010-05-15 11:32:37 +00002410 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2411 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2412 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2413 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002414
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002415 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002416 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2417 if (IsDerivedFrom(ToPointee1, ToPointee2))
2418 return ImplicitConversionSequence::Better;
2419 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2420 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002421
2422 if (ToIface1 && ToIface2) {
2423 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2424 return ImplicitConversionSequence::Better;
2425 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2426 return ImplicitConversionSequence::Worse;
2427 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002428 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002429
2430 // -- conversion of B* to A* is better than conversion of C* to A*,
2431 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2432 if (IsDerivedFrom(FromPointee2, FromPointee1))
2433 return ImplicitConversionSequence::Better;
2434 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2435 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002436
Douglas Gregor237f96c2008-11-26 23:31:11 +00002437 if (FromIface1 && FromIface2) {
2438 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2439 return ImplicitConversionSequence::Better;
2440 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2441 return ImplicitConversionSequence::Worse;
2442 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002443 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002444 }
2445
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002446 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002447 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2448 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2449 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2450 const MemberPointerType * FromMemPointer1 =
2451 FromType1->getAs<MemberPointerType>();
2452 const MemberPointerType * ToMemPointer1 =
2453 ToType1->getAs<MemberPointerType>();
2454 const MemberPointerType * FromMemPointer2 =
2455 FromType2->getAs<MemberPointerType>();
2456 const MemberPointerType * ToMemPointer2 =
2457 ToType2->getAs<MemberPointerType>();
2458 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2459 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2460 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2461 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2462 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2463 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2464 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2465 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002466 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002467 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2468 if (IsDerivedFrom(ToPointee1, ToPointee2))
2469 return ImplicitConversionSequence::Worse;
2470 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2471 return ImplicitConversionSequence::Better;
2472 }
2473 // conversion of B::* to C::* is better than conversion of A::* to C::*
2474 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2475 if (IsDerivedFrom(FromPointee1, FromPointee2))
2476 return ImplicitConversionSequence::Better;
2477 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2478 return ImplicitConversionSequence::Worse;
2479 }
2480 }
2481
Douglas Gregor5ab11652010-04-17 22:01:05 +00002482 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002483 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002484 // -- binding of an expression of type C to a reference of type
2485 // B& is better than binding an expression of type C to a
2486 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002487 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2488 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002489 if (IsDerivedFrom(ToType1, ToType2))
2490 return ImplicitConversionSequence::Better;
2491 else if (IsDerivedFrom(ToType2, ToType1))
2492 return ImplicitConversionSequence::Worse;
2493 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002494
Douglas Gregor2fe98832008-11-03 19:09:14 +00002495 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002496 // -- binding of an expression of type B to a reference of type
2497 // A& is better than binding an expression of type C to a
2498 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002499 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2500 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002501 if (IsDerivedFrom(FromType2, FromType1))
2502 return ImplicitConversionSequence::Better;
2503 else if (IsDerivedFrom(FromType1, FromType2))
2504 return ImplicitConversionSequence::Worse;
2505 }
2506 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002507
Douglas Gregor5c407d92008-10-23 00:40:37 +00002508 return ImplicitConversionSequence::Indistinguishable;
2509}
2510
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002511/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2512/// determine whether they are reference-related,
2513/// reference-compatible, reference-compatible with added
2514/// qualification, or incompatible, for use in C++ initialization by
2515/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2516/// type, and the first type (T1) is the pointee type of the reference
2517/// type being initialized.
2518Sema::ReferenceCompareResult
2519Sema::CompareReferenceRelationship(SourceLocation Loc,
2520 QualType OrigT1, QualType OrigT2,
2521 bool& DerivedToBase) {
2522 assert(!OrigT1->isReferenceType() &&
2523 "T1 must be the pointee type of the reference type");
2524 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2525
2526 QualType T1 = Context.getCanonicalType(OrigT1);
2527 QualType T2 = Context.getCanonicalType(OrigT2);
2528 Qualifiers T1Quals, T2Quals;
2529 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2530 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2531
2532 // C++ [dcl.init.ref]p4:
2533 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2534 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2535 // T1 is a base class of T2.
2536 if (UnqualT1 == UnqualT2)
2537 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002538 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002539 IsDerivedFrom(UnqualT2, UnqualT1))
2540 DerivedToBase = true;
2541 else
2542 return Ref_Incompatible;
2543
2544 // At this point, we know that T1 and T2 are reference-related (at
2545 // least).
2546
2547 // If the type is an array type, promote the element qualifiers to the type
2548 // for comparison.
2549 if (isa<ArrayType>(T1) && T1Quals)
2550 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2551 if (isa<ArrayType>(T2) && T2Quals)
2552 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2553
2554 // C++ [dcl.init.ref]p4:
2555 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2556 // reference-related to T2 and cv1 is the same cv-qualification
2557 // as, or greater cv-qualification than, cv2. For purposes of
2558 // overload resolution, cases for which cv1 is greater
2559 // cv-qualification than cv2 are identified as
2560 // reference-compatible with added qualification (see 13.3.3.2).
2561 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2562 return Ref_Compatible;
2563 else if (T1.isMoreQualifiedThan(T2))
2564 return Ref_Compatible_With_Added_Qualification;
2565 else
2566 return Ref_Related;
2567}
2568
2569/// \brief Compute an implicit conversion sequence for reference
2570/// initialization.
2571static ImplicitConversionSequence
2572TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2573 SourceLocation DeclLoc,
2574 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002575 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002576 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2577
2578 // Most paths end in a failed conversion.
2579 ImplicitConversionSequence ICS;
2580 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2581
2582 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2583 QualType T2 = Init->getType();
2584
2585 // If the initializer is the address of an overloaded function, try
2586 // to resolve the overloaded function. If all goes well, T2 is the
2587 // type of the resulting function.
2588 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2589 DeclAccessPair Found;
2590 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2591 false, Found))
2592 T2 = Fn->getType();
2593 }
2594
2595 // Compute some basic properties of the types and the initializer.
2596 bool isRValRef = DeclType->isRValueReferenceType();
2597 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002598 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002599 Sema::ReferenceCompareResult RefRelationship
2600 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2601
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002602
2603 // C++ [over.ics.ref]p3:
2604 // Except for an implicit object parameter, for which see 13.3.1,
2605 // a standard conversion sequence cannot be formed if it requires
2606 // binding an lvalue reference to non-const to an rvalue or
2607 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002608 //
2609 // FIXME: DPG doesn't trust this code. It seems far too early to
2610 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002611 if (isRValRef && InitLvalue == Expr::LV_Valid)
2612 return ICS;
2613
Douglas Gregor870f3742010-04-18 09:22:00 +00002614 // C++0x [dcl.init.ref]p16:
2615 // A reference to type "cv1 T1" is initialized by an expression
2616 // of type "cv2 T2" as follows:
2617
2618 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002619 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2620 // reference-compatible with "cv2 T2," or
2621 //
2622 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2623 if (InitLvalue == Expr::LV_Valid &&
2624 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2625 // C++ [over.ics.ref]p1:
2626 // When a parameter of reference type binds directly (8.5.3)
2627 // to an argument expression, the implicit conversion sequence
2628 // is the identity conversion, unless the argument expression
2629 // has a type that is a derived class of the parameter type,
2630 // in which case the implicit conversion sequence is a
2631 // derived-to-base Conversion (13.3.3.1).
2632 ICS.setStandard();
2633 ICS.Standard.First = ICK_Identity;
2634 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2635 ICS.Standard.Third = ICK_Identity;
2636 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2637 ICS.Standard.setToType(0, T2);
2638 ICS.Standard.setToType(1, T1);
2639 ICS.Standard.setToType(2, T1);
2640 ICS.Standard.ReferenceBinding = true;
2641 ICS.Standard.DirectBinding = true;
2642 ICS.Standard.RRefBinding = false;
2643 ICS.Standard.CopyConstructor = 0;
2644
2645 // Nothing more to do: the inaccessibility/ambiguity check for
2646 // derived-to-base conversions is suppressed when we're
2647 // computing the implicit conversion sequence (C++
2648 // [over.best.ics]p2).
2649 return ICS;
2650 }
2651
2652 // -- has a class type (i.e., T2 is a class type), where T1 is
2653 // not reference-related to T2, and can be implicitly
2654 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2655 // is reference-compatible with "cv3 T3" 92) (this
2656 // conversion is selected by enumerating the applicable
2657 // conversion functions (13.3.1.6) and choosing the best
2658 // one through overload resolution (13.3)),
2659 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2660 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2661 RefRelationship == Sema::Ref_Incompatible) {
2662 CXXRecordDecl *T2RecordDecl
2663 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2664
2665 OverloadCandidateSet CandidateSet(DeclLoc);
2666 const UnresolvedSetImpl *Conversions
2667 = T2RecordDecl->getVisibleConversionFunctions();
2668 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2669 E = Conversions->end(); I != E; ++I) {
2670 NamedDecl *D = *I;
2671 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2672 if (isa<UsingShadowDecl>(D))
2673 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2674
2675 FunctionTemplateDecl *ConvTemplate
2676 = dyn_cast<FunctionTemplateDecl>(D);
2677 CXXConversionDecl *Conv;
2678 if (ConvTemplate)
2679 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2680 else
2681 Conv = cast<CXXConversionDecl>(D);
2682
2683 // If the conversion function doesn't return a reference type,
2684 // it can't be considered for this conversion.
2685 if (Conv->getConversionType()->isLValueReferenceType() &&
2686 (AllowExplicit || !Conv->isExplicit())) {
2687 if (ConvTemplate)
2688 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2689 Init, DeclType, CandidateSet);
2690 else
2691 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2692 DeclType, CandidateSet);
2693 }
2694 }
2695
2696 OverloadCandidateSet::iterator Best;
2697 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2698 case OR_Success:
2699 // C++ [over.ics.ref]p1:
2700 //
2701 // [...] If the parameter binds directly to the result of
2702 // applying a conversion function to the argument
2703 // expression, the implicit conversion sequence is a
2704 // user-defined conversion sequence (13.3.3.1.2), with the
2705 // second standard conversion sequence either an identity
2706 // conversion or, if the conversion function returns an
2707 // entity of a type that is a derived class of the parameter
2708 // type, a derived-to-base Conversion.
2709 if (!Best->FinalConversion.DirectBinding)
2710 break;
2711
2712 ICS.setUserDefined();
2713 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2714 ICS.UserDefined.After = Best->FinalConversion;
2715 ICS.UserDefined.ConversionFunction = Best->Function;
2716 ICS.UserDefined.EllipsisConversion = false;
2717 assert(ICS.UserDefined.After.ReferenceBinding &&
2718 ICS.UserDefined.After.DirectBinding &&
2719 "Expected a direct reference binding!");
2720 return ICS;
2721
2722 case OR_Ambiguous:
2723 ICS.setAmbiguous();
2724 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2725 Cand != CandidateSet.end(); ++Cand)
2726 if (Cand->Viable)
2727 ICS.Ambiguous.addConversion(Cand->Function);
2728 return ICS;
2729
2730 case OR_No_Viable_Function:
2731 case OR_Deleted:
2732 // There was no suitable conversion, or we found a deleted
2733 // conversion; continue with other checks.
2734 break;
2735 }
2736 }
2737
2738 // -- Otherwise, the reference shall be to a non-volatile const
2739 // type (i.e., cv1 shall be const), or the reference shall be an
2740 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002741 //
2742 // We actually handle one oddity of C++ [over.ics.ref] at this
2743 // point, which is that, due to p2 (which short-circuits reference
2744 // binding by only attempting a simple conversion for non-direct
2745 // bindings) and p3's strange wording, we allow a const volatile
2746 // reference to bind to an rvalue. Hence the check for the presence
2747 // of "const" rather than checking for "const" being the only
2748 // qualifier.
2749 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002750 return ICS;
2751
Douglas Gregorf93df192010-04-18 08:46:23 +00002752 // -- if T2 is a class type and
2753 // -- the initializer expression is an rvalue and "cv1 T1"
2754 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002755 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002756 // -- T1 is not reference-related to T2 and the initializer
2757 // expression can be implicitly converted to an rvalue
2758 // of type "cv3 T3" (this conversion is selected by
2759 // enumerating the applicable conversion functions
2760 // (13.3.1.6) and choosing the best one through overload
2761 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002762 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002763 // then the reference is bound to the initializer
2764 // expression rvalue in the first case and to the object
2765 // that is the result of the conversion in the second case
2766 // (or, in either case, to the appropriate base class
2767 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002768 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002769 // We're only checking the first case here, which is a direct
2770 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002771 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2772 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2773 ICS.setStandard();
2774 ICS.Standard.First = ICK_Identity;
2775 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2776 ICS.Standard.Third = ICK_Identity;
2777 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2778 ICS.Standard.setToType(0, T2);
2779 ICS.Standard.setToType(1, T1);
2780 ICS.Standard.setToType(2, T1);
2781 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002782 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002783 ICS.Standard.RRefBinding = isRValRef;
2784 ICS.Standard.CopyConstructor = 0;
2785 return ICS;
2786 }
2787
2788 // -- Otherwise, a temporary of type "cv1 T1" is created and
2789 // initialized from the initializer expression using the
2790 // rules for a non-reference copy initialization (8.5). The
2791 // reference is then bound to the temporary. If T1 is
2792 // reference-related to T2, cv1 must be the same
2793 // cv-qualification as, or greater cv-qualification than,
2794 // cv2; otherwise, the program is ill-formed.
2795 if (RefRelationship == Sema::Ref_Related) {
2796 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2797 // we would be reference-compatible or reference-compatible with
2798 // added qualification. But that wasn't the case, so the reference
2799 // initialization fails.
2800 return ICS;
2801 }
2802
2803 // If at least one of the types is a class type, the types are not
2804 // related, and we aren't allowed any user conversions, the
2805 // reference binding fails. This case is important for breaking
2806 // recursion, since TryImplicitConversion below will attempt to
2807 // create a temporary through the use of a copy constructor.
2808 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2809 (T1->isRecordType() || T2->isRecordType()))
2810 return ICS;
2811
2812 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002813 // When a parameter of reference type is not bound directly to
2814 // an argument expression, the conversion sequence is the one
2815 // required to convert the argument expression to the
2816 // underlying type of the reference according to
2817 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2818 // to copy-initializing a temporary of the underlying type with
2819 // the argument expression. Any difference in top-level
2820 // cv-qualification is subsumed by the initialization itself
2821 // and does not constitute a conversion.
2822 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2823 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002824 /*InOverloadResolution=*/false);
2825
2826 // Of course, that's still a reference binding.
2827 if (ICS.isStandard()) {
2828 ICS.Standard.ReferenceBinding = true;
2829 ICS.Standard.RRefBinding = isRValRef;
2830 } else if (ICS.isUserDefined()) {
2831 ICS.UserDefined.After.ReferenceBinding = true;
2832 ICS.UserDefined.After.RRefBinding = isRValRef;
2833 }
2834 return ICS;
2835}
2836
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002837/// TryCopyInitialization - Try to copy-initialize a value of type
2838/// ToType from the expression From. Return the implicit conversion
2839/// sequence required to pass this argument, which may be a bad
2840/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002841/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002842/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002843static ImplicitConversionSequence
2844TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002845 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002846 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002847 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002848 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002849 /*FIXME:*/From->getLocStart(),
2850 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002851 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002852
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002853 return S.TryImplicitConversion(From, ToType,
2854 SuppressUserConversions,
2855 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002856 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002857}
2858
Douglas Gregor436424c2008-11-18 23:14:02 +00002859/// TryObjectArgumentInitialization - Try to initialize the object
2860/// parameter of the given member function (@c Method) from the
2861/// expression @p From.
2862ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002863Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002864 CXXMethodDecl *Method,
2865 CXXRecordDecl *ActingContext) {
2866 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002867 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2868 // const volatile object.
2869 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2870 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2871 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002872
2873 // Set up the conversion sequence as a "bad" conversion, to allow us
2874 // to exit early.
2875 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002876
2877 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002878 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002879 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002880 FromType = PT->getPointeeType();
2881
2882 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002883
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002884 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002885 // where X is the class of which the function is a member
2886 // (C++ [over.match.funcs]p4). However, when finding an implicit
2887 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002888 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002889 // (C++ [over.match.funcs]p5). We perform a simplified version of
2890 // reference binding here, that allows class rvalues to bind to
2891 // non-constant references.
2892
2893 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2894 // with the implicit object parameter (C++ [over.match.funcs]p5).
2895 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002896 if (ImplicitParamType.getCVRQualifiers()
2897 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002898 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002899 ICS.setBad(BadConversionSequence::bad_qualifiers,
2900 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002901 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002902 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002903
2904 // Check that we have either the same type or a derived type. It
2905 // affects the conversion rank.
2906 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002907 ImplicitConversionKind SecondKind;
2908 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2909 SecondKind = ICK_Identity;
2910 } else if (IsDerivedFrom(FromType, ClassType))
2911 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002912 else {
John McCall65eb8792010-02-25 01:37:24 +00002913 ICS.setBad(BadConversionSequence::unrelated_class,
2914 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002915 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002916 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002917
2918 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002919 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002920 ICS.Standard.setAsIdentityConversion();
2921 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002922 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002923 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002924 ICS.Standard.ReferenceBinding = true;
2925 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002926 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002927 return ICS;
2928}
2929
2930/// PerformObjectArgumentInitialization - Perform initialization of
2931/// the implicit object parameter for the given Method with the given
2932/// expression.
2933bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002934Sema::PerformObjectArgumentInitialization(Expr *&From,
2935 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002936 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002937 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002938 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002939 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002940 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002941
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002942 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002943 FromRecordType = PT->getPointeeType();
2944 DestType = Method->getThisType(Context);
2945 } else {
2946 FromRecordType = From->getType();
2947 DestType = ImplicitParamRecordType;
2948 }
2949
John McCall6e9f8f62009-12-03 04:06:58 +00002950 // Note that we always use the true parent context when performing
2951 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002952 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002953 = TryObjectArgumentInitialization(From->getType(), Method,
2954 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002955 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002956 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002957 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002958 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002959
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002960 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002961 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002962
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002963 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002964 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2965 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002966 return false;
2967}
2968
Douglas Gregor5fb53972009-01-14 15:45:31 +00002969/// TryContextuallyConvertToBool - Attempt to contextually convert the
2970/// expression From to bool (C++0x [conv]p3).
2971ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002972 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00002973 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002974 // FIXME: Are these flags correct?
2975 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002976 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002977 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002978}
2979
2980/// PerformContextuallyConvertToBool - Perform a contextual conversion
2981/// of the expression From to bool (C++0x [conv]p3).
2982bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2983 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002984 if (!ICS.isBad())
2985 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002986
Fariborz Jahanian76197412009-11-18 18:26:29 +00002987 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002988 return Diag(From->getSourceRange().getBegin(),
2989 diag::err_typecheck_bool_condition)
2990 << From->getType() << From->getSourceRange();
2991 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002992}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00002993
2994/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
2995/// expression From to 'id'.
2996ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00002997 QualType Ty = Context.getObjCIdType();
2998 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00002999 // FIXME: Are these flags correct?
3000 /*SuppressUserConversions=*/false,
3001 /*AllowExplicit=*/true,
3002 /*InOverloadResolution=*/false);
3003}
3004
3005/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3006/// of the expression From to 'id'.
3007bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003008 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003009 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3010 if (!ICS.isBad())
3011 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3012 return true;
3013}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003014
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003015/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003016/// candidate functions, using the given function call arguments. If
3017/// @p SuppressUserConversions, then don't allow user-defined
3018/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003019///
3020/// \para PartialOverloading true if we are performing "partial" overloading
3021/// based on an incomplete set of function arguments. This feature is used by
3022/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003023void
3024Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003025 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003026 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003027 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003028 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003029 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003030 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003031 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003032 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003033 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003034 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003035
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003036 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003037 if (!isa<CXXConstructorDecl>(Method)) {
3038 // If we get here, it's because we're calling a member function
3039 // that is named without a member access expression (e.g.,
3040 // "this->f") that was either written explicitly or created
3041 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003042 // function, e.g., X::f(). We use an empty type for the implied
3043 // object argument (C++ [over.call.func]p3), and the acting context
3044 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003045 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003046 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003047 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003048 return;
3049 }
3050 // We treat a constructor like a non-member function, since its object
3051 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003052 }
3053
Douglas Gregorff7028a2009-11-13 23:59:09 +00003054 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003055 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003056
Douglas Gregor27381f32009-11-23 12:27:39 +00003057 // Overload resolution is always an unevaluated context.
3058 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3059
Douglas Gregorffe14e32009-11-14 01:20:54 +00003060 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3061 // C++ [class.copy]p3:
3062 // A member function template is never instantiated to perform the copy
3063 // of a class object to an object of its class type.
3064 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3065 if (NumArgs == 1 &&
3066 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003067 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3068 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003069 return;
3070 }
3071
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003072 // Add this candidate
3073 CandidateSet.push_back(OverloadCandidate());
3074 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003075 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003076 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003077 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003078 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003079 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003080
3081 unsigned NumArgsInProto = Proto->getNumArgs();
3082
3083 // (C++ 13.3.2p2): A candidate function having fewer than m
3084 // parameters is viable only if it has an ellipsis in its parameter
3085 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003086 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3087 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003088 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003089 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003090 return;
3091 }
3092
3093 // (C++ 13.3.2p2): A candidate function having more than m parameters
3094 // is viable only if the (m+1)st parameter has a default argument
3095 // (8.3.6). For the purposes of overload resolution, the
3096 // parameter list is truncated on the right, so that there are
3097 // exactly m parameters.
3098 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003099 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003100 // Not enough arguments.
3101 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003102 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003103 return;
3104 }
3105
3106 // Determine the implicit conversion sequences for each of the
3107 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003108 Candidate.Conversions.resize(NumArgs);
3109 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3110 if (ArgIdx < NumArgsInProto) {
3111 // (C++ 13.3.2p3): for F to be a viable function, there shall
3112 // exist for each argument an implicit conversion sequence
3113 // (13.3.3.1) that converts that argument to the corresponding
3114 // parameter of F.
3115 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003116 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003117 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003118 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003119 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003120 if (Candidate.Conversions[ArgIdx].isBad()) {
3121 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003122 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003123 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003124 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003125 } else {
3126 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3127 // argument for which there is no corresponding parameter is
3128 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003129 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003130 }
3131 }
3132}
3133
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003134/// \brief Add all of the function declarations in the given function set to
3135/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003136void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003137 Expr **Args, unsigned NumArgs,
3138 OverloadCandidateSet& CandidateSet,
3139 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003140 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003141 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3142 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003143 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003144 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003145 cast<CXXMethodDecl>(FD)->getParent(),
3146 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003147 CandidateSet, SuppressUserConversions);
3148 else
John McCalla0296f72010-03-19 07:35:19 +00003149 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003150 SuppressUserConversions);
3151 } else {
John McCalla0296f72010-03-19 07:35:19 +00003152 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003153 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3154 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003155 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003156 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003157 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003158 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003159 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003160 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003161 else
John McCalla0296f72010-03-19 07:35:19 +00003162 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003163 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003164 Args, NumArgs, CandidateSet,
3165 SuppressUserConversions);
3166 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003167 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003168}
3169
John McCallf0f1cf02009-11-17 07:50:12 +00003170/// AddMethodCandidate - Adds a named decl (which is some kind of
3171/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003172void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003173 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003174 Expr **Args, unsigned NumArgs,
3175 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003176 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003177 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003178 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003179
3180 if (isa<UsingShadowDecl>(Decl))
3181 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3182
3183 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3184 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3185 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003186 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3187 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003188 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003189 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003190 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003191 } else {
John McCalla0296f72010-03-19 07:35:19 +00003192 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003193 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003194 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003195 }
3196}
3197
Douglas Gregor436424c2008-11-18 23:14:02 +00003198/// AddMethodCandidate - Adds the given C++ member function to the set
3199/// of candidate functions, using the given function call arguments
3200/// and the object argument (@c Object). For example, in a call
3201/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3202/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3203/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003204/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003205void
John McCalla0296f72010-03-19 07:35:19 +00003206Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003207 CXXRecordDecl *ActingContext, QualType ObjectType,
3208 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003209 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003210 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003211 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003212 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003213 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003214 assert(!isa<CXXConstructorDecl>(Method) &&
3215 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003216
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003217 if (!CandidateSet.isNewCandidate(Method))
3218 return;
3219
Douglas Gregor27381f32009-11-23 12:27:39 +00003220 // Overload resolution is always an unevaluated context.
3221 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3222
Douglas Gregor436424c2008-11-18 23:14:02 +00003223 // Add this candidate
3224 CandidateSet.push_back(OverloadCandidate());
3225 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003226 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003227 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003228 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003229 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003230
3231 unsigned NumArgsInProto = Proto->getNumArgs();
3232
3233 // (C++ 13.3.2p2): A candidate function having fewer than m
3234 // parameters is viable only if it has an ellipsis in its parameter
3235 // list (8.3.5).
3236 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3237 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003238 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003239 return;
3240 }
3241
3242 // (C++ 13.3.2p2): A candidate function having more than m parameters
3243 // is viable only if the (m+1)st parameter has a default argument
3244 // (8.3.6). For the purposes of overload resolution, the
3245 // parameter list is truncated on the right, so that there are
3246 // exactly m parameters.
3247 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3248 if (NumArgs < MinRequiredArgs) {
3249 // Not enough arguments.
3250 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003251 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003252 return;
3253 }
3254
3255 Candidate.Viable = true;
3256 Candidate.Conversions.resize(NumArgs + 1);
3257
John McCall6e9f8f62009-12-03 04:06:58 +00003258 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003259 // The implicit object argument is ignored.
3260 Candidate.IgnoreObjectArgument = true;
3261 else {
3262 // Determine the implicit conversion sequence for the object
3263 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003264 Candidate.Conversions[0]
3265 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003266 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003267 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003268 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003269 return;
3270 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003271 }
3272
3273 // Determine the implicit conversion sequences for each of the
3274 // arguments.
3275 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3276 if (ArgIdx < NumArgsInProto) {
3277 // (C++ 13.3.2p3): for F to be a viable function, there shall
3278 // exist for each argument an implicit conversion sequence
3279 // (13.3.3.1) that converts that argument to the corresponding
3280 // parameter of F.
3281 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003282 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003283 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003284 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003285 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003286 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003287 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003288 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003289 break;
3290 }
3291 } else {
3292 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3293 // argument for which there is no corresponding parameter is
3294 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003295 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003296 }
3297 }
3298}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003299
Douglas Gregor97628d62009-08-21 00:16:32 +00003300/// \brief Add a C++ member function template as a candidate to the candidate
3301/// set, using template argument deduction to produce an appropriate member
3302/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003303void
Douglas Gregor97628d62009-08-21 00:16:32 +00003304Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003305 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003306 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003307 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003308 QualType ObjectType,
3309 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003310 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003311 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003312 if (!CandidateSet.isNewCandidate(MethodTmpl))
3313 return;
3314
Douglas Gregor97628d62009-08-21 00:16:32 +00003315 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003316 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003317 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003318 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003319 // candidate functions in the usual way.113) A given name can refer to one
3320 // or more function templates and also to a set of overloaded non-template
3321 // functions. In such a case, the candidate functions generated from each
3322 // function template are combined with the set of non-template candidate
3323 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003324 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003325 FunctionDecl *Specialization = 0;
3326 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003327 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003328 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003329 CandidateSet.push_back(OverloadCandidate());
3330 OverloadCandidate &Candidate = CandidateSet.back();
3331 Candidate.FoundDecl = FoundDecl;
3332 Candidate.Function = MethodTmpl->getTemplatedDecl();
3333 Candidate.Viable = false;
3334 Candidate.FailureKind = ovl_fail_bad_deduction;
3335 Candidate.IsSurrogate = false;
3336 Candidate.IgnoreObjectArgument = false;
3337 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3338 Info);
3339 return;
3340 }
Mike Stump11289f42009-09-09 15:08:12 +00003341
Douglas Gregor97628d62009-08-21 00:16:32 +00003342 // Add the function template specialization produced by template argument
3343 // deduction as a candidate.
3344 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003345 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003346 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003347 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003348 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003349 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003350}
3351
Douglas Gregor05155d82009-08-21 23:19:43 +00003352/// \brief Add a C++ function template specialization as a candidate
3353/// in the candidate set, using template argument deduction to produce
3354/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003355void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003356Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003357 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003358 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003359 Expr **Args, unsigned NumArgs,
3360 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003361 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003362 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3363 return;
3364
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003365 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003366 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003367 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003368 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003369 // candidate functions in the usual way.113) A given name can refer to one
3370 // or more function templates and also to a set of overloaded non-template
3371 // functions. In such a case, the candidate functions generated from each
3372 // function template are combined with the set of non-template candidate
3373 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003374 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003375 FunctionDecl *Specialization = 0;
3376 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003377 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003378 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003379 CandidateSet.push_back(OverloadCandidate());
3380 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003381 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003382 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3383 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003384 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003385 Candidate.IsSurrogate = false;
3386 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003387 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3388 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003389 return;
3390 }
Mike Stump11289f42009-09-09 15:08:12 +00003391
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003392 // Add the function template specialization produced by template argument
3393 // deduction as a candidate.
3394 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003395 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003396 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003397}
Mike Stump11289f42009-09-09 15:08:12 +00003398
Douglas Gregora1f013e2008-11-07 22:36:19 +00003399/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003400/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003401/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003402/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003403/// (which may or may not be the same type as the type that the
3404/// conversion function produces).
3405void
3406Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003407 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003408 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003409 Expr *From, QualType ToType,
3410 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003411 assert(!Conversion->getDescribedFunctionTemplate() &&
3412 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003413 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003414 if (!CandidateSet.isNewCandidate(Conversion))
3415 return;
3416
Douglas Gregor27381f32009-11-23 12:27:39 +00003417 // Overload resolution is always an unevaluated context.
3418 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3419
Douglas Gregora1f013e2008-11-07 22:36:19 +00003420 // Add this candidate
3421 CandidateSet.push_back(OverloadCandidate());
3422 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003423 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003424 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003425 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003426 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003427 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003428 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003429 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003430
Douglas Gregor436424c2008-11-18 23:14:02 +00003431 // Determine the implicit conversion sequence for the implicit
3432 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003433 Candidate.Viable = true;
3434 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003435 Candidate.Conversions[0]
3436 = TryObjectArgumentInitialization(From->getType(), Conversion,
3437 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003438 // Conversion functions to a different type in the base class is visible in
3439 // the derived class. So, a derived to base conversion should not participate
3440 // in overload resolution.
3441 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3442 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003443 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003444 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003445 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003446 return;
3447 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003448
3449 // We won't go through a user-define type conversion function to convert a
3450 // derived to base as such conversions are given Conversion Rank. They only
3451 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3452 QualType FromCanon
3453 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3454 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3455 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3456 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003457 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003458 return;
3459 }
3460
Douglas Gregora1f013e2008-11-07 22:36:19 +00003461 // To determine what the conversion from the result of calling the
3462 // conversion function to the type we're eventually trying to
3463 // convert to (ToType), we need to synthesize a call to the
3464 // conversion function and attempt copy initialization from it. This
3465 // makes sure that we get the right semantics with respect to
3466 // lvalues/rvalues and the type. Fortunately, we can allocate this
3467 // call on the stack and we don't need its arguments to be
3468 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003469 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003470 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003471 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003472 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003473 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003474
3475 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003476 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3477 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003478 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003479 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003480 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003481 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003482 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003483 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003484 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003485
John McCall0d1da222010-01-12 00:44:57 +00003486 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003487 case ImplicitConversionSequence::StandardConversion:
3488 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003489
3490 // C++ [over.ics.user]p3:
3491 // If the user-defined conversion is specified by a specialization of a
3492 // conversion function template, the second standard conversion sequence
3493 // shall have exact match rank.
3494 if (Conversion->getPrimaryTemplate() &&
3495 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3496 Candidate.Viable = false;
3497 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3498 }
3499
Douglas Gregora1f013e2008-11-07 22:36:19 +00003500 break;
3501
3502 case ImplicitConversionSequence::BadConversion:
3503 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003504 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003505 break;
3506
3507 default:
Mike Stump11289f42009-09-09 15:08:12 +00003508 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003509 "Can only end up with a standard conversion sequence or failure");
3510 }
3511}
3512
Douglas Gregor05155d82009-08-21 23:19:43 +00003513/// \brief Adds a conversion function template specialization
3514/// candidate to the overload set, using template argument deduction
3515/// to deduce the template arguments of the conversion function
3516/// template from the type that we are converting to (C++
3517/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003518void
Douglas Gregor05155d82009-08-21 23:19:43 +00003519Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003520 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003521 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003522 Expr *From, QualType ToType,
3523 OverloadCandidateSet &CandidateSet) {
3524 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3525 "Only conversion function templates permitted here");
3526
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003527 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3528 return;
3529
John McCallbc077cf2010-02-08 23:07:23 +00003530 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003531 CXXConversionDecl *Specialization = 0;
3532 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003533 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003534 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003535 CandidateSet.push_back(OverloadCandidate());
3536 OverloadCandidate &Candidate = CandidateSet.back();
3537 Candidate.FoundDecl = FoundDecl;
3538 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3539 Candidate.Viable = false;
3540 Candidate.FailureKind = ovl_fail_bad_deduction;
3541 Candidate.IsSurrogate = false;
3542 Candidate.IgnoreObjectArgument = false;
3543 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3544 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003545 return;
3546 }
Mike Stump11289f42009-09-09 15:08:12 +00003547
Douglas Gregor05155d82009-08-21 23:19:43 +00003548 // Add the conversion function template specialization produced by
3549 // template argument deduction as a candidate.
3550 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003551 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003552 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003553}
3554
Douglas Gregorab7897a2008-11-19 22:57:39 +00003555/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3556/// converts the given @c Object to a function pointer via the
3557/// conversion function @c Conversion, and then attempts to call it
3558/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3559/// the type of function that we'll eventually be calling.
3560void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003561 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003562 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003563 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003564 QualType ObjectType,
3565 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003566 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003567 if (!CandidateSet.isNewCandidate(Conversion))
3568 return;
3569
Douglas Gregor27381f32009-11-23 12:27:39 +00003570 // Overload resolution is always an unevaluated context.
3571 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3572
Douglas Gregorab7897a2008-11-19 22:57:39 +00003573 CandidateSet.push_back(OverloadCandidate());
3574 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003575 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003576 Candidate.Function = 0;
3577 Candidate.Surrogate = Conversion;
3578 Candidate.Viable = true;
3579 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003580 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003581 Candidate.Conversions.resize(NumArgs + 1);
3582
3583 // Determine the implicit conversion sequence for the implicit
3584 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003585 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003586 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003587 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003588 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003589 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003590 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003591 return;
3592 }
3593
3594 // The first conversion is actually a user-defined conversion whose
3595 // first conversion is ObjectInit's standard conversion (which is
3596 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003597 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003598 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003599 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003600 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003601 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003602 = Candidate.Conversions[0].UserDefined.Before;
3603 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3604
Mike Stump11289f42009-09-09 15:08:12 +00003605 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003606 unsigned NumArgsInProto = Proto->getNumArgs();
3607
3608 // (C++ 13.3.2p2): A candidate function having fewer than m
3609 // parameters is viable only if it has an ellipsis in its parameter
3610 // list (8.3.5).
3611 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3612 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003613 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003614 return;
3615 }
3616
3617 // Function types don't have any default arguments, so just check if
3618 // we have enough arguments.
3619 if (NumArgs < NumArgsInProto) {
3620 // Not enough arguments.
3621 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003622 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003623 return;
3624 }
3625
3626 // Determine the implicit conversion sequences for each of the
3627 // arguments.
3628 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3629 if (ArgIdx < NumArgsInProto) {
3630 // (C++ 13.3.2p3): for F to be a viable function, there shall
3631 // exist for each argument an implicit conversion sequence
3632 // (13.3.3.1) that converts that argument to the corresponding
3633 // parameter of F.
3634 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003635 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003636 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003637 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003638 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003639 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003640 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003641 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003642 break;
3643 }
3644 } else {
3645 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3646 // argument for which there is no corresponding parameter is
3647 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003648 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003649 }
3650 }
3651}
3652
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003653/// \brief Add overload candidates for overloaded operators that are
3654/// member functions.
3655///
3656/// Add the overloaded operator candidates that are member functions
3657/// for the operator Op that was used in an operator expression such
3658/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3659/// CandidateSet will store the added overload candidates. (C++
3660/// [over.match.oper]).
3661void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3662 SourceLocation OpLoc,
3663 Expr **Args, unsigned NumArgs,
3664 OverloadCandidateSet& CandidateSet,
3665 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003666 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3667
3668 // C++ [over.match.oper]p3:
3669 // For a unary operator @ with an operand of a type whose
3670 // cv-unqualified version is T1, and for a binary operator @ with
3671 // a left operand of a type whose cv-unqualified version is T1 and
3672 // a right operand of a type whose cv-unqualified version is T2,
3673 // three sets of candidate functions, designated member
3674 // candidates, non-member candidates and built-in candidates, are
3675 // constructed as follows:
3676 QualType T1 = Args[0]->getType();
3677 QualType T2;
3678 if (NumArgs > 1)
3679 T2 = Args[1]->getType();
3680
3681 // -- If T1 is a class type, the set of member candidates is the
3682 // result of the qualified lookup of T1::operator@
3683 // (13.3.1.1.1); otherwise, the set of member candidates is
3684 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003685 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003686 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003687 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003688 return;
Mike Stump11289f42009-09-09 15:08:12 +00003689
John McCall27b18f82009-11-17 02:14:36 +00003690 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3691 LookupQualifiedName(Operators, T1Rec->getDecl());
3692 Operators.suppressDiagnostics();
3693
Mike Stump11289f42009-09-09 15:08:12 +00003694 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003695 OperEnd = Operators.end();
3696 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003697 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003698 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003699 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003700 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003701 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003702}
3703
Douglas Gregora11693b2008-11-12 17:17:38 +00003704/// AddBuiltinCandidate - Add a candidate for a built-in
3705/// operator. ResultTy and ParamTys are the result and parameter types
3706/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003707/// arguments being passed to the candidate. IsAssignmentOperator
3708/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003709/// operator. NumContextualBoolArguments is the number of arguments
3710/// (at the beginning of the argument list) that will be contextually
3711/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003712void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003713 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003714 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003715 bool IsAssignmentOperator,
3716 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003717 // Overload resolution is always an unevaluated context.
3718 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3719
Douglas Gregora11693b2008-11-12 17:17:38 +00003720 // Add this candidate
3721 CandidateSet.push_back(OverloadCandidate());
3722 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003723 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003724 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003725 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003726 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003727 Candidate.BuiltinTypes.ResultTy = ResultTy;
3728 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3729 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3730
3731 // Determine the implicit conversion sequences for each of the
3732 // arguments.
3733 Candidate.Viable = true;
3734 Candidate.Conversions.resize(NumArgs);
3735 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003736 // C++ [over.match.oper]p4:
3737 // For the built-in assignment operators, conversions of the
3738 // left operand are restricted as follows:
3739 // -- no temporaries are introduced to hold the left operand, and
3740 // -- no user-defined conversions are applied to the left
3741 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003742 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003743 //
3744 // We block these conversions by turning off user-defined
3745 // conversions, since that is the only way that initialization of
3746 // a reference to a non-class type can occur from something that
3747 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003748 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003749 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003750 "Contextual conversion to bool requires bool type");
3751 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3752 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003753 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003754 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003755 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003756 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003757 }
John McCall0d1da222010-01-12 00:44:57 +00003758 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003759 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003760 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003761 break;
3762 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003763 }
3764}
3765
3766/// BuiltinCandidateTypeSet - A set of types that will be used for the
3767/// candidate operator functions for built-in operators (C++
3768/// [over.built]). The types are separated into pointer types and
3769/// enumeration types.
3770class BuiltinCandidateTypeSet {
3771 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003772 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003773
3774 /// PointerTypes - The set of pointer types that will be used in the
3775 /// built-in candidates.
3776 TypeSet PointerTypes;
3777
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003778 /// MemberPointerTypes - The set of member pointer types that will be
3779 /// used in the built-in candidates.
3780 TypeSet MemberPointerTypes;
3781
Douglas Gregora11693b2008-11-12 17:17:38 +00003782 /// EnumerationTypes - The set of enumeration types that will be
3783 /// used in the built-in candidates.
3784 TypeSet EnumerationTypes;
3785
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003786 /// \brief The set of vector types that will be used in the built-in
3787 /// candidates.
3788 TypeSet VectorTypes;
3789
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003790 /// Sema - The semantic analysis instance where we are building the
3791 /// candidate type set.
3792 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003793
Douglas Gregora11693b2008-11-12 17:17:38 +00003794 /// Context - The AST context in which we will build the type sets.
3795 ASTContext &Context;
3796
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003797 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3798 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003799 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003800
3801public:
3802 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003803 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003804
Mike Stump11289f42009-09-09 15:08:12 +00003805 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003806 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003807
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003808 void AddTypesConvertedFrom(QualType Ty,
3809 SourceLocation Loc,
3810 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003811 bool AllowExplicitConversions,
3812 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003813
3814 /// pointer_begin - First pointer type found;
3815 iterator pointer_begin() { return PointerTypes.begin(); }
3816
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003817 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003818 iterator pointer_end() { return PointerTypes.end(); }
3819
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003820 /// member_pointer_begin - First member pointer type found;
3821 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3822
3823 /// member_pointer_end - Past the last member pointer type found;
3824 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3825
Douglas Gregora11693b2008-11-12 17:17:38 +00003826 /// enumeration_begin - First enumeration type found;
3827 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3828
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003829 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003830 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003831
3832 iterator vector_begin() { return VectorTypes.begin(); }
3833 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00003834};
3835
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003836/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003837/// the set of pointer types along with any more-qualified variants of
3838/// that type. For example, if @p Ty is "int const *", this routine
3839/// will add "int const *", "int const volatile *", "int const
3840/// restrict *", and "int const volatile restrict *" to the set of
3841/// pointer types. Returns true if the add of @p Ty itself succeeded,
3842/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003843///
3844/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003845bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003846BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3847 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003848
Douglas Gregora11693b2008-11-12 17:17:38 +00003849 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003850 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003851 return false;
3852
John McCall8ccfcb52009-09-24 19:53:00 +00003853 const PointerType *PointerTy = Ty->getAs<PointerType>();
3854 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003855
John McCall8ccfcb52009-09-24 19:53:00 +00003856 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003857 // Don't add qualified variants of arrays. For one, they're not allowed
3858 // (the qualifier would sink to the element type), and for another, the
3859 // only overload situation where it matters is subscript or pointer +- int,
3860 // and those shouldn't have qualifier variants anyway.
3861 if (PointeeTy->isArrayType())
3862 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003863 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003864 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003865 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003866 bool hasVolatile = VisibleQuals.hasVolatile();
3867 bool hasRestrict = VisibleQuals.hasRestrict();
3868
John McCall8ccfcb52009-09-24 19:53:00 +00003869 // Iterate through all strict supersets of BaseCVR.
3870 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3871 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003872 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3873 // in the types.
3874 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3875 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003876 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3877 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003878 }
3879
3880 return true;
3881}
3882
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003883/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3884/// to the set of pointer types along with any more-qualified variants of
3885/// that type. For example, if @p Ty is "int const *", this routine
3886/// will add "int const *", "int const volatile *", "int const
3887/// restrict *", and "int const volatile restrict *" to the set of
3888/// pointer types. Returns true if the add of @p Ty itself succeeded,
3889/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003890///
3891/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003892bool
3893BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3894 QualType Ty) {
3895 // Insert this type.
3896 if (!MemberPointerTypes.insert(Ty))
3897 return false;
3898
John McCall8ccfcb52009-09-24 19:53:00 +00003899 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3900 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003901
John McCall8ccfcb52009-09-24 19:53:00 +00003902 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003903 // Don't add qualified variants of arrays. For one, they're not allowed
3904 // (the qualifier would sink to the element type), and for another, the
3905 // only overload situation where it matters is subscript or pointer +- int,
3906 // and those shouldn't have qualifier variants anyway.
3907 if (PointeeTy->isArrayType())
3908 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003909 const Type *ClassTy = PointerTy->getClass();
3910
3911 // Iterate through all strict supersets of the pointee type's CVR
3912 // qualifiers.
3913 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3914 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3915 if ((CVR | BaseCVR) != CVR) continue;
3916
3917 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3918 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003919 }
3920
3921 return true;
3922}
3923
Douglas Gregora11693b2008-11-12 17:17:38 +00003924/// AddTypesConvertedFrom - Add each of the types to which the type @p
3925/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003926/// primarily interested in pointer types and enumeration types. We also
3927/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003928/// AllowUserConversions is true if we should look at the conversion
3929/// functions of a class type, and AllowExplicitConversions if we
3930/// should also include the explicit conversion functions of a class
3931/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003932void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003933BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003934 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003935 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003936 bool AllowExplicitConversions,
3937 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003938 // Only deal with canonical types.
3939 Ty = Context.getCanonicalType(Ty);
3940
3941 // Look through reference types; they aren't part of the type of an
3942 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003943 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003944 Ty = RefTy->getPointeeType();
3945
3946 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003947 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003948
Sebastian Redl65ae2002009-11-05 16:36:20 +00003949 // If we're dealing with an array type, decay to the pointer.
3950 if (Ty->isArrayType())
3951 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3952
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003953 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003954 QualType PointeeTy = PointerTy->getPointeeType();
3955
3956 // Insert our type, and its more-qualified variants, into the set
3957 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003958 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003959 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003960 } else if (Ty->isMemberPointerType()) {
3961 // Member pointers are far easier, since the pointee can't be converted.
3962 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3963 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003964 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003965 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003966 } else if (Ty->isVectorType()) {
3967 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003968 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003969 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003970 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003971 // No conversion functions in incomplete types.
3972 return;
3973 }
Mike Stump11289f42009-09-09 15:08:12 +00003974
Douglas Gregora11693b2008-11-12 17:17:38 +00003975 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003976 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003977 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003978 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003979 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003980 NamedDecl *D = I.getDecl();
3981 if (isa<UsingShadowDecl>(D))
3982 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003983
Mike Stump11289f42009-09-09 15:08:12 +00003984 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003985 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003986 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003987 continue;
3988
John McCallda4458e2010-03-31 01:36:47 +00003989 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003990 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003991 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003992 VisibleQuals);
3993 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003994 }
3995 }
3996 }
3997}
3998
Douglas Gregor84605ae2009-08-24 13:43:27 +00003999/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4000/// the volatile- and non-volatile-qualified assignment operators for the
4001/// given type to the candidate set.
4002static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4003 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004004 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004005 unsigned NumArgs,
4006 OverloadCandidateSet &CandidateSet) {
4007 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004008
Douglas Gregor84605ae2009-08-24 13:43:27 +00004009 // T& operator=(T&, T)
4010 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4011 ParamTypes[1] = T;
4012 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4013 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004014
Douglas Gregor84605ae2009-08-24 13:43:27 +00004015 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4016 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004017 ParamTypes[0]
4018 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004019 ParamTypes[1] = T;
4020 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004021 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004022 }
4023}
Mike Stump11289f42009-09-09 15:08:12 +00004024
Sebastian Redl1054fae2009-10-25 17:03:50 +00004025/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4026/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004027static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4028 Qualifiers VRQuals;
4029 const RecordType *TyRec;
4030 if (const MemberPointerType *RHSMPType =
4031 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004032 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004033 else
4034 TyRec = ArgExpr->getType()->getAs<RecordType>();
4035 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004036 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004037 VRQuals.addVolatile();
4038 VRQuals.addRestrict();
4039 return VRQuals;
4040 }
4041
4042 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004043 if (!ClassDecl->hasDefinition())
4044 return VRQuals;
4045
John McCallad371252010-01-20 00:46:10 +00004046 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004047 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004048
John McCallad371252010-01-20 00:46:10 +00004049 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004050 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004051 NamedDecl *D = I.getDecl();
4052 if (isa<UsingShadowDecl>(D))
4053 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4054 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004055 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4056 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4057 CanTy = ResTypeRef->getPointeeType();
4058 // Need to go down the pointer/mempointer chain and add qualifiers
4059 // as see them.
4060 bool done = false;
4061 while (!done) {
4062 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4063 CanTy = ResTypePtr->getPointeeType();
4064 else if (const MemberPointerType *ResTypeMPtr =
4065 CanTy->getAs<MemberPointerType>())
4066 CanTy = ResTypeMPtr->getPointeeType();
4067 else
4068 done = true;
4069 if (CanTy.isVolatileQualified())
4070 VRQuals.addVolatile();
4071 if (CanTy.isRestrictQualified())
4072 VRQuals.addRestrict();
4073 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4074 return VRQuals;
4075 }
4076 }
4077 }
4078 return VRQuals;
4079}
4080
Douglas Gregord08452f2008-11-19 15:42:04 +00004081/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4082/// operator overloads to the candidate set (C++ [over.built]), based
4083/// on the operator @p Op and the arguments given. For example, if the
4084/// operator is a binary '+', this routine might add "int
4085/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004086void
Mike Stump11289f42009-09-09 15:08:12 +00004087Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004088 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004089 Expr **Args, unsigned NumArgs,
4090 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004091 // The set of "promoted arithmetic types", which are the arithmetic
4092 // types are that preserved by promotion (C++ [over.built]p2). Note
4093 // that the first few of these types are the promoted integral
4094 // types; these types need to be first.
4095 // FIXME: What about complex?
4096 const unsigned FirstIntegralType = 0;
4097 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004098 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004099 LastPromotedIntegralType = 13;
4100 const unsigned FirstPromotedArithmeticType = 7,
4101 LastPromotedArithmeticType = 16;
4102 const unsigned NumArithmeticTypes = 16;
4103 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004104 Context.BoolTy, Context.CharTy, Context.WCharTy,
4105// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004106 Context.SignedCharTy, Context.ShortTy,
4107 Context.UnsignedCharTy, Context.UnsignedShortTy,
4108 Context.IntTy, Context.LongTy, Context.LongLongTy,
4109 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4110 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4111 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004112 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4113 "Invalid first promoted integral type");
4114 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4115 == Context.UnsignedLongLongTy &&
4116 "Invalid last promoted integral type");
4117 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4118 "Invalid first promoted arithmetic type");
4119 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4120 == Context.LongDoubleTy &&
4121 "Invalid last promoted arithmetic type");
4122
Douglas Gregora11693b2008-11-12 17:17:38 +00004123 // Find all of the types that the arguments can convert to, but only
4124 // if the operator we're looking at has built-in operator candidates
4125 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004126 Qualifiers VisibleTypeConversionsQuals;
4127 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004128 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4129 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4130
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004131 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004132 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4133 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4134 OpLoc,
4135 true,
4136 (Op == OO_Exclaim ||
4137 Op == OO_AmpAmp ||
4138 Op == OO_PipePipe),
4139 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004140
4141 bool isComparison = false;
4142 switch (Op) {
4143 case OO_None:
4144 case NUM_OVERLOADED_OPERATORS:
4145 assert(false && "Expected an overloaded operator");
4146 break;
4147
Douglas Gregord08452f2008-11-19 15:42:04 +00004148 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004149 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004150 goto UnaryStar;
4151 else
4152 goto BinaryStar;
4153 break;
4154
4155 case OO_Plus: // '+' is either unary or binary
4156 if (NumArgs == 1)
4157 goto UnaryPlus;
4158 else
4159 goto BinaryPlus;
4160 break;
4161
4162 case OO_Minus: // '-' is either unary or binary
4163 if (NumArgs == 1)
4164 goto UnaryMinus;
4165 else
4166 goto BinaryMinus;
4167 break;
4168
4169 case OO_Amp: // '&' is either unary or binary
4170 if (NumArgs == 1)
4171 goto UnaryAmp;
4172 else
4173 goto BinaryAmp;
4174
4175 case OO_PlusPlus:
4176 case OO_MinusMinus:
4177 // C++ [over.built]p3:
4178 //
4179 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4180 // is either volatile or empty, there exist candidate operator
4181 // functions of the form
4182 //
4183 // VQ T& operator++(VQ T&);
4184 // T operator++(VQ T&, int);
4185 //
4186 // C++ [over.built]p4:
4187 //
4188 // For every pair (T, VQ), where T is an arithmetic type other
4189 // than bool, and VQ is either volatile or empty, there exist
4190 // candidate operator functions of the form
4191 //
4192 // VQ T& operator--(VQ T&);
4193 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004194 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004195 Arith < NumArithmeticTypes; ++Arith) {
4196 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004197 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004198 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004199
4200 // Non-volatile version.
4201 if (NumArgs == 1)
4202 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4203 else
4204 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004205 // heuristic to reduce number of builtin candidates in the set.
4206 // Add volatile version only if there are conversions to a volatile type.
4207 if (VisibleTypeConversionsQuals.hasVolatile()) {
4208 // Volatile version
4209 ParamTypes[0]
4210 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4211 if (NumArgs == 1)
4212 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4213 else
4214 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4215 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004216 }
4217
4218 // C++ [over.built]p5:
4219 //
4220 // For every pair (T, VQ), where T is a cv-qualified or
4221 // cv-unqualified object type, and VQ is either volatile or
4222 // empty, there exist candidate operator functions of the form
4223 //
4224 // T*VQ& operator++(T*VQ&);
4225 // T*VQ& operator--(T*VQ&);
4226 // T* operator++(T*VQ&, int);
4227 // T* operator--(T*VQ&, int);
4228 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4229 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4230 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004231 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004232 continue;
4233
Mike Stump11289f42009-09-09 15:08:12 +00004234 QualType ParamTypes[2] = {
4235 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004236 };
Mike Stump11289f42009-09-09 15:08:12 +00004237
Douglas Gregord08452f2008-11-19 15:42:04 +00004238 // Without volatile
4239 if (NumArgs == 1)
4240 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4241 else
4242 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4243
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004244 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4245 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004246 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004247 ParamTypes[0]
4248 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004249 if (NumArgs == 1)
4250 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4251 else
4252 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4253 }
4254 }
4255 break;
4256
4257 UnaryStar:
4258 // C++ [over.built]p6:
4259 // For every cv-qualified or cv-unqualified object type T, there
4260 // exist candidate operator functions of the form
4261 //
4262 // T& operator*(T*);
4263 //
4264 // C++ [over.built]p7:
4265 // For every function type T, there exist candidate operator
4266 // functions of the form
4267 // T& operator*(T*);
4268 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4269 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4270 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004271 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004272 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004273 &ParamTy, Args, 1, CandidateSet);
4274 }
4275 break;
4276
4277 UnaryPlus:
4278 // C++ [over.built]p8:
4279 // For every type T, there exist candidate operator functions of
4280 // the form
4281 //
4282 // T* operator+(T*);
4283 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4284 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4285 QualType ParamTy = *Ptr;
4286 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288
Douglas Gregord08452f2008-11-19 15:42:04 +00004289 // Fall through
4290
4291 UnaryMinus:
4292 // C++ [over.built]p9:
4293 // For every promoted arithmetic type T, there exist candidate
4294 // operator functions of the form
4295 //
4296 // T operator+(T);
4297 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004298 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004299 Arith < LastPromotedArithmeticType; ++Arith) {
4300 QualType ArithTy = ArithmeticTypes[Arith];
4301 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4302 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004303
4304 // Extension: We also add these operators for vector types.
4305 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4306 VecEnd = CandidateTypes.vector_end();
4307 Vec != VecEnd; ++Vec) {
4308 QualType VecTy = *Vec;
4309 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4310 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004311 break;
4312
4313 case OO_Tilde:
4314 // C++ [over.built]p10:
4315 // For every promoted integral type T, there exist candidate
4316 // operator functions of the form
4317 //
4318 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004319 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004320 Int < LastPromotedIntegralType; ++Int) {
4321 QualType IntTy = ArithmeticTypes[Int];
4322 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4323 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004324
4325 // Extension: We also add this operator for vector types.
4326 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4327 VecEnd = CandidateTypes.vector_end();
4328 Vec != VecEnd; ++Vec) {
4329 QualType VecTy = *Vec;
4330 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4331 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004332 break;
4333
Douglas Gregora11693b2008-11-12 17:17:38 +00004334 case OO_New:
4335 case OO_Delete:
4336 case OO_Array_New:
4337 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004338 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004339 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004340 break;
4341
4342 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004343 UnaryAmp:
4344 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004345 // C++ [over.match.oper]p3:
4346 // -- For the operator ',', the unary operator '&', or the
4347 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004348 break;
4349
Douglas Gregor84605ae2009-08-24 13:43:27 +00004350 case OO_EqualEqual:
4351 case OO_ExclaimEqual:
4352 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004353 // For every pointer to member type T, there exist candidate operator
4354 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004355 //
4356 // bool operator==(T,T);
4357 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004358 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004359 MemPtr = CandidateTypes.member_pointer_begin(),
4360 MemPtrEnd = CandidateTypes.member_pointer_end();
4361 MemPtr != MemPtrEnd;
4362 ++MemPtr) {
4363 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4364 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4365 }
Mike Stump11289f42009-09-09 15:08:12 +00004366
Douglas Gregor84605ae2009-08-24 13:43:27 +00004367 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004368
Douglas Gregora11693b2008-11-12 17:17:38 +00004369 case OO_Less:
4370 case OO_Greater:
4371 case OO_LessEqual:
4372 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004373 // C++ [over.built]p15:
4374 //
4375 // For every pointer or enumeration type T, there exist
4376 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004377 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004378 // bool operator<(T, T);
4379 // bool operator>(T, T);
4380 // bool operator<=(T, T);
4381 // bool operator>=(T, T);
4382 // bool operator==(T, T);
4383 // bool operator!=(T, T);
4384 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4385 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4386 QualType ParamTypes[2] = { *Ptr, *Ptr };
4387 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4388 }
Mike Stump11289f42009-09-09 15:08:12 +00004389 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004390 = CandidateTypes.enumeration_begin();
4391 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4392 QualType ParamTypes[2] = { *Enum, *Enum };
4393 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4394 }
4395
4396 // Fall through.
4397 isComparison = true;
4398
Douglas Gregord08452f2008-11-19 15:42:04 +00004399 BinaryPlus:
4400 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004401 if (!isComparison) {
4402 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4403
4404 // C++ [over.built]p13:
4405 //
4406 // For every cv-qualified or cv-unqualified object type T
4407 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004408 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004409 // T* operator+(T*, ptrdiff_t);
4410 // T& operator[](T*, ptrdiff_t); [BELOW]
4411 // T* operator-(T*, ptrdiff_t);
4412 // T* operator+(ptrdiff_t, T*);
4413 // T& operator[](ptrdiff_t, T*); [BELOW]
4414 //
4415 // C++ [over.built]p14:
4416 //
4417 // For every T, where T is a pointer to object type, there
4418 // exist candidate operator functions of the form
4419 //
4420 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004421 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004422 = CandidateTypes.pointer_begin();
4423 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4424 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4425
4426 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4427 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4428
4429 if (Op == OO_Plus) {
4430 // T* operator+(ptrdiff_t, T*);
4431 ParamTypes[0] = ParamTypes[1];
4432 ParamTypes[1] = *Ptr;
4433 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4434 } else {
4435 // ptrdiff_t operator-(T, T);
4436 ParamTypes[1] = *Ptr;
4437 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4438 Args, 2, CandidateSet);
4439 }
4440 }
4441 }
4442 // Fall through
4443
Douglas Gregora11693b2008-11-12 17:17:38 +00004444 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004445 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004446 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004447 // C++ [over.built]p12:
4448 //
4449 // For every pair of promoted arithmetic types L and R, there
4450 // exist candidate operator functions of the form
4451 //
4452 // LR operator*(L, R);
4453 // LR operator/(L, R);
4454 // LR operator+(L, R);
4455 // LR operator-(L, R);
4456 // bool operator<(L, R);
4457 // bool operator>(L, R);
4458 // bool operator<=(L, R);
4459 // bool operator>=(L, R);
4460 // bool operator==(L, R);
4461 // bool operator!=(L, R);
4462 //
4463 // where LR is the result of the usual arithmetic conversions
4464 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004465 //
4466 // C++ [over.built]p24:
4467 //
4468 // For every pair of promoted arithmetic types L and R, there exist
4469 // candidate operator functions of the form
4470 //
4471 // LR operator?(bool, L, R);
4472 //
4473 // where LR is the result of the usual arithmetic conversions
4474 // between types L and R.
4475 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004476 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004477 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004478 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004479 Right < LastPromotedArithmeticType; ++Right) {
4480 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004481 QualType Result
4482 = isComparison
4483 ? Context.BoolTy
4484 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004485 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4486 }
4487 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004488
4489 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4490 // conditional operator for vector types.
4491 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4492 Vec1End = CandidateTypes.vector_end();
4493 Vec1 != Vec1End; ++Vec1)
4494 for (BuiltinCandidateTypeSet::iterator
4495 Vec2 = CandidateTypes.vector_begin(),
4496 Vec2End = CandidateTypes.vector_end();
4497 Vec2 != Vec2End; ++Vec2) {
4498 QualType LandR[2] = { *Vec1, *Vec2 };
4499 QualType Result;
4500 if (isComparison)
4501 Result = Context.BoolTy;
4502 else {
4503 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4504 Result = *Vec1;
4505 else
4506 Result = *Vec2;
4507 }
4508
4509 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4510 }
4511
Douglas Gregora11693b2008-11-12 17:17:38 +00004512 break;
4513
4514 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004515 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004516 case OO_Caret:
4517 case OO_Pipe:
4518 case OO_LessLess:
4519 case OO_GreaterGreater:
4520 // C++ [over.built]p17:
4521 //
4522 // For every pair of promoted integral types L and R, there
4523 // exist candidate operator functions of the form
4524 //
4525 // LR operator%(L, R);
4526 // LR operator&(L, R);
4527 // LR operator^(L, R);
4528 // LR operator|(L, R);
4529 // L operator<<(L, R);
4530 // L operator>>(L, R);
4531 //
4532 // where LR is the result of the usual arithmetic conversions
4533 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004534 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004535 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004536 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004537 Right < LastPromotedIntegralType; ++Right) {
4538 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4539 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4540 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004541 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004542 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4543 }
4544 }
4545 break;
4546
4547 case OO_Equal:
4548 // C++ [over.built]p20:
4549 //
4550 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004551 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004552 // empty, there exist candidate operator functions of the form
4553 //
4554 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004555 for (BuiltinCandidateTypeSet::iterator
4556 Enum = CandidateTypes.enumeration_begin(),
4557 EnumEnd = CandidateTypes.enumeration_end();
4558 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004559 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004560 CandidateSet);
4561 for (BuiltinCandidateTypeSet::iterator
4562 MemPtr = CandidateTypes.member_pointer_begin(),
4563 MemPtrEnd = CandidateTypes.member_pointer_end();
4564 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004565 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004566 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004567
4568 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004569
4570 case OO_PlusEqual:
4571 case OO_MinusEqual:
4572 // C++ [over.built]p19:
4573 //
4574 // For every pair (T, VQ), where T is any type and VQ is either
4575 // volatile or empty, there exist candidate operator functions
4576 // of the form
4577 //
4578 // T*VQ& operator=(T*VQ&, T*);
4579 //
4580 // C++ [over.built]p21:
4581 //
4582 // For every pair (T, VQ), where T is a cv-qualified or
4583 // cv-unqualified object type and VQ is either volatile or
4584 // empty, there exist candidate operator functions of the form
4585 //
4586 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4587 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4588 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4589 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4590 QualType ParamTypes[2];
4591 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4592
4593 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004594 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004595 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4596 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004597
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004598 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4599 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004600 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004601 ParamTypes[0]
4602 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004603 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4604 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004605 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004606 }
4607 // Fall through.
4608
4609 case OO_StarEqual:
4610 case OO_SlashEqual:
4611 // C++ [over.built]p18:
4612 //
4613 // For every triple (L, VQ, R), where L is an arithmetic type,
4614 // VQ is either volatile or empty, and R is a promoted
4615 // arithmetic type, there exist candidate operator functions of
4616 // the form
4617 //
4618 // VQ L& operator=(VQ L&, R);
4619 // VQ L& operator*=(VQ L&, R);
4620 // VQ L& operator/=(VQ L&, R);
4621 // VQ L& operator+=(VQ L&, R);
4622 // VQ L& operator-=(VQ L&, R);
4623 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004624 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004625 Right < LastPromotedArithmeticType; ++Right) {
4626 QualType ParamTypes[2];
4627 ParamTypes[1] = ArithmeticTypes[Right];
4628
4629 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004630 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004631 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4632 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004633
4634 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004635 if (VisibleTypeConversionsQuals.hasVolatile()) {
4636 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4637 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4638 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4639 /*IsAssigmentOperator=*/Op == OO_Equal);
4640 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004641 }
4642 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004643
4644 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4645 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4646 Vec1End = CandidateTypes.vector_end();
4647 Vec1 != Vec1End; ++Vec1)
4648 for (BuiltinCandidateTypeSet::iterator
4649 Vec2 = CandidateTypes.vector_begin(),
4650 Vec2End = CandidateTypes.vector_end();
4651 Vec2 != Vec2End; ++Vec2) {
4652 QualType ParamTypes[2];
4653 ParamTypes[1] = *Vec2;
4654 // Add this built-in operator as a candidate (VQ is empty).
4655 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4656 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4657 /*IsAssigmentOperator=*/Op == OO_Equal);
4658
4659 // Add this built-in operator as a candidate (VQ is 'volatile').
4660 if (VisibleTypeConversionsQuals.hasVolatile()) {
4661 ParamTypes[0] = Context.getVolatileType(*Vec1);
4662 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4663 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4664 /*IsAssigmentOperator=*/Op == OO_Equal);
4665 }
4666 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004667 break;
4668
4669 case OO_PercentEqual:
4670 case OO_LessLessEqual:
4671 case OO_GreaterGreaterEqual:
4672 case OO_AmpEqual:
4673 case OO_CaretEqual:
4674 case OO_PipeEqual:
4675 // C++ [over.built]p22:
4676 //
4677 // For every triple (L, VQ, R), where L is an integral type, VQ
4678 // is either volatile or empty, and R is a promoted integral
4679 // type, there exist candidate operator functions of the form
4680 //
4681 // VQ L& operator%=(VQ L&, R);
4682 // VQ L& operator<<=(VQ L&, R);
4683 // VQ L& operator>>=(VQ L&, R);
4684 // VQ L& operator&=(VQ L&, R);
4685 // VQ L& operator^=(VQ L&, R);
4686 // VQ L& operator|=(VQ L&, R);
4687 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004688 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004689 Right < LastPromotedIntegralType; ++Right) {
4690 QualType ParamTypes[2];
4691 ParamTypes[1] = ArithmeticTypes[Right];
4692
4693 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004694 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004695 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004696 if (VisibleTypeConversionsQuals.hasVolatile()) {
4697 // Add this built-in operator as a candidate (VQ is 'volatile').
4698 ParamTypes[0] = ArithmeticTypes[Left];
4699 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4700 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4701 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4702 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004703 }
4704 }
4705 break;
4706
Douglas Gregord08452f2008-11-19 15:42:04 +00004707 case OO_Exclaim: {
4708 // C++ [over.operator]p23:
4709 //
4710 // There also exist candidate operator functions of the form
4711 //
Mike Stump11289f42009-09-09 15:08:12 +00004712 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004713 // bool operator&&(bool, bool); [BELOW]
4714 // bool operator||(bool, bool); [BELOW]
4715 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004716 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4717 /*IsAssignmentOperator=*/false,
4718 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004719 break;
4720 }
4721
Douglas Gregora11693b2008-11-12 17:17:38 +00004722 case OO_AmpAmp:
4723 case OO_PipePipe: {
4724 // C++ [over.operator]p23:
4725 //
4726 // There also exist candidate operator functions of the form
4727 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004728 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004729 // bool operator&&(bool, bool);
4730 // bool operator||(bool, bool);
4731 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004732 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4733 /*IsAssignmentOperator=*/false,
4734 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004735 break;
4736 }
4737
4738 case OO_Subscript:
4739 // C++ [over.built]p13:
4740 //
4741 // For every cv-qualified or cv-unqualified object type T there
4742 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004743 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004744 // T* operator+(T*, ptrdiff_t); [ABOVE]
4745 // T& operator[](T*, ptrdiff_t);
4746 // T* operator-(T*, ptrdiff_t); [ABOVE]
4747 // T* operator+(ptrdiff_t, T*); [ABOVE]
4748 // T& operator[](ptrdiff_t, T*);
4749 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4750 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4751 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004752 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004753 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004754
4755 // T& operator[](T*, ptrdiff_t)
4756 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4757
4758 // T& operator[](ptrdiff_t, T*);
4759 ParamTypes[0] = ParamTypes[1];
4760 ParamTypes[1] = *Ptr;
4761 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004762 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004763 break;
4764
4765 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004766 // C++ [over.built]p11:
4767 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4768 // C1 is the same type as C2 or is a derived class of C2, T is an object
4769 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4770 // there exist candidate operator functions of the form
4771 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4772 // where CV12 is the union of CV1 and CV2.
4773 {
4774 for (BuiltinCandidateTypeSet::iterator Ptr =
4775 CandidateTypes.pointer_begin();
4776 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4777 QualType C1Ty = (*Ptr);
4778 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004779 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004780 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004781 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004782 if (!isa<RecordType>(C1))
4783 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004784 // heuristic to reduce number of builtin candidates in the set.
4785 // Add volatile/restrict version only if there are conversions to a
4786 // volatile/restrict type.
4787 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4788 continue;
4789 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4790 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004791 }
4792 for (BuiltinCandidateTypeSet::iterator
4793 MemPtr = CandidateTypes.member_pointer_begin(),
4794 MemPtrEnd = CandidateTypes.member_pointer_end();
4795 MemPtr != MemPtrEnd; ++MemPtr) {
4796 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4797 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004798 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004799 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4800 break;
4801 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4802 // build CV12 T&
4803 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004804 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4805 T.isVolatileQualified())
4806 continue;
4807 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4808 T.isRestrictQualified())
4809 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004810 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004811 QualType ResultTy = Context.getLValueReferenceType(T);
4812 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4813 }
4814 }
4815 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004816 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004817
4818 case OO_Conditional:
4819 // Note that we don't consider the first argument, since it has been
4820 // contextually converted to bool long ago. The candidates below are
4821 // therefore added as binary.
4822 //
4823 // C++ [over.built]p24:
4824 // For every type T, where T is a pointer or pointer-to-member type,
4825 // there exist candidate operator functions of the form
4826 //
4827 // T operator?(bool, T, T);
4828 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004829 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4830 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4831 QualType ParamTypes[2] = { *Ptr, *Ptr };
4832 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4833 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004834 for (BuiltinCandidateTypeSet::iterator Ptr =
4835 CandidateTypes.member_pointer_begin(),
4836 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4837 QualType ParamTypes[2] = { *Ptr, *Ptr };
4838 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4839 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004840 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004841 }
4842}
4843
Douglas Gregore254f902009-02-04 00:32:51 +00004844/// \brief Add function candidates found via argument-dependent lookup
4845/// to the set of overloading candidates.
4846///
4847/// This routine performs argument-dependent name lookup based on the
4848/// given function name (which may also be an operator name) and adds
4849/// all of the overload candidates found by ADL to the overload
4850/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004851void
Douglas Gregore254f902009-02-04 00:32:51 +00004852Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004853 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004854 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004855 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004856 OverloadCandidateSet& CandidateSet,
4857 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004858 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004859
John McCall91f61fc2010-01-26 06:04:06 +00004860 // FIXME: This approach for uniquing ADL results (and removing
4861 // redundant candidates from the set) relies on pointer-equality,
4862 // which means we need to key off the canonical decl. However,
4863 // always going back to the canonical decl might not get us the
4864 // right set of default arguments. What default arguments are
4865 // we supposed to consider on ADL candidates, anyway?
4866
Douglas Gregorcabea402009-09-22 15:41:20 +00004867 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004868 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004869
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004870 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004871 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4872 CandEnd = CandidateSet.end();
4873 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004874 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004875 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004876 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004877 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004878 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004879
4880 // For each of the ADL candidates we found, add it to the overload
4881 // set.
John McCall8fe68082010-01-26 07:16:45 +00004882 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004883 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004884 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004885 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004886 continue;
4887
John McCalla0296f72010-03-19 07:35:19 +00004888 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004889 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004890 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004891 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004892 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004893 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004894 }
Douglas Gregore254f902009-02-04 00:32:51 +00004895}
4896
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004897/// isBetterOverloadCandidate - Determines whether the first overload
4898/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004899bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004900Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004901 const OverloadCandidate& Cand2,
4902 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004903 // Define viable functions to be better candidates than non-viable
4904 // functions.
4905 if (!Cand2.Viable)
4906 return Cand1.Viable;
4907 else if (!Cand1.Viable)
4908 return false;
4909
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004910 // C++ [over.match.best]p1:
4911 //
4912 // -- if F is a static member function, ICS1(F) is defined such
4913 // that ICS1(F) is neither better nor worse than ICS1(G) for
4914 // any function G, and, symmetrically, ICS1(G) is neither
4915 // better nor worse than ICS1(F).
4916 unsigned StartArg = 0;
4917 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4918 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004919
Douglas Gregord3cb3562009-07-07 23:38:56 +00004920 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004921 // A viable function F1 is defined to be a better function than another
4922 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004923 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004924 unsigned NumArgs = Cand1.Conversions.size();
4925 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4926 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004927 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004928 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4929 Cand2.Conversions[ArgIdx])) {
4930 case ImplicitConversionSequence::Better:
4931 // Cand1 has a better conversion sequence.
4932 HasBetterConversion = true;
4933 break;
4934
4935 case ImplicitConversionSequence::Worse:
4936 // Cand1 can't be better than Cand2.
4937 return false;
4938
4939 case ImplicitConversionSequence::Indistinguishable:
4940 // Do nothing.
4941 break;
4942 }
4943 }
4944
Mike Stump11289f42009-09-09 15:08:12 +00004945 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004946 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004947 if (HasBetterConversion)
4948 return true;
4949
Mike Stump11289f42009-09-09 15:08:12 +00004950 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004951 // specialization, or, if not that,
4952 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4953 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4954 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004955
4956 // -- F1 and F2 are function template specializations, and the function
4957 // template for F1 is more specialized than the template for F2
4958 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004959 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004960 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4961 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004962 if (FunctionTemplateDecl *BetterTemplate
4963 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4964 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004965 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004966 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4967 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004968 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004969
Douglas Gregora1f013e2008-11-07 22:36:19 +00004970 // -- the context is an initialization by user-defined conversion
4971 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4972 // from the return type of F1 to the destination type (i.e.,
4973 // the type of the entity being initialized) is a better
4974 // conversion sequence than the standard conversion sequence
4975 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004976 if (Cand1.Function && Cand2.Function &&
4977 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004978 isa<CXXConversionDecl>(Cand2.Function)) {
4979 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4980 Cand2.FinalConversion)) {
4981 case ImplicitConversionSequence::Better:
4982 // Cand1 has a better conversion sequence.
4983 return true;
4984
4985 case ImplicitConversionSequence::Worse:
4986 // Cand1 can't be better than Cand2.
4987 return false;
4988
4989 case ImplicitConversionSequence::Indistinguishable:
4990 // Do nothing
4991 break;
4992 }
4993 }
4994
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004995 return false;
4996}
4997
Mike Stump11289f42009-09-09 15:08:12 +00004998/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004999/// within an overload candidate set.
5000///
5001/// \param CandidateSet the set of candidate functions.
5002///
5003/// \param Loc the location of the function name (or operator symbol) for
5004/// which overload resolution occurs.
5005///
Mike Stump11289f42009-09-09 15:08:12 +00005006/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005007/// function, Best points to the candidate function found.
5008///
5009/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005010OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5011 SourceLocation Loc,
5012 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005013 // Find the best viable function.
5014 Best = CandidateSet.end();
5015 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5016 Cand != CandidateSet.end(); ++Cand) {
5017 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005018 if (Best == CandidateSet.end() ||
5019 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005020 Best = Cand;
5021 }
5022 }
5023
5024 // If we didn't find any viable functions, abort.
5025 if (Best == CandidateSet.end())
5026 return OR_No_Viable_Function;
5027
5028 // Make sure that this function is better than every other viable
5029 // function. If not, we have an ambiguity.
5030 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5031 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005032 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005033 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005034 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005035 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005036 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005037 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005038 }
Mike Stump11289f42009-09-09 15:08:12 +00005039
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005040 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005041 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005042 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005043 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005044 return OR_Deleted;
5045
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005046 // C++ [basic.def.odr]p2:
5047 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005048 // when referred to from a potentially-evaluated expression. [Note: this
5049 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005050 // (clause 13), user-defined conversions (12.3.2), allocation function for
5051 // placement new (5.3.4), as well as non-default initialization (8.5).
5052 if (Best->Function)
5053 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005054 return OR_Success;
5055}
5056
John McCall53262c92010-01-12 02:15:36 +00005057namespace {
5058
5059enum OverloadCandidateKind {
5060 oc_function,
5061 oc_method,
5062 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005063 oc_function_template,
5064 oc_method_template,
5065 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005066 oc_implicit_default_constructor,
5067 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005068 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005069};
5070
John McCalle1ac8d12010-01-13 00:25:19 +00005071OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5072 FunctionDecl *Fn,
5073 std::string &Description) {
5074 bool isTemplate = false;
5075
5076 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5077 isTemplate = true;
5078 Description = S.getTemplateArgumentBindingsText(
5079 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5080 }
John McCallfd0b2f82010-01-06 09:43:14 +00005081
5082 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005083 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005084 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005085
John McCall53262c92010-01-12 02:15:36 +00005086 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5087 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005088 }
5089
5090 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5091 // This actually gets spelled 'candidate function' for now, but
5092 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005093 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005094 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005095
5096 assert(Meth->isCopyAssignment()
5097 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005098 return oc_implicit_copy_assignment;
5099 }
5100
John McCalle1ac8d12010-01-13 00:25:19 +00005101 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005102}
5103
5104} // end anonymous namespace
5105
5106// Notes the location of an overload candidate.
5107void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005108 std::string FnDesc;
5109 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5110 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5111 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005112}
5113
John McCall0d1da222010-01-12 00:44:57 +00005114/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5115/// "lead" diagnostic; it will be given two arguments, the source and
5116/// target types of the conversion.
5117void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5118 SourceLocation CaretLoc,
5119 const PartialDiagnostic &PDiag) {
5120 Diag(CaretLoc, PDiag)
5121 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5122 for (AmbiguousConversionSequence::const_iterator
5123 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5124 NoteOverloadCandidate(*I);
5125 }
John McCall12f97bc2010-01-08 04:41:39 +00005126}
5127
John McCall0d1da222010-01-12 00:44:57 +00005128namespace {
5129
John McCall6a61b522010-01-13 09:16:55 +00005130void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5131 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5132 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005133 assert(Cand->Function && "for now, candidate must be a function");
5134 FunctionDecl *Fn = Cand->Function;
5135
5136 // There's a conversion slot for the object argument if this is a
5137 // non-constructor method. Note that 'I' corresponds the
5138 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005139 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005140 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005141 if (I == 0)
5142 isObjectArgument = true;
5143 else
5144 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005145 }
5146
John McCalle1ac8d12010-01-13 00:25:19 +00005147 std::string FnDesc;
5148 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5149
John McCall6a61b522010-01-13 09:16:55 +00005150 Expr *FromExpr = Conv.Bad.FromExpr;
5151 QualType FromTy = Conv.Bad.getFromType();
5152 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005153
John McCallfb7ad0f2010-02-02 02:42:52 +00005154 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005155 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005156 Expr *E = FromExpr->IgnoreParens();
5157 if (isa<UnaryOperator>(E))
5158 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005159 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005160
5161 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5162 << (unsigned) FnKind << FnDesc
5163 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5164 << ToTy << Name << I+1;
5165 return;
5166 }
5167
John McCall6d174642010-01-23 08:10:49 +00005168 // Do some hand-waving analysis to see if the non-viability is due
5169 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005170 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5171 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5172 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5173 CToTy = RT->getPointeeType();
5174 else {
5175 // TODO: detect and diagnose the full richness of const mismatches.
5176 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5177 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5178 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5179 }
5180
5181 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5182 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5183 // It is dumb that we have to do this here.
5184 while (isa<ArrayType>(CFromTy))
5185 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5186 while (isa<ArrayType>(CToTy))
5187 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5188
5189 Qualifiers FromQs = CFromTy.getQualifiers();
5190 Qualifiers ToQs = CToTy.getQualifiers();
5191
5192 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5194 << (unsigned) FnKind << FnDesc
5195 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5196 << FromTy
5197 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5198 << (unsigned) isObjectArgument << I+1;
5199 return;
5200 }
5201
5202 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5203 assert(CVR && "unexpected qualifiers mismatch");
5204
5205 if (isObjectArgument) {
5206 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5207 << (unsigned) FnKind << FnDesc
5208 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5209 << FromTy << (CVR - 1);
5210 } else {
5211 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5212 << (unsigned) FnKind << FnDesc
5213 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5214 << FromTy << (CVR - 1) << I+1;
5215 }
5216 return;
5217 }
5218
John McCall6d174642010-01-23 08:10:49 +00005219 // Diagnose references or pointers to incomplete types differently,
5220 // since it's far from impossible that the incompleteness triggered
5221 // the failure.
5222 QualType TempFromTy = FromTy.getNonReferenceType();
5223 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5224 TempFromTy = PTy->getPointeeType();
5225 if (TempFromTy->isIncompleteType()) {
5226 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5227 << (unsigned) FnKind << FnDesc
5228 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5229 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5230 return;
5231 }
5232
John McCall47000992010-01-14 03:28:57 +00005233 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005234 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5235 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005236 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005237 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005238}
5239
5240void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5241 unsigned NumFormalArgs) {
5242 // TODO: treat calls to a missing default constructor as a special case
5243
5244 FunctionDecl *Fn = Cand->Function;
5245 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5246
5247 unsigned MinParams = Fn->getMinRequiredArguments();
5248
5249 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005250 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005251 unsigned mode, modeCount;
5252 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005253 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5254 (Cand->FailureKind == ovl_fail_bad_deduction &&
5255 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005256 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5257 mode = 0; // "at least"
5258 else
5259 mode = 2; // "exactly"
5260 modeCount = MinParams;
5261 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005262 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5263 (Cand->FailureKind == ovl_fail_bad_deduction &&
5264 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005265 if (MinParams != FnTy->getNumArgs())
5266 mode = 1; // "at most"
5267 else
5268 mode = 2; // "exactly"
5269 modeCount = FnTy->getNumArgs();
5270 }
5271
5272 std::string Description;
5273 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5274
5275 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005276 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5277 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005278}
5279
John McCall8b9ed552010-02-01 18:53:26 +00005280/// Diagnose a failed template-argument deduction.
5281void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5282 Expr **Args, unsigned NumArgs) {
5283 FunctionDecl *Fn = Cand->Function; // pattern
5284
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005285 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005286 NamedDecl *ParamD;
5287 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5288 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5289 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005290 switch (Cand->DeductionFailure.Result) {
5291 case Sema::TDK_Success:
5292 llvm_unreachable("TDK_success while diagnosing bad deduction");
5293
5294 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005295 assert(ParamD && "no parameter found for incomplete deduction result");
5296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5297 << ParamD->getDeclName();
5298 return;
5299 }
5300
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005301 case Sema::TDK_Inconsistent:
5302 case Sema::TDK_InconsistentQuals: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005303 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005304 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005305 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005306 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005307 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005308 which = 1;
5309 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005310 which = 2;
5311 }
5312
5313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5314 << which << ParamD->getDeclName()
5315 << *Cand->DeductionFailure.getFirstArg()
5316 << *Cand->DeductionFailure.getSecondArg();
5317 return;
5318 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005319
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005320 case Sema::TDK_InvalidExplicitArguments:
5321 assert(ParamD && "no parameter found for invalid explicit arguments");
5322 if (ParamD->getDeclName())
5323 S.Diag(Fn->getLocation(),
5324 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5325 << ParamD->getDeclName();
5326 else {
5327 int index = 0;
5328 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5329 index = TTP->getIndex();
5330 else if (NonTypeTemplateParmDecl *NTTP
5331 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5332 index = NTTP->getIndex();
5333 else
5334 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5335 S.Diag(Fn->getLocation(),
5336 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5337 << (index + 1);
5338 }
5339 return;
5340
Douglas Gregor02eb4832010-05-08 18:13:28 +00005341 case Sema::TDK_TooManyArguments:
5342 case Sema::TDK_TooFewArguments:
5343 DiagnoseArityMismatch(S, Cand, NumArgs);
5344 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005345
5346 case Sema::TDK_InstantiationDepth:
5347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5348 return;
5349
5350 case Sema::TDK_SubstitutionFailure: {
5351 std::string ArgString;
5352 if (TemplateArgumentList *Args
5353 = Cand->DeductionFailure.getTemplateArgumentList())
5354 ArgString = S.getTemplateArgumentBindingsText(
5355 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5356 *Args);
5357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5358 << ArgString;
5359 return;
5360 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005361
John McCall8b9ed552010-02-01 18:53:26 +00005362 // TODO: diagnose these individually, then kill off
5363 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005364 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005365 case Sema::TDK_FailedOverloadResolution:
5366 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5367 return;
5368 }
5369}
5370
5371/// Generates a 'note' diagnostic for an overload candidate. We've
5372/// already generated a primary error at the call site.
5373///
5374/// It really does need to be a single diagnostic with its caret
5375/// pointed at the candidate declaration. Yes, this creates some
5376/// major challenges of technical writing. Yes, this makes pointing
5377/// out problems with specific arguments quite awkward. It's still
5378/// better than generating twenty screens of text for every failed
5379/// overload.
5380///
5381/// It would be great to be able to express per-candidate problems
5382/// more richly for those diagnostic clients that cared, but we'd
5383/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005384void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5385 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005386 FunctionDecl *Fn = Cand->Function;
5387
John McCall12f97bc2010-01-08 04:41:39 +00005388 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005389 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005390 std::string FnDesc;
5391 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005392
5393 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005394 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005395 return;
John McCall12f97bc2010-01-08 04:41:39 +00005396 }
5397
John McCalle1ac8d12010-01-13 00:25:19 +00005398 // We don't really have anything else to say about viable candidates.
5399 if (Cand->Viable) {
5400 S.NoteOverloadCandidate(Fn);
5401 return;
5402 }
John McCall0d1da222010-01-12 00:44:57 +00005403
John McCall6a61b522010-01-13 09:16:55 +00005404 switch (Cand->FailureKind) {
5405 case ovl_fail_too_many_arguments:
5406 case ovl_fail_too_few_arguments:
5407 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005408
John McCall6a61b522010-01-13 09:16:55 +00005409 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005410 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5411
John McCallfe796dd2010-01-23 05:17:32 +00005412 case ovl_fail_trivial_conversion:
5413 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005414 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005415 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005416
John McCall65eb8792010-02-25 01:37:24 +00005417 case ovl_fail_bad_conversion: {
5418 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5419 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005420 if (Cand->Conversions[I].isBad())
5421 return DiagnoseBadConversion(S, Cand, I);
5422
5423 // FIXME: this currently happens when we're called from SemaInit
5424 // when user-conversion overload fails. Figure out how to handle
5425 // those conditions and diagnose them well.
5426 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005427 }
John McCall65eb8792010-02-25 01:37:24 +00005428 }
John McCalld3224162010-01-08 00:58:21 +00005429}
5430
5431void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5432 // Desugar the type of the surrogate down to a function type,
5433 // retaining as many typedefs as possible while still showing
5434 // the function type (and, therefore, its parameter types).
5435 QualType FnType = Cand->Surrogate->getConversionType();
5436 bool isLValueReference = false;
5437 bool isRValueReference = false;
5438 bool isPointer = false;
5439 if (const LValueReferenceType *FnTypeRef =
5440 FnType->getAs<LValueReferenceType>()) {
5441 FnType = FnTypeRef->getPointeeType();
5442 isLValueReference = true;
5443 } else if (const RValueReferenceType *FnTypeRef =
5444 FnType->getAs<RValueReferenceType>()) {
5445 FnType = FnTypeRef->getPointeeType();
5446 isRValueReference = true;
5447 }
5448 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5449 FnType = FnTypePtr->getPointeeType();
5450 isPointer = true;
5451 }
5452 // Desugar down to a function type.
5453 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5454 // Reconstruct the pointer/reference as appropriate.
5455 if (isPointer) FnType = S.Context.getPointerType(FnType);
5456 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5457 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5458
5459 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5460 << FnType;
5461}
5462
5463void NoteBuiltinOperatorCandidate(Sema &S,
5464 const char *Opc,
5465 SourceLocation OpLoc,
5466 OverloadCandidate *Cand) {
5467 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5468 std::string TypeStr("operator");
5469 TypeStr += Opc;
5470 TypeStr += "(";
5471 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5472 if (Cand->Conversions.size() == 1) {
5473 TypeStr += ")";
5474 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5475 } else {
5476 TypeStr += ", ";
5477 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5478 TypeStr += ")";
5479 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5480 }
5481}
5482
5483void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5484 OverloadCandidate *Cand) {
5485 unsigned NoOperands = Cand->Conversions.size();
5486 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5487 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005488 if (ICS.isBad()) break; // all meaningless after first invalid
5489 if (!ICS.isAmbiguous()) continue;
5490
5491 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005492 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005493 }
5494}
5495
John McCall3712d9e2010-01-15 23:32:50 +00005496SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5497 if (Cand->Function)
5498 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005499 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005500 return Cand->Surrogate->getLocation();
5501 return SourceLocation();
5502}
5503
John McCallad2587a2010-01-12 00:48:53 +00005504struct CompareOverloadCandidatesForDisplay {
5505 Sema &S;
5506 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005507
5508 bool operator()(const OverloadCandidate *L,
5509 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005510 // Fast-path this check.
5511 if (L == R) return false;
5512
John McCall12f97bc2010-01-08 04:41:39 +00005513 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005514 if (L->Viable) {
5515 if (!R->Viable) return true;
5516
5517 // TODO: introduce a tri-valued comparison for overload
5518 // candidates. Would be more worthwhile if we had a sort
5519 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005520 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5521 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005522 } else if (R->Viable)
5523 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005524
John McCall3712d9e2010-01-15 23:32:50 +00005525 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005526
John McCall3712d9e2010-01-15 23:32:50 +00005527 // Criteria by which we can sort non-viable candidates:
5528 if (!L->Viable) {
5529 // 1. Arity mismatches come after other candidates.
5530 if (L->FailureKind == ovl_fail_too_many_arguments ||
5531 L->FailureKind == ovl_fail_too_few_arguments)
5532 return false;
5533 if (R->FailureKind == ovl_fail_too_many_arguments ||
5534 R->FailureKind == ovl_fail_too_few_arguments)
5535 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005536
John McCallfe796dd2010-01-23 05:17:32 +00005537 // 2. Bad conversions come first and are ordered by the number
5538 // of bad conversions and quality of good conversions.
5539 if (L->FailureKind == ovl_fail_bad_conversion) {
5540 if (R->FailureKind != ovl_fail_bad_conversion)
5541 return true;
5542
5543 // If there's any ordering between the defined conversions...
5544 // FIXME: this might not be transitive.
5545 assert(L->Conversions.size() == R->Conversions.size());
5546
5547 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005548 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5549 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005550 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5551 R->Conversions[I])) {
5552 case ImplicitConversionSequence::Better:
5553 leftBetter++;
5554 break;
5555
5556 case ImplicitConversionSequence::Worse:
5557 leftBetter--;
5558 break;
5559
5560 case ImplicitConversionSequence::Indistinguishable:
5561 break;
5562 }
5563 }
5564 if (leftBetter > 0) return true;
5565 if (leftBetter < 0) return false;
5566
5567 } else if (R->FailureKind == ovl_fail_bad_conversion)
5568 return false;
5569
John McCall3712d9e2010-01-15 23:32:50 +00005570 // TODO: others?
5571 }
5572
5573 // Sort everything else by location.
5574 SourceLocation LLoc = GetLocationForCandidate(L);
5575 SourceLocation RLoc = GetLocationForCandidate(R);
5576
5577 // Put candidates without locations (e.g. builtins) at the end.
5578 if (LLoc.isInvalid()) return false;
5579 if (RLoc.isInvalid()) return true;
5580
5581 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005582 }
5583};
5584
John McCallfe796dd2010-01-23 05:17:32 +00005585/// CompleteNonViableCandidate - Normally, overload resolution only
5586/// computes up to the first
5587void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5588 Expr **Args, unsigned NumArgs) {
5589 assert(!Cand->Viable);
5590
5591 // Don't do anything on failures other than bad conversion.
5592 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5593
5594 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005595 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005596 unsigned ConvCount = Cand->Conversions.size();
5597 while (true) {
5598 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5599 ConvIdx++;
5600 if (Cand->Conversions[ConvIdx - 1].isBad())
5601 break;
5602 }
5603
5604 if (ConvIdx == ConvCount)
5605 return;
5606
John McCall65eb8792010-02-25 01:37:24 +00005607 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5608 "remaining conversion is initialized?");
5609
Douglas Gregoradc7a702010-04-16 17:45:54 +00005610 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005611 // operation somehow.
5612 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005613
5614 const FunctionProtoType* Proto;
5615 unsigned ArgIdx = ConvIdx;
5616
5617 if (Cand->IsSurrogate) {
5618 QualType ConvType
5619 = Cand->Surrogate->getConversionType().getNonReferenceType();
5620 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5621 ConvType = ConvPtrType->getPointeeType();
5622 Proto = ConvType->getAs<FunctionProtoType>();
5623 ArgIdx--;
5624 } else if (Cand->Function) {
5625 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5626 if (isa<CXXMethodDecl>(Cand->Function) &&
5627 !isa<CXXConstructorDecl>(Cand->Function))
5628 ArgIdx--;
5629 } else {
5630 // Builtin binary operator with a bad first conversion.
5631 assert(ConvCount <= 3);
5632 for (; ConvIdx != ConvCount; ++ConvIdx)
5633 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005634 = TryCopyInitialization(S, Args[ConvIdx],
5635 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5636 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005637 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005638 return;
5639 }
5640
5641 // Fill in the rest of the conversions.
5642 unsigned NumArgsInProto = Proto->getNumArgs();
5643 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5644 if (ArgIdx < NumArgsInProto)
5645 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005646 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5647 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005648 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005649 else
5650 Cand->Conversions[ConvIdx].setEllipsis();
5651 }
5652}
5653
John McCalld3224162010-01-08 00:58:21 +00005654} // end anonymous namespace
5655
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005656/// PrintOverloadCandidates - When overload resolution fails, prints
5657/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005658/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005659void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005660Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005661 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005662 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005663 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005664 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005665 // Sort the candidates by viability and position. Sorting directly would
5666 // be prohibitive, so we make a set of pointers and sort those.
5667 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5668 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5669 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5670 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005671 Cand != LastCand; ++Cand) {
5672 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005673 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005674 else if (OCD == OCD_AllCandidates) {
5675 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5676 Cands.push_back(Cand);
5677 }
5678 }
5679
John McCallad2587a2010-01-12 00:48:53 +00005680 std::sort(Cands.begin(), Cands.end(),
5681 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005682
John McCall0d1da222010-01-12 00:44:57 +00005683 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005684
John McCall12f97bc2010-01-08 04:41:39 +00005685 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5686 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5687 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005688
John McCalld3224162010-01-08 00:58:21 +00005689 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005690 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005691 else if (Cand->IsSurrogate)
5692 NoteSurrogateCandidate(*this, Cand);
5693
5694 // This a builtin candidate. We do not, in general, want to list
5695 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005696 else if (Cand->Viable) {
5697 // Generally we only see ambiguities including viable builtin
5698 // operators if overload resolution got screwed up by an
5699 // ambiguous user-defined conversion.
5700 //
5701 // FIXME: It's quite possible for different conversions to see
5702 // different ambiguities, though.
5703 if (!ReportedAmbiguousConversions) {
5704 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5705 ReportedAmbiguousConversions = true;
5706 }
John McCalld3224162010-01-08 00:58:21 +00005707
John McCall0d1da222010-01-12 00:44:57 +00005708 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005709 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005710 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005711 }
5712}
5713
John McCalla0296f72010-03-19 07:35:19 +00005714static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005715 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005716 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005717
John McCalla0296f72010-03-19 07:35:19 +00005718 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005719}
5720
Douglas Gregorcd695e52008-11-10 20:40:00 +00005721/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5722/// an overloaded function (C++ [over.over]), where @p From is an
5723/// expression with overloaded function type and @p ToType is the type
5724/// we're trying to resolve to. For example:
5725///
5726/// @code
5727/// int f(double);
5728/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005729///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005730/// int (*pfd)(double) = f; // selects f(double)
5731/// @endcode
5732///
5733/// This routine returns the resulting FunctionDecl if it could be
5734/// resolved, and NULL otherwise. When @p Complain is true, this
5735/// routine will emit diagnostics if there is an error.
5736FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005737Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005738 bool Complain,
5739 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005740 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005741 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005742 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005743 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005744 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005745 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005746 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005747 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005748 FunctionType = MemTypePtr->getPointeeType();
5749 IsMember = true;
5750 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005751
Douglas Gregorcd695e52008-11-10 20:40:00 +00005752 // C++ [over.over]p1:
5753 // [...] [Note: any redundant set of parentheses surrounding the
5754 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005755 // C++ [over.over]p1:
5756 // [...] The overloaded function name can be preceded by the &
5757 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005758 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5759 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5760 if (OvlExpr->hasExplicitTemplateArgs()) {
5761 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5762 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005763 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005764
5765 // We expect a pointer or reference to function, or a function pointer.
5766 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5767 if (!FunctionType->isFunctionType()) {
5768 if (Complain)
5769 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5770 << OvlExpr->getName() << ToType;
5771
5772 return 0;
5773 }
5774
5775 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005776
Douglas Gregorcd695e52008-11-10 20:40:00 +00005777 // Look through all of the overloaded functions, searching for one
5778 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005779 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005780 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5781
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005782 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005783 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5784 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005785 // Look through any using declarations to find the underlying function.
5786 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5787
Douglas Gregorcd695e52008-11-10 20:40:00 +00005788 // C++ [over.over]p3:
5789 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005790 // targets of type "pointer-to-function" or "reference-to-function."
5791 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005792 // type "pointer-to-member-function."
5793 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005794
Mike Stump11289f42009-09-09 15:08:12 +00005795 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005796 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005797 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005798 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005799 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005800 // static when converting to member pointer.
5801 if (Method->isStatic() == IsMember)
5802 continue;
5803 } else if (IsMember)
5804 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005805
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005806 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005807 // If the name is a function template, template argument deduction is
5808 // done (14.8.2.2), and if the argument deduction succeeds, the
5809 // resulting template argument list is used to generate a single
5810 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005811 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005812 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005813 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005814 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005815 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005816 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005817 FunctionType, Specialization, Info)) {
5818 // FIXME: make a note of the failed deduction for diagnostics.
5819 (void)Result;
5820 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005821 // FIXME: If the match isn't exact, shouldn't we just drop this as
5822 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005823 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005824 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005825 Matches.push_back(std::make_pair(I.getPair(),
5826 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005827 }
John McCalld14a8642009-11-21 08:51:07 +00005828
5829 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005830 }
Mike Stump11289f42009-09-09 15:08:12 +00005831
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005832 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005833 // Skip non-static functions when converting to pointer, and static
5834 // when converting to member pointer.
5835 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005836 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005837
5838 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005839 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005840 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005841 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005842 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005843
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005844 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005845 QualType ResultTy;
5846 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5847 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5848 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005849 Matches.push_back(std::make_pair(I.getPair(),
5850 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005851 FoundNonTemplateFunction = true;
5852 }
Mike Stump11289f42009-09-09 15:08:12 +00005853 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005854 }
5855
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005856 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005857 if (Matches.empty()) {
5858 if (Complain) {
5859 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5860 << OvlExpr->getName() << FunctionType;
5861 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5862 E = OvlExpr->decls_end();
5863 I != E; ++I)
5864 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5865 NoteOverloadCandidate(F);
5866 }
5867
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005868 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005869 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005870 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005871 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005872 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005873 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005874 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005875 return Result;
5876 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005877
5878 // C++ [over.over]p4:
5879 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005880 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005881 // [...] and any given function template specialization F1 is
5882 // eliminated if the set contains a second function template
5883 // specialization whose function template is more specialized
5884 // than the function template of F1 according to the partial
5885 // ordering rules of 14.5.5.2.
5886
5887 // The algorithm specified above is quadratic. We instead use a
5888 // two-pass algorithm (similar to the one used to identify the
5889 // best viable function in an overload set) that identifies the
5890 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005891
5892 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5893 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5894 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005895
5896 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005897 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005898 TPOC_Other, From->getLocStart(),
5899 PDiag(),
5900 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005901 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005902 PDiag(diag::note_ovl_candidate)
5903 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005904 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005905 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005906 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005907 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005908 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005909 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5910 }
John McCall58cc69d2010-01-27 01:50:18 +00005911 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005912 }
Mike Stump11289f42009-09-09 15:08:12 +00005913
Douglas Gregorfae1d712009-09-26 03:56:17 +00005914 // [...] any function template specializations in the set are
5915 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005916 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005917 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005918 ++I;
5919 else {
John McCalla0296f72010-03-19 07:35:19 +00005920 Matches[I] = Matches[--N];
5921 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005922 }
5923 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005924
Mike Stump11289f42009-09-09 15:08:12 +00005925 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005926 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005927 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005928 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005929 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005930 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00005931 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00005932 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5933 }
John McCalla0296f72010-03-19 07:35:19 +00005934 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005935 }
Mike Stump11289f42009-09-09 15:08:12 +00005936
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005937 // FIXME: We should probably return the same thing that BestViableFunction
5938 // returns (even if we issue the diagnostics here).
5939 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005940 << Matches[0].second->getDeclName();
5941 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5942 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005943 return 0;
5944}
5945
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005946/// \brief Given an expression that refers to an overloaded function, try to
5947/// resolve that overloaded function expression down to a single function.
5948///
5949/// This routine can only resolve template-ids that refer to a single function
5950/// template, where that template-id refers to a single template whose template
5951/// arguments are either provided by the template-id or have defaults,
5952/// as described in C++0x [temp.arg.explicit]p3.
5953FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5954 // C++ [over.over]p1:
5955 // [...] [Note: any redundant set of parentheses surrounding the
5956 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005957 // C++ [over.over]p1:
5958 // [...] The overloaded function name can be preceded by the &
5959 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005960
5961 if (From->getType() != Context.OverloadTy)
5962 return 0;
5963
5964 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005965
5966 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005967 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005968 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005969
5970 TemplateArgumentListInfo ExplicitTemplateArgs;
5971 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005972
5973 // Look through all of the overloaded functions, searching for one
5974 // whose type matches exactly.
5975 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005976 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5977 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005978 // C++0x [temp.arg.explicit]p3:
5979 // [...] In contexts where deduction is done and fails, or in contexts
5980 // where deduction is not done, if a template argument list is
5981 // specified and it, along with any default template arguments,
5982 // identifies a single function template specialization, then the
5983 // template-id is an lvalue for the function template specialization.
5984 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5985
5986 // C++ [over.over]p2:
5987 // If the name is a function template, template argument deduction is
5988 // done (14.8.2.2), and if the argument deduction succeeds, the
5989 // resulting template argument list is used to generate a single
5990 // function template specialization, which is added to the set of
5991 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005992 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005993 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005994 if (TemplateDeductionResult Result
5995 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5996 Specialization, Info)) {
5997 // FIXME: make a note of the failed deduction for diagnostics.
5998 (void)Result;
5999 continue;
6000 }
6001
6002 // Multiple matches; we can't resolve to a single declaration.
6003 if (Matched)
6004 return 0;
6005
6006 Matched = Specialization;
6007 }
6008
6009 return Matched;
6010}
6011
Douglas Gregorcabea402009-09-22 15:41:20 +00006012/// \brief Add a single candidate to the overload set.
6013static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006014 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006015 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006016 Expr **Args, unsigned NumArgs,
6017 OverloadCandidateSet &CandidateSet,
6018 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006019 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006020 if (isa<UsingShadowDecl>(Callee))
6021 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6022
Douglas Gregorcabea402009-09-22 15:41:20 +00006023 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006024 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006025 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006026 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006027 return;
John McCalld14a8642009-11-21 08:51:07 +00006028 }
6029
6030 if (FunctionTemplateDecl *FuncTemplate
6031 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006032 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6033 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006034 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006035 return;
6036 }
6037
6038 assert(false && "unhandled case in overloaded call candidate");
6039
6040 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006041}
6042
6043/// \brief Add the overload candidates named by callee and/or found by argument
6044/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006045void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006046 Expr **Args, unsigned NumArgs,
6047 OverloadCandidateSet &CandidateSet,
6048 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006049
6050#ifndef NDEBUG
6051 // Verify that ArgumentDependentLookup is consistent with the rules
6052 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006053 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006054 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6055 // and let Y be the lookup set produced by argument dependent
6056 // lookup (defined as follows). If X contains
6057 //
6058 // -- a declaration of a class member, or
6059 //
6060 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006061 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006062 //
6063 // -- a declaration that is neither a function or a function
6064 // template
6065 //
6066 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006067
John McCall57500772009-12-16 12:17:52 +00006068 if (ULE->requiresADL()) {
6069 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6070 E = ULE->decls_end(); I != E; ++I) {
6071 assert(!(*I)->getDeclContext()->isRecord());
6072 assert(isa<UsingShadowDecl>(*I) ||
6073 !(*I)->getDeclContext()->isFunctionOrMethod());
6074 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006075 }
6076 }
6077#endif
6078
John McCall57500772009-12-16 12:17:52 +00006079 // It would be nice to avoid this copy.
6080 TemplateArgumentListInfo TABuffer;
6081 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6082 if (ULE->hasExplicitTemplateArgs()) {
6083 ULE->copyTemplateArgumentsInto(TABuffer);
6084 ExplicitTemplateArgs = &TABuffer;
6085 }
6086
6087 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6088 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006089 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006090 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006091 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006092
John McCall57500772009-12-16 12:17:52 +00006093 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006094 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6095 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006096 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006097 CandidateSet,
6098 PartialOverloading);
6099}
John McCalld681c392009-12-16 08:11:27 +00006100
John McCall57500772009-12-16 12:17:52 +00006101static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6102 Expr **Args, unsigned NumArgs) {
6103 Fn->Destroy(SemaRef.Context);
6104 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6105 Args[Arg]->Destroy(SemaRef.Context);
6106 return SemaRef.ExprError();
6107}
6108
John McCalld681c392009-12-16 08:11:27 +00006109/// Attempts to recover from a call where no functions were found.
6110///
6111/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006112static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006113BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006114 UnresolvedLookupExpr *ULE,
6115 SourceLocation LParenLoc,
6116 Expr **Args, unsigned NumArgs,
6117 SourceLocation *CommaLocs,
6118 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006119
6120 CXXScopeSpec SS;
6121 if (ULE->getQualifier()) {
6122 SS.setScopeRep(ULE->getQualifier());
6123 SS.setRange(ULE->getQualifierRange());
6124 }
6125
John McCall57500772009-12-16 12:17:52 +00006126 TemplateArgumentListInfo TABuffer;
6127 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6128 if (ULE->hasExplicitTemplateArgs()) {
6129 ULE->copyTemplateArgumentsInto(TABuffer);
6130 ExplicitTemplateArgs = &TABuffer;
6131 }
6132
John McCalld681c392009-12-16 08:11:27 +00006133 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6134 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006135 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall57500772009-12-16 12:17:52 +00006136 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00006137
John McCall57500772009-12-16 12:17:52 +00006138 assert(!R.empty() && "lookup results empty despite recovery");
6139
6140 // Build an implicit member call if appropriate. Just drop the
6141 // casts and such from the call, we don't really care.
6142 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6143 if ((*R.begin())->isCXXClassMember())
6144 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6145 else if (ExplicitTemplateArgs)
6146 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6147 else
6148 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6149
6150 if (NewFn.isInvalid())
6151 return Destroy(SemaRef, Fn, Args, NumArgs);
6152
6153 Fn->Destroy(SemaRef.Context);
6154
6155 // This shouldn't cause an infinite loop because we're giving it
6156 // an expression with non-empty lookup results, which should never
6157 // end up here.
6158 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6159 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6160 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006161}
Douglas Gregorcabea402009-09-22 15:41:20 +00006162
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006163/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006164/// (which eventually refers to the declaration Func) and the call
6165/// arguments Args/NumArgs, attempt to resolve the function call down
6166/// to a specific function. If overload resolution succeeds, returns
6167/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006168/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006169/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006170Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006171Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006172 SourceLocation LParenLoc,
6173 Expr **Args, unsigned NumArgs,
6174 SourceLocation *CommaLocs,
6175 SourceLocation RParenLoc) {
6176#ifndef NDEBUG
6177 if (ULE->requiresADL()) {
6178 // To do ADL, we must have found an unqualified name.
6179 assert(!ULE->getQualifier() && "qualified name with ADL");
6180
6181 // We don't perform ADL for implicit declarations of builtins.
6182 // Verify that this was correctly set up.
6183 FunctionDecl *F;
6184 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6185 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6186 F->getBuiltinID() && F->isImplicit())
6187 assert(0 && "performing ADL for builtin");
6188
6189 // We don't perform ADL in C.
6190 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6191 }
6192#endif
6193
John McCallbc077cf2010-02-08 23:07:23 +00006194 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006195
John McCall57500772009-12-16 12:17:52 +00006196 // Add the functions denoted by the callee to the set of candidate
6197 // functions, including those from argument-dependent lookup.
6198 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006199
6200 // If we found nothing, try to recover.
6201 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6202 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006203 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006204 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006205 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006206
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006207 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006208 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006209 case OR_Success: {
6210 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006211 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006212 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006213 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006214 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6215 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006216
6217 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006218 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006219 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006220 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006221 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006222 break;
6223
6224 case OR_Ambiguous:
6225 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006226 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006227 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006228 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006229
6230 case OR_Deleted:
6231 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6232 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006233 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006234 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006235 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006236 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006237 }
6238
6239 // Overload resolution failed. Destroy all of the subexpressions and
6240 // return NULL.
6241 Fn->Destroy(Context);
6242 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6243 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006244 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006245}
6246
John McCall4c4c1df2010-01-26 03:27:55 +00006247static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006248 return Functions.size() > 1 ||
6249 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6250}
6251
Douglas Gregor084d8552009-03-13 23:49:33 +00006252/// \brief Create a unary operation that may resolve to an overloaded
6253/// operator.
6254///
6255/// \param OpLoc The location of the operator itself (e.g., '*').
6256///
6257/// \param OpcIn The UnaryOperator::Opcode that describes this
6258/// operator.
6259///
6260/// \param Functions The set of non-member functions that will be
6261/// considered by overload resolution. The caller needs to build this
6262/// set based on the context using, e.g.,
6263/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6264/// set should not contain any member functions; those will be added
6265/// by CreateOverloadedUnaryOp().
6266///
6267/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006268Sema::OwningExprResult
6269Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6270 const UnresolvedSetImpl &Fns,
6271 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006272 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6273 Expr *Input = (Expr *)input.get();
6274
6275 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6276 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6277 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6278
6279 Expr *Args[2] = { Input, 0 };
6280 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006281
Douglas Gregor084d8552009-03-13 23:49:33 +00006282 // For post-increment and post-decrement, add the implicit '0' as
6283 // the second argument, so that we know this is a post-increment or
6284 // post-decrement.
6285 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6286 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006287 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006288 SourceLocation());
6289 NumArgs = 2;
6290 }
6291
6292 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00006293 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006294 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006295 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006296 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006297 /*ADL*/ true, IsOverloaded(Fns),
6298 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006299 input.release();
6300 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6301 &Args[0], NumArgs,
6302 Context.DependentTy,
6303 OpLoc));
6304 }
6305
6306 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006307 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006308
6309 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006310 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006311
6312 // Add operator candidates that are member functions.
6313 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6314
John McCall4c4c1df2010-01-26 03:27:55 +00006315 // Add candidates from ADL.
6316 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006317 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006318 /*ExplicitTemplateArgs*/ 0,
6319 CandidateSet);
6320
Douglas Gregor084d8552009-03-13 23:49:33 +00006321 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006322 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006323
6324 // Perform overload resolution.
6325 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006326 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006327 case OR_Success: {
6328 // We found a built-in operator or an overloaded operator.
6329 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006330
Douglas Gregor084d8552009-03-13 23:49:33 +00006331 if (FnDecl) {
6332 // We matched an overloaded operator. Build a call to that
6333 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006334
Douglas Gregor084d8552009-03-13 23:49:33 +00006335 // Convert the arguments.
6336 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006337 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006338
John McCall16df1e52010-03-30 21:47:33 +00006339 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6340 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006341 return ExprError();
6342 } else {
6343 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006344 OwningExprResult InputInit
6345 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006346 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006347 SourceLocation(),
6348 move(input));
6349 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006350 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006351
Douglas Gregore6600372009-12-23 17:40:29 +00006352 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006353 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006354 }
6355
John McCall4fa0d5f2010-05-06 18:15:07 +00006356 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6357
Douglas Gregor084d8552009-03-13 23:49:33 +00006358 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006359 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006360
Douglas Gregor084d8552009-03-13 23:49:33 +00006361 // Build the actual expression node.
6362 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6363 SourceLocation());
6364 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006365
Douglas Gregor084d8552009-03-13 23:49:33 +00006366 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006367 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006368 ExprOwningPtr<CallExpr> TheCall(this,
6369 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006370 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006371
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006372 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6373 FnDecl))
6374 return ExprError();
6375
6376 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006377 } else {
6378 // We matched a built-in operator. Convert the arguments, then
6379 // break out so that we will build the appropriate built-in
6380 // operator node.
6381 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006382 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006383 return ExprError();
6384
6385 break;
6386 }
6387 }
6388
6389 case OR_No_Viable_Function:
6390 // No viable function; fall through to handling this as a
6391 // built-in operator, which will produce an error message for us.
6392 break;
6393
6394 case OR_Ambiguous:
6395 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6396 << UnaryOperator::getOpcodeStr(Opc)
6397 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006398 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006399 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006400 return ExprError();
6401
6402 case OR_Deleted:
6403 Diag(OpLoc, diag::err_ovl_deleted_oper)
6404 << Best->Function->isDeleted()
6405 << UnaryOperator::getOpcodeStr(Opc)
6406 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006407 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006408 return ExprError();
6409 }
6410
6411 // Either we found no viable overloaded operator or we matched a
6412 // built-in operator. In either case, fall through to trying to
6413 // build a built-in operation.
6414 input.release();
6415 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6416}
6417
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006418/// \brief Create a binary operation that may resolve to an overloaded
6419/// operator.
6420///
6421/// \param OpLoc The location of the operator itself (e.g., '+').
6422///
6423/// \param OpcIn The BinaryOperator::Opcode that describes this
6424/// operator.
6425///
6426/// \param Functions The set of non-member functions that will be
6427/// considered by overload resolution. The caller needs to build this
6428/// set based on the context using, e.g.,
6429/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6430/// set should not contain any member functions; those will be added
6431/// by CreateOverloadedBinOp().
6432///
6433/// \param LHS Left-hand argument.
6434/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006435Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006436Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006437 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006438 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006439 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006440 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006441 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006442
6443 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6444 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6445 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6446
6447 // If either side is type-dependent, create an appropriate dependent
6448 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006449 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006450 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006451 // If there are no functions to store, just build a dependent
6452 // BinaryOperator or CompoundAssignment.
6453 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6454 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6455 Context.DependentTy, OpLoc));
6456
6457 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6458 Context.DependentTy,
6459 Context.DependentTy,
6460 Context.DependentTy,
6461 OpLoc));
6462 }
John McCall4c4c1df2010-01-26 03:27:55 +00006463
6464 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006465 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006466 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006467 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006468 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006469 /*ADL*/ true, IsOverloaded(Fns),
6470 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006471 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006472 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006473 Context.DependentTy,
6474 OpLoc));
6475 }
6476
6477 // If this is the .* operator, which is not overloadable, just
6478 // create a built-in binary operator.
6479 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006480 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006481
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006482 // If this is the assignment operator, we only perform overload resolution
6483 // if the left-hand side is a class or enumeration type. This is actually
6484 // a hack. The standard requires that we do overload resolution between the
6485 // various built-in candidates, but as DR507 points out, this can lead to
6486 // problems. So we do it this way, which pretty much follows what GCC does.
6487 // Note that we go the traditional code path for compound assignment forms.
6488 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006489 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006490
Douglas Gregor084d8552009-03-13 23:49:33 +00006491 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006492 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006493
6494 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006495 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006496
6497 // Add operator candidates that are member functions.
6498 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6499
John McCall4c4c1df2010-01-26 03:27:55 +00006500 // Add candidates from ADL.
6501 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6502 Args, 2,
6503 /*ExplicitTemplateArgs*/ 0,
6504 CandidateSet);
6505
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006506 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006507 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006508
6509 // Perform overload resolution.
6510 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006511 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006512 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006513 // We found a built-in operator or an overloaded operator.
6514 FunctionDecl *FnDecl = Best->Function;
6515
6516 if (FnDecl) {
6517 // We matched an overloaded operator. Build a call to that
6518 // operator.
6519
6520 // Convert the arguments.
6521 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006522 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006523 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006524
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006525 OwningExprResult Arg1
6526 = PerformCopyInitialization(
6527 InitializedEntity::InitializeParameter(
6528 FnDecl->getParamDecl(0)),
6529 SourceLocation(),
6530 Owned(Args[1]));
6531 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006532 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006533
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006534 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006535 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006536 return ExprError();
6537
6538 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006539 } else {
6540 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006541 OwningExprResult Arg0
6542 = PerformCopyInitialization(
6543 InitializedEntity::InitializeParameter(
6544 FnDecl->getParamDecl(0)),
6545 SourceLocation(),
6546 Owned(Args[0]));
6547 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006548 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006549
6550 OwningExprResult Arg1
6551 = PerformCopyInitialization(
6552 InitializedEntity::InitializeParameter(
6553 FnDecl->getParamDecl(1)),
6554 SourceLocation(),
6555 Owned(Args[1]));
6556 if (Arg1.isInvalid())
6557 return ExprError();
6558 Args[0] = LHS = Arg0.takeAs<Expr>();
6559 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006560 }
6561
John McCall4fa0d5f2010-05-06 18:15:07 +00006562 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6563
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006564 // Determine the result type
6565 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006566 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006567 ResultTy = ResultTy.getNonReferenceType();
6568
6569 // Build the actual expression node.
6570 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006571 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006572 UsualUnaryConversions(FnExpr);
6573
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006574 ExprOwningPtr<CXXOperatorCallExpr>
6575 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6576 Args, 2, ResultTy,
6577 OpLoc));
6578
6579 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6580 FnDecl))
6581 return ExprError();
6582
6583 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006584 } else {
6585 // We matched a built-in operator. Convert the arguments, then
6586 // break out so that we will build the appropriate built-in
6587 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006588 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006589 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006590 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006591 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006592 return ExprError();
6593
6594 break;
6595 }
6596 }
6597
Douglas Gregor66950a32009-09-30 21:46:01 +00006598 case OR_No_Viable_Function: {
6599 // C++ [over.match.oper]p9:
6600 // If the operator is the operator , [...] and there are no
6601 // viable functions, then the operator is assumed to be the
6602 // built-in operator and interpreted according to clause 5.
6603 if (Opc == BinaryOperator::Comma)
6604 break;
6605
Sebastian Redl027de2a2009-05-21 11:50:50 +00006606 // For class as left operand for assignment or compound assigment operator
6607 // do not fall through to handling in built-in, but report that no overloaded
6608 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006609 OwningExprResult Result = ExprError();
6610 if (Args[0]->getType()->isRecordType() &&
6611 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006612 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6613 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006614 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006615 } else {
6616 // No viable function; try to create a built-in operation, which will
6617 // produce an error. Then, show the non-viable candidates.
6618 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006619 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006620 assert(Result.isInvalid() &&
6621 "C++ binary operator overloading is missing candidates!");
6622 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006623 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006624 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006625 return move(Result);
6626 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006627
6628 case OR_Ambiguous:
6629 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6630 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006631 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006632 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006633 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006634 return ExprError();
6635
6636 case OR_Deleted:
6637 Diag(OpLoc, diag::err_ovl_deleted_oper)
6638 << Best->Function->isDeleted()
6639 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006640 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006641 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006642 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006643 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006644
Douglas Gregor66950a32009-09-30 21:46:01 +00006645 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006646 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006647}
6648
Sebastian Redladba46e2009-10-29 20:17:01 +00006649Action::OwningExprResult
6650Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6651 SourceLocation RLoc,
6652 ExprArg Base, ExprArg Idx) {
6653 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6654 static_cast<Expr*>(Idx.get()) };
6655 DeclarationName OpName =
6656 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6657
6658 // If either side is type-dependent, create an appropriate dependent
6659 // expression.
6660 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6661
John McCall58cc69d2010-01-27 01:50:18 +00006662 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006663 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006664 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006665 0, SourceRange(), OpName, LLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006666 /*ADL*/ true, /*Overloaded*/ false,
6667 UnresolvedSetIterator(),
6668 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00006669 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006670
6671 Base.release();
6672 Idx.release();
6673 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6674 Args, 2,
6675 Context.DependentTy,
6676 RLoc));
6677 }
6678
6679 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006680 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006681
6682 // Subscript can only be overloaded as a member function.
6683
6684 // Add operator candidates that are member functions.
6685 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6686
6687 // Add builtin operator candidates.
6688 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6689
6690 // Perform overload resolution.
6691 OverloadCandidateSet::iterator Best;
6692 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6693 case OR_Success: {
6694 // We found a built-in operator or an overloaded operator.
6695 FunctionDecl *FnDecl = Best->Function;
6696
6697 if (FnDecl) {
6698 // We matched an overloaded operator. Build a call to that
6699 // operator.
6700
John McCalla0296f72010-03-19 07:35:19 +00006701 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006702 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006703
Sebastian Redladba46e2009-10-29 20:17:01 +00006704 // Convert the arguments.
6705 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006706 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006707 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006708 return ExprError();
6709
Anders Carlssona68e51e2010-01-29 18:37:50 +00006710 // Convert the arguments.
6711 OwningExprResult InputInit
6712 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6713 FnDecl->getParamDecl(0)),
6714 SourceLocation(),
6715 Owned(Args[1]));
6716 if (InputInit.isInvalid())
6717 return ExprError();
6718
6719 Args[1] = InputInit.takeAs<Expr>();
6720
Sebastian Redladba46e2009-10-29 20:17:01 +00006721 // Determine the result type
6722 QualType ResultTy
6723 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6724 ResultTy = ResultTy.getNonReferenceType();
6725
6726 // Build the actual expression node.
6727 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6728 LLoc);
6729 UsualUnaryConversions(FnExpr);
6730
6731 Base.release();
6732 Idx.release();
6733 ExprOwningPtr<CXXOperatorCallExpr>
6734 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6735 FnExpr, Args, 2,
6736 ResultTy, RLoc));
6737
6738 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6739 FnDecl))
6740 return ExprError();
6741
6742 return MaybeBindToTemporary(TheCall.release());
6743 } else {
6744 // We matched a built-in operator. Convert the arguments, then
6745 // break out so that we will build the appropriate built-in
6746 // operator node.
6747 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006748 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006749 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006750 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006751 return ExprError();
6752
6753 break;
6754 }
6755 }
6756
6757 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006758 if (CandidateSet.empty())
6759 Diag(LLoc, diag::err_ovl_no_oper)
6760 << Args[0]->getType() << /*subscript*/ 0
6761 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6762 else
6763 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6764 << Args[0]->getType()
6765 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006766 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006767 "[]", LLoc);
6768 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006769 }
6770
6771 case OR_Ambiguous:
6772 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6773 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006774 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006775 "[]", LLoc);
6776 return ExprError();
6777
6778 case OR_Deleted:
6779 Diag(LLoc, diag::err_ovl_deleted_oper)
6780 << Best->Function->isDeleted() << "[]"
6781 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006782 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006783 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006784 return ExprError();
6785 }
6786
6787 // We matched a built-in operator; build it.
6788 Base.release();
6789 Idx.release();
6790 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6791 Owned(Args[1]), RLoc);
6792}
6793
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006794/// BuildCallToMemberFunction - Build a call to a member
6795/// function. MemExpr is the expression that refers to the member
6796/// function (and includes the object parameter), Args/NumArgs are the
6797/// arguments to the function call (not including the object
6798/// parameter). The caller needs to validate that the member
6799/// expression refers to a member function or an overloaded member
6800/// function.
John McCall2d74de92009-12-01 22:10:20 +00006801Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006802Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6803 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006804 unsigned NumArgs, SourceLocation *CommaLocs,
6805 SourceLocation RParenLoc) {
6806 // Dig out the member expression. This holds both the object
6807 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006808 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6809
John McCall10eae182009-11-30 22:42:35 +00006810 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006811 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006812 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006813 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006814 if (isa<MemberExpr>(NakedMemExpr)) {
6815 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006816 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006817 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006818 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006819 } else {
6820 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006821 Qualifier = UnresExpr->getQualifier();
6822
John McCall6e9f8f62009-12-03 04:06:58 +00006823 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006824
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006825 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006826 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006827
John McCall2d74de92009-12-01 22:10:20 +00006828 // FIXME: avoid copy.
6829 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6830 if (UnresExpr->hasExplicitTemplateArgs()) {
6831 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6832 TemplateArgs = &TemplateArgsBuffer;
6833 }
6834
John McCall10eae182009-11-30 22:42:35 +00006835 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6836 E = UnresExpr->decls_end(); I != E; ++I) {
6837
John McCall6e9f8f62009-12-03 04:06:58 +00006838 NamedDecl *Func = *I;
6839 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6840 if (isa<UsingShadowDecl>(Func))
6841 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6842
John McCall10eae182009-11-30 22:42:35 +00006843 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006844 // If explicit template arguments were provided, we can't call a
6845 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006846 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006847 continue;
6848
John McCalla0296f72010-03-19 07:35:19 +00006849 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006850 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006851 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006852 } else {
John McCall10eae182009-11-30 22:42:35 +00006853 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006854 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006855 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006856 CandidateSet,
6857 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006858 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006859 }
Mike Stump11289f42009-09-09 15:08:12 +00006860
John McCall10eae182009-11-30 22:42:35 +00006861 DeclarationName DeclName = UnresExpr->getMemberName();
6862
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006863 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006864 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006865 case OR_Success:
6866 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006867 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006868 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006869 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006870 break;
6871
6872 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006873 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006874 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006875 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006876 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006877 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006878 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006879
6880 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006881 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006882 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006883 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006884 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006885 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006886
6887 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006888 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006889 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006890 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006891 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006892 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006893 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006894 }
6895
John McCall16df1e52010-03-30 21:47:33 +00006896 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006897
John McCall2d74de92009-12-01 22:10:20 +00006898 // If overload resolution picked a static member, build a
6899 // non-member call based on that function.
6900 if (Method->isStatic()) {
6901 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6902 Args, NumArgs, RParenLoc);
6903 }
6904
John McCall10eae182009-11-30 22:42:35 +00006905 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006906 }
6907
6908 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006909 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006910 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006911 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006912 Method->getResultType().getNonReferenceType(),
6913 RParenLoc));
6914
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006915 // Check for a valid return type.
6916 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6917 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006918 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006919
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006920 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006921 // We only need to do this if there was actually an overload; otherwise
6922 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006923 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006924 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006925 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6926 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006927 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006928 MemExpr->setBase(ObjectArg);
6929
6930 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00006931 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00006932 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006933 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006934 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006935
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006936 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006937 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006938
John McCall2d74de92009-12-01 22:10:20 +00006939 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006940}
6941
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006942/// BuildCallToObjectOfClassType - Build a call to an object of class
6943/// type (C++ [over.call.object]), which can end up invoking an
6944/// overloaded function call operator (@c operator()) or performing a
6945/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006946Sema::ExprResult
6947Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006948 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006949 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006950 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006951 SourceLocation RParenLoc) {
6952 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006953 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006954
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006955 // C++ [over.call.object]p1:
6956 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006957 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006958 // candidate functions includes at least the function call
6959 // operators of T. The function call operators of T are obtained by
6960 // ordinary lookup of the name operator() in the context of
6961 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006962 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006963 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006964
6965 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006966 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006967 << Object->getSourceRange()))
6968 return true;
6969
John McCall27b18f82009-11-17 02:14:36 +00006970 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6971 LookupQualifiedName(R, Record->getDecl());
6972 R.suppressDiagnostics();
6973
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006974 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006975 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006976 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006977 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006978 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006979 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006980
Douglas Gregorab7897a2008-11-19 22:57:39 +00006981 // C++ [over.call.object]p2:
6982 // In addition, for each conversion function declared in T of the
6983 // form
6984 //
6985 // operator conversion-type-id () cv-qualifier;
6986 //
6987 // where cv-qualifier is the same cv-qualification as, or a
6988 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006989 // denotes the type "pointer to function of (P1,...,Pn) returning
6990 // R", or the type "reference to pointer to function of
6991 // (P1,...,Pn) returning R", or the type "reference to function
6992 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006993 // is also considered as a candidate function. Similarly,
6994 // surrogate call functions are added to the set of candidate
6995 // functions for each conversion function declared in an
6996 // accessible base class provided the function is not hidden
6997 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006998 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006999 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007000 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007001 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007002 NamedDecl *D = *I;
7003 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7004 if (isa<UsingShadowDecl>(D))
7005 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7006
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007007 // Skip over templated conversion functions; they aren't
7008 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007009 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007010 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007011
John McCall6e9f8f62009-12-03 04:06:58 +00007012 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007013
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007014 // Strip the reference type (if any) and then the pointer type (if
7015 // any) to get down to what might be a function type.
7016 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7017 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7018 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007019
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007020 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007021 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007022 Object->getType(), Args, NumArgs,
7023 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007024 }
Mike Stump11289f42009-09-09 15:08:12 +00007025
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007026 // Perform overload resolution.
7027 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007028 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007029 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007030 // Overload resolution succeeded; we'll build the appropriate call
7031 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007032 break;
7033
7034 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007035 if (CandidateSet.empty())
7036 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7037 << Object->getType() << /*call*/ 1
7038 << Object->getSourceRange();
7039 else
7040 Diag(Object->getSourceRange().getBegin(),
7041 diag::err_ovl_no_viable_object_call)
7042 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007043 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007044 break;
7045
7046 case OR_Ambiguous:
7047 Diag(Object->getSourceRange().getBegin(),
7048 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007049 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007050 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007051 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007052
7053 case OR_Deleted:
7054 Diag(Object->getSourceRange().getBegin(),
7055 diag::err_ovl_deleted_object_call)
7056 << Best->Function->isDeleted()
7057 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007058 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007059 break;
Mike Stump11289f42009-09-09 15:08:12 +00007060 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007061
Douglas Gregorab7897a2008-11-19 22:57:39 +00007062 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007063 // We had an error; delete all of the subexpressions and return
7064 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00007065 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007066 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00007067 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007068 return true;
7069 }
7070
Douglas Gregorab7897a2008-11-19 22:57:39 +00007071 if (Best->Function == 0) {
7072 // Since there is no function declaration, this is one of the
7073 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007074 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007075 = cast<CXXConversionDecl>(
7076 Best->Conversions[0].UserDefined.ConversionFunction);
7077
John McCalla0296f72010-03-19 07:35:19 +00007078 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007079 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007080
Douglas Gregorab7897a2008-11-19 22:57:39 +00007081 // We selected one of the surrogate functions that converts the
7082 // object parameter to a function pointer. Perform the conversion
7083 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007084
7085 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007086 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007087 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7088 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007089
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007090 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007091 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007092 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007093 }
7094
John McCalla0296f72010-03-19 07:35:19 +00007095 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007096 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007097
Douglas Gregorab7897a2008-11-19 22:57:39 +00007098 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7099 // that calls this method, using Object for the implicit object
7100 // parameter and passing along the remaining arguments.
7101 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007102 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007103
7104 unsigned NumArgsInProto = Proto->getNumArgs();
7105 unsigned NumArgsToCheck = NumArgs;
7106
7107 // Build the full argument list for the method call (the
7108 // implicit object parameter is placed at the beginning of the
7109 // list).
7110 Expr **MethodArgs;
7111 if (NumArgs < NumArgsInProto) {
7112 NumArgsToCheck = NumArgsInProto;
7113 MethodArgs = new Expr*[NumArgsInProto + 1];
7114 } else {
7115 MethodArgs = new Expr*[NumArgs + 1];
7116 }
7117 MethodArgs[0] = Object;
7118 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7119 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007120
7121 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007122 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007123 UsualUnaryConversions(NewFn);
7124
7125 // Once we've built TheCall, all of the expressions are properly
7126 // owned.
7127 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00007128 ExprOwningPtr<CXXOperatorCallExpr>
7129 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007130 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007131 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007132 delete [] MethodArgs;
7133
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007134 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7135 Method))
7136 return true;
7137
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007138 // We may have default arguments. If so, we need to allocate more
7139 // slots in the call for them.
7140 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007141 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007142 else if (NumArgs > NumArgsInProto)
7143 NumArgsToCheck = NumArgsInProto;
7144
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007145 bool IsError = false;
7146
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007147 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007148 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007149 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007150 TheCall->setArg(0, Object);
7151
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007152
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007153 // Check the argument types.
7154 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007155 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007156 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007157 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007158
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007159 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007160
7161 OwningExprResult InputInit
7162 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7163 Method->getParamDecl(i)),
7164 SourceLocation(), Owned(Arg));
7165
7166 IsError |= InputInit.isInvalid();
7167 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007168 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007169 OwningExprResult DefArg
7170 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7171 if (DefArg.isInvalid()) {
7172 IsError = true;
7173 break;
7174 }
7175
7176 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007177 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007178
7179 TheCall->setArg(i + 1, Arg);
7180 }
7181
7182 // If this is a variadic call, handle args passed through "...".
7183 if (Proto->isVariadic()) {
7184 // Promote the arguments (C99 6.5.2.2p7).
7185 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7186 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007187 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007188 TheCall->setArg(i + 1, Arg);
7189 }
7190 }
7191
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007192 if (IsError) return true;
7193
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007194 if (CheckFunctionCall(Method, TheCall.get()))
7195 return true;
7196
Douglas Gregore5e775b2010-04-13 15:50:39 +00007197 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007198}
7199
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007200/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007201/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007202/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007203Sema::OwningExprResult
7204Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7205 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007206 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007207
John McCallbc077cf2010-02-08 23:07:23 +00007208 SourceLocation Loc = Base->getExprLoc();
7209
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007210 // C++ [over.ref]p1:
7211 //
7212 // [...] An expression x->m is interpreted as (x.operator->())->m
7213 // for a class object x of type T if T::operator->() exists and if
7214 // the operator is selected as the best match function by the
7215 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007216 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007217 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007218 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007219
John McCallbc077cf2010-02-08 23:07:23 +00007220 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007221 PDiag(diag::err_typecheck_incomplete_tag)
7222 << Base->getSourceRange()))
7223 return ExprError();
7224
John McCall27b18f82009-11-17 02:14:36 +00007225 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7226 LookupQualifiedName(R, BaseRecord->getDecl());
7227 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007228
7229 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007230 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007231 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007232 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007233 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007234
7235 // Perform overload resolution.
7236 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007237 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007238 case OR_Success:
7239 // Overload resolution succeeded; we'll build the call below.
7240 break;
7241
7242 case OR_No_Viable_Function:
7243 if (CandidateSet.empty())
7244 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007245 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007246 else
7247 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007248 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007249 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007250 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007251
7252 case OR_Ambiguous:
7253 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007254 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007255 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007256 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007257
7258 case OR_Deleted:
7259 Diag(OpLoc, diag::err_ovl_deleted_oper)
7260 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007261 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007262 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007263 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007264 }
7265
John McCalla0296f72010-03-19 07:35:19 +00007266 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007267 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007268
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007269 // Convert the object parameter.
7270 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007271 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7272 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007273 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007274
7275 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007276 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007277
7278 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007279 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7280 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007281 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007282
7283 QualType ResultTy = Method->getResultType().getNonReferenceType();
7284 ExprOwningPtr<CXXOperatorCallExpr>
7285 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7286 &Base, 1, ResultTy, OpLoc));
7287
7288 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7289 Method))
7290 return ExprError();
7291 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007292}
7293
Douglas Gregorcd695e52008-11-10 20:40:00 +00007294/// FixOverloadedFunctionReference - E is an expression that refers to
7295/// a C++ overloaded function (possibly with some parentheses and
7296/// perhaps a '&' around it). We have resolved the overloaded function
7297/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007298/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007299Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007300 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007301 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007302 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7303 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007304 if (SubExpr == PE->getSubExpr())
7305 return PE->Retain();
7306
7307 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7308 }
7309
7310 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007311 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7312 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007313 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007314 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007315 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007316 if (SubExpr == ICE->getSubExpr())
7317 return ICE->Retain();
7318
7319 return new (Context) ImplicitCastExpr(ICE->getType(),
7320 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007321 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007322 ICE->isLvalueCast());
7323 }
7324
7325 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007326 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007327 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7329 if (Method->isStatic()) {
7330 // Do nothing: static member functions aren't any different
7331 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007332 } else {
John McCalle66edc12009-11-24 19:00:30 +00007333 // Fix the sub expression, which really has to be an
7334 // UnresolvedLookupExpr holding an overloaded member function
7335 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007336 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7337 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007338 if (SubExpr == UnOp->getSubExpr())
7339 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007340
John McCalld14a8642009-11-21 08:51:07 +00007341 assert(isa<DeclRefExpr>(SubExpr)
7342 && "fixed to something other than a decl ref");
7343 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7344 && "fixed to a member ref with no nested name qualifier");
7345
7346 // We have taken the address of a pointer to member
7347 // function. Perform the computation here so that we get the
7348 // appropriate pointer to member type.
7349 QualType ClassType
7350 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7351 QualType MemPtrType
7352 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7353
7354 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7355 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007356 }
7357 }
John McCall16df1e52010-03-30 21:47:33 +00007358 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7359 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007360 if (SubExpr == UnOp->getSubExpr())
7361 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007362
Douglas Gregor51c538b2009-11-20 19:42:02 +00007363 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7364 Context.getPointerType(SubExpr->getType()),
7365 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007366 }
John McCalld14a8642009-11-21 08:51:07 +00007367
7368 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007369 // FIXME: avoid copy.
7370 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007371 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007372 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7373 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007374 }
7375
John McCalld14a8642009-11-21 08:51:07 +00007376 return DeclRefExpr::Create(Context,
7377 ULE->getQualifier(),
7378 ULE->getQualifierRange(),
7379 Fn,
7380 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007381 Fn->getType(),
7382 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007383 }
7384
John McCall10eae182009-11-30 22:42:35 +00007385 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007386 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007387 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7388 if (MemExpr->hasExplicitTemplateArgs()) {
7389 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7390 TemplateArgs = &TemplateArgsBuffer;
7391 }
John McCall6b51f282009-11-23 01:53:49 +00007392
John McCall2d74de92009-12-01 22:10:20 +00007393 Expr *Base;
7394
7395 // If we're filling in
7396 if (MemExpr->isImplicitAccess()) {
7397 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7398 return DeclRefExpr::Create(Context,
7399 MemExpr->getQualifier(),
7400 MemExpr->getQualifierRange(),
7401 Fn,
7402 MemExpr->getMemberLoc(),
7403 Fn->getType(),
7404 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007405 } else {
7406 SourceLocation Loc = MemExpr->getMemberLoc();
7407 if (MemExpr->getQualifier())
7408 Loc = MemExpr->getQualifierRange().getBegin();
7409 Base = new (Context) CXXThisExpr(Loc,
7410 MemExpr->getBaseType(),
7411 /*isImplicit=*/true);
7412 }
John McCall2d74de92009-12-01 22:10:20 +00007413 } else
7414 Base = MemExpr->getBase()->Retain();
7415
7416 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007417 MemExpr->isArrow(),
7418 MemExpr->getQualifier(),
7419 MemExpr->getQualifierRange(),
7420 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007421 Found,
John McCall6b51f282009-11-23 01:53:49 +00007422 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007423 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007424 Fn->getType());
7425 }
7426
Douglas Gregor51c538b2009-11-20 19:42:02 +00007427 assert(false && "Invalid reference to overloaded function");
7428 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007429}
7430
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007431Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007432 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007433 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007434 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007435}
7436
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007437} // end namespace clang