blob: 61d42f083c61f80643b2df13c237e48f4238f4f5 [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 McCall6d1116a2010-06-11 10:04:22 +0000158 (getFromType()->isPointerType() ||
159 getFromType()->isObjCObjectPointerType() ||
160 getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
162 return true;
163
164 return false;
165}
166
Douglas Gregor5c407d92008-10-23 00:40:37 +0000167/// isPointerConversionToVoidPointer - Determines whether this
168/// conversion is a conversion of a pointer to a void pointer. This is
169/// used as part of the ranking of standard conversion sequences (C++
170/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000171bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000172StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000173isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000174 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000175 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000176
177 // Note that FromType has not necessarily been transformed by the
178 // array-to-pointer implicit conversion, so check for its presence
179 // and redo the conversion to get a pointer.
180 if (First == ICK_Array_To_Pointer)
181 FromType = Context.getArrayDecayedType(FromType);
182
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000185 return ToPtrType->getPointeeType()->isVoidType();
186
187 return false;
188}
189
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000190/// DebugPrint - Print this standard conversion sequence to standard
191/// error. Useful for debugging overloading issues.
192void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000193 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194 bool PrintedSomething = false;
195 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000197 PrintedSomething = true;
198 }
199
200 if (Second != ICK_Identity) {
201 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000202 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000203 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000204 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000205
206 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000207 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000208 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000209 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000210 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000211 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000212 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (Third != ICK_Identity) {
217 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000218 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000220 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221 PrintedSomething = true;
222 }
223
224 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000225 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000226 }
227}
228
229/// DebugPrint - Print this user-defined conversion sequence to standard
230/// error. Useful for debugging overloading issues.
231void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000232 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000233 if (Before.First || Before.Second || Before.Third) {
234 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000237 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 After.DebugPrint();
241 }
242}
243
244/// DebugPrint - Print this implicit conversion sequence to standard
245/// error. Useful for debugging overloading issues.
246void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000247 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000248 switch (ConversionKind) {
249 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 Standard.DebugPrint();
252 break;
253 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000254 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 UserDefined.DebugPrint();
256 break;
257 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000258 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000259 break;
John McCall0d1da222010-01-12 00:44:57 +0000260 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000261 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000262 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 break;
266 }
267
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269}
270
John McCall0d1da222010-01-12 00:44:57 +0000271void AmbiguousConversionSequence::construct() {
272 new (&conversions()) ConversionSet();
273}
274
275void AmbiguousConversionSequence::destruct() {
276 conversions().~ConversionSet();
277}
278
279void
280AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
281 FromTypePtr = O.FromTypePtr;
282 ToTypePtr = O.ToTypePtr;
283 new (&conversions()) ConversionSet(O.conversions());
284}
285
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000286namespace {
287 // Structure used by OverloadCandidate::DeductionFailureInfo to store
288 // template parameter and template argument information.
289 struct DFIParamWithArguments {
290 TemplateParameter Param;
291 TemplateArgument FirstArg;
292 TemplateArgument SecondArg;
293 };
294}
295
296/// \brief Convert from Sema's representation of template deduction information
297/// to the form used in overload-candidate information.
298OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000299static MakeDeductionFailureInfo(ASTContext &Context,
300 Sema::TemplateDeductionResult TDK,
Douglas Gregord09efd42010-05-08 20:07:26 +0000301 Sema::TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000302 OverloadCandidate::DeductionFailureInfo Result;
303 Result.Result = static_cast<unsigned>(TDK);
304 Result.Data = 0;
305 switch (TDK) {
306 case Sema::TDK_Success:
307 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000308 case Sema::TDK_TooManyArguments:
309 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000310 break;
311
312 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000313 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000314 Result.Data = Info.Param.getOpaqueValue();
315 break;
316
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000317 case Sema::TDK_Inconsistent:
318 case Sema::TDK_InconsistentQuals: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000319 // FIXME: Should allocate from normal heap so that we can free this later.
320 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000321 Saved->Param = Info.Param;
322 Saved->FirstArg = Info.FirstArg;
323 Saved->SecondArg = Info.SecondArg;
324 Result.Data = Saved;
325 break;
326 }
327
328 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000329 Result.Data = Info.take();
330 break;
331
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000332 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000333 case Sema::TDK_FailedOverloadResolution:
334 break;
335 }
336
337 return Result;
338}
John McCall0d1da222010-01-12 00:44:57 +0000339
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000340void OverloadCandidate::DeductionFailureInfo::Destroy() {
341 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
342 case Sema::TDK_Success:
343 case Sema::TDK_InstantiationDepth:
344 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000345 case Sema::TDK_TooManyArguments:
346 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000347 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000348 break;
349
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
351 case Sema::TDK_InconsistentQuals:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000352 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000353 Data = 0;
354 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000355
356 case Sema::TDK_SubstitutionFailure:
357 // FIXME: Destroy the template arugment list?
358 Data = 0;
359 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360
Douglas Gregor461761d2010-05-08 18:20:53 +0000361 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000363 case Sema::TDK_FailedOverloadResolution:
364 break;
365 }
366}
367
368TemplateParameter
369OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
370 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
371 case Sema::TDK_Success:
372 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000373 case Sema::TDK_TooManyArguments:
374 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000375 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 return TemplateParameter();
377
378 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 return TemplateParameter::getFromOpaqueValue(Data);
381
382 case Sema::TDK_Inconsistent:
383 case Sema::TDK_InconsistentQuals:
384 return static_cast<DFIParamWithArguments*>(Data)->Param;
385
386 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000387 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_FailedOverloadResolution:
389 break;
390 }
391
392 return TemplateParameter();
393}
Douglas Gregord09efd42010-05-08 20:07:26 +0000394
395TemplateArgumentList *
396OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
397 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
398 case Sema::TDK_Success:
399 case Sema::TDK_InstantiationDepth:
400 case Sema::TDK_TooManyArguments:
401 case Sema::TDK_TooFewArguments:
402 case Sema::TDK_Incomplete:
403 case Sema::TDK_InvalidExplicitArguments:
404 case Sema::TDK_Inconsistent:
405 case Sema::TDK_InconsistentQuals:
406 return 0;
407
408 case Sema::TDK_SubstitutionFailure:
409 return static_cast<TemplateArgumentList*>(Data);
410
411 // Unhandled
412 case Sema::TDK_NonDeducedMismatch:
413 case Sema::TDK_FailedOverloadResolution:
414 break;
415 }
416
417 return 0;
418}
419
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
421 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
422 case Sema::TDK_Success:
423 case Sema::TDK_InstantiationDepth:
424 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000425 case Sema::TDK_TooManyArguments:
426 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000428 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429 return 0;
430
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_Inconsistent:
432 case Sema::TDK_InconsistentQuals:
433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
434
Douglas Gregor461761d2010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440
441 return 0;
442}
443
444const TemplateArgument *
445OverloadCandidate::DeductionFailureInfo::getSecondArg() {
446 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
447 case Sema::TDK_Success:
448 case Sema::TDK_InstantiationDepth:
449 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000450 case Sema::TDK_TooManyArguments:
451 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000452 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000453 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 return 0;
455
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000456 case Sema::TDK_Inconsistent:
457 case Sema::TDK_InconsistentQuals:
458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor461761d2010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000475// overload of the declarations in Old. This routine returns false if
476// New and Old cannot be overloaded, e.g., if New has the same
477// signature as some function in Old (C++ 1.3.10) or if the Old
478// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000479// it does return false, MatchedDecl will point to the decl that New
480// cannot be overloaded with. This decl may be a UsingShadowDecl on
481// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482//
483// Example: Given the following input:
484//
485// void f(int, float); // #1
486// void f(int, int); // #2
487// int f(int, int); // #3
488//
489// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491//
John McCall3d988d92009-12-02 08:47:38 +0000492// When we process #2, Old contains only the FunctionDecl for #1. By
493// comparing the parameter types, we see that #1 and #2 are overloaded
494// (since they have different signatures), so this routine returns
495// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496//
John McCall3d988d92009-12-02 08:47:38 +0000497// When we process #3, Old is an overload set containing #1 and #2. We
498// compare the signatures of #3 to #1 (they're overloaded, so we do
499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
500// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000503//
504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
505// into a class by a using declaration. The rules for whether to hide
506// shadow declarations ignore some properties which otherwise figure
507// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000513 NamedDecl *OldD = *I;
514
515 bool OldIsUsingDecl = false;
516 if (isa<UsingShadowDecl>(OldD)) {
517 OldIsUsingDecl = true;
518
519 // We can always introduce two using declarations into the same
520 // context, even if they have identical signatures.
521 if (NewIsUsingDecl) continue;
522
523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
524 }
525
526 // If either declaration was introduced by a using declaration,
527 // we'll need to use slightly different rules for matching.
528 // Essentially, these rules are the normal rules, except that
529 // function templates hide function templates with different
530 // return types or template parameter lists.
531 bool UseMemberUsingDeclRules =
532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
533
John McCall3d988d92009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
536 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
538 continue;
539 }
540
John McCalldaa3d6b2009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000543 }
John McCall3d988d92009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
546 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
548 continue;
549 }
550
John McCalldaa3d6b2009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000553 }
John McCall84d87672009-12-10 09:41:52 +0000554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
555 // We can overload with these, which can show up when doing
556 // redeclaration checks for UsingDecls.
557 assert(Old.getLookupKind() == LookupUsingDeclName);
558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
559 // Optimistically assume that an unresolved using decl will
560 // overload; if it doesn't, we'll have to diagnose during
561 // template instantiation.
562 } else {
John McCall1f82f242009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000568 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 }
John McCall1f82f242009-11-18 22:49:29 +0000570
John McCalldaa3d6b2009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000572}
573
John McCalle9cccd82010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall1f82f242009-11-18 22:49:29 +0000576 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
577 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
578
579 // C++ [temp.fct]p2:
580 // A function template can be overloaded with other function templates
581 // and with normal (non-template) functions.
582 if ((OldTemplate == 0) != (NewTemplate == 0))
583 return true;
584
585 // Is the function New an overload of the function Old?
586 QualType OldQType = Context.getCanonicalType(Old->getType());
587 QualType NewQType = Context.getCanonicalType(New->getType());
588
589 // Compare the signatures (C++ 1.3.10) of the two functions to
590 // determine whether they are overloads. If we find any mismatch
591 // in the signature, they are overloads.
592
593 // If either of these functions is a K&R-style function (no
594 // prototype), then we consider them to have matching signatures.
595 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
596 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
597 return false;
598
599 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
600 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
601
602 // The signature of a function includes the types of its
603 // parameters (C++ 1.3.10), which includes the presence or absence
604 // of the ellipsis; see C++ DR 357).
605 if (OldQType != NewQType &&
606 (OldType->getNumArgs() != NewType->getNumArgs() ||
607 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000608 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000609 return true;
610
611 // C++ [temp.over.link]p4:
612 // The signature of a function template consists of its function
613 // signature, its return type and its template parameter list. The names
614 // of the template parameters are significant only for establishing the
615 // relationship between the template parameters and the rest of the
616 // signature.
617 //
618 // We check the return type and template parameter lists for function
619 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000620 //
621 // However, we don't consider either of these when deciding whether
622 // a member introduced by a shadow declaration is hidden.
623 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000624 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
625 OldTemplate->getTemplateParameters(),
626 false, TPL_TemplateMatch) ||
627 OldType->getResultType() != NewType->getResultType()))
628 return true;
629
630 // If the function is a class member, its signature includes the
631 // cv-qualifiers (if any) on the function itself.
632 //
633 // As part of this, also check whether one of the member functions
634 // is static, in which case they are not overloads (C++
635 // 13.1p2). While not part of the definition of the signature,
636 // this check is important to determine whether these functions
637 // can be overloaded.
638 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
639 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
640 if (OldMethod && NewMethod &&
641 !OldMethod->isStatic() && !NewMethod->isStatic() &&
642 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
643 return true;
644
645 // The signatures match; this is not an overload.
646 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000647}
648
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000649/// TryImplicitConversion - Attempt to perform an implicit conversion
650/// from the given expression (Expr) to the given type (ToType). This
651/// function returns an implicit conversion sequence that can be used
652/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653///
654/// void f(float f);
655/// void g(int i) { f(i); }
656///
657/// this routine would produce an implicit conversion sequence to
658/// describe the initialization of f from i, which will be a standard
659/// conversion sequence containing an lvalue-to-rvalue conversion (C++
660/// 4.1) followed by a floating-integral conversion (C++ 4.9).
661//
662/// Note that this routine only determines how the conversion can be
663/// performed; it does not actually perform the conversion. As such,
664/// it will not produce any diagnostics if no conversion is available,
665/// but will instead return an implicit conversion sequence of kind
666/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000667///
668/// If @p SuppressUserConversions, then user-defined conversions are
669/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000670/// If @p AllowExplicit, then explicit user-defined conversions are
671/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000672ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000673Sema::TryImplicitConversion(Expr* From, QualType ToType,
674 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000675 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000676 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000677 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000678 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000679 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000680 return ICS;
681 }
682
683 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000684 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000685 return ICS;
686 }
687
Douglas Gregor5ab11652010-04-17 22:01:05 +0000688 if (SuppressUserConversions) {
689 // C++ [over.ics.user]p4:
690 // A conversion of an expression of class type to the same class
691 // type is given Exact Match rank, and a conversion of an
692 // expression of class type to a base class of that type is
693 // given Conversion rank, in spite of the fact that a copy/move
694 // constructor (i.e., a user-defined conversion function) is
695 // called for those cases.
696 QualType FromType = From->getType();
697 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
698 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
699 IsDerivedFrom(FromType, ToType))) {
700 // We're not in the case above, so there is no conversion that
701 // we can perform.
702 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
703 return ICS;
704 }
705
706 ICS.setStandard();
707 ICS.Standard.setAsIdentityConversion();
708 ICS.Standard.setFromType(FromType);
709 ICS.Standard.setAllToTypes(ToType);
710
711 // We don't actually check at this point whether there is a valid
712 // copy/move constructor, since overloading just assumes that it
713 // exists. When we actually perform initialization, we'll find the
714 // appropriate constructor to copy the returned object, if needed.
715 ICS.Standard.CopyConstructor = 0;
716
717 // Determine whether this is considered a derived-to-base conversion.
718 if (!Context.hasSameUnqualifiedType(FromType, ToType))
719 ICS.Standard.Second = ICK_Derived_To_Base;
720
721 return ICS;
722 }
723
724 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000725 OverloadCandidateSet Conversions(From->getExprLoc());
726 OverloadingResult UserDefResult
727 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000728 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000729
730 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000731 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000732 // C++ [over.ics.user]p4:
733 // A conversion of an expression of class type to the same class
734 // type is given Exact Match rank, and a conversion of an
735 // expression of class type to a base class of that type is
736 // given Conversion rank, in spite of the fact that a copy
737 // constructor (i.e., a user-defined conversion function) is
738 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000739 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000740 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000741 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000742 = Context.getCanonicalType(From->getType().getUnqualifiedType());
743 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000744 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000745 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000746 // Turn this into a "standard" conversion sequence, so that it
747 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000748 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000749 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000750 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000751 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000752 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000753 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000754 ICS.Standard.Second = ICK_Derived_To_Base;
755 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000756 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000757
758 // C++ [over.best.ics]p4:
759 // However, when considering the argument of a user-defined
760 // conversion function that is a candidate by 13.3.1.3 when
761 // invoked for the copying of the temporary in the second step
762 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
763 // 13.3.1.6 in all cases, only standard conversion sequences and
764 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000765 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000766 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000767 }
John McCalle8c8cd22010-01-13 22:30:33 +0000768 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000769 ICS.setAmbiguous();
770 ICS.Ambiguous.setFromType(From->getType());
771 ICS.Ambiguous.setToType(ToType);
772 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
773 Cand != Conversions.end(); ++Cand)
774 if (Cand->Viable)
775 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000776 } else {
John McCall65eb8792010-02-25 01:37:24 +0000777 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000778 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000779
780 return ICS;
781}
782
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000783/// PerformImplicitConversion - Perform an implicit conversion of the
784/// expression From to the type ToType. Returns true if there was an
785/// error, false otherwise. The expression From is replaced with the
786/// converted expression. Flavor is the kind of conversion we're
787/// performing, used in the error message. If @p AllowExplicit,
788/// explicit user-defined conversions are permitted.
789bool
790Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
791 AssignmentAction Action, bool AllowExplicit) {
792 ImplicitConversionSequence ICS;
793 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
794}
795
796bool
797Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
798 AssignmentAction Action, bool AllowExplicit,
799 ImplicitConversionSequence& ICS) {
800 ICS = TryImplicitConversion(From, ToType,
801 /*SuppressUserConversions=*/false,
802 AllowExplicit,
803 /*InOverloadResolution=*/false);
804 return PerformImplicitConversion(From, ToType, ICS, Action);
805}
806
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000807/// \brief Determine whether the conversion from FromType to ToType is a valid
808/// conversion that strips "noreturn" off the nested function type.
809static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
810 QualType ToType, QualType &ResultTy) {
811 if (Context.hasSameUnqualifiedType(FromType, ToType))
812 return false;
813
814 // Strip the noreturn off the type we're converting from; noreturn can
815 // safely be removed.
816 FromType = Context.getNoReturnType(FromType, false);
817 if (!Context.hasSameUnqualifiedType(FromType, ToType))
818 return false;
819
820 ResultTy = FromType;
821 return true;
822}
Douglas Gregor46188682010-05-18 22:42:18 +0000823
824/// \brief Determine whether the conversion from FromType to ToType is a valid
825/// vector conversion.
826///
827/// \param ICK Will be set to the vector conversion kind, if this is a vector
828/// conversion.
829static bool IsVectorConversion(ASTContext &Context, QualType FromType,
830 QualType ToType, ImplicitConversionKind &ICK) {
831 // We need at least one of these types to be a vector type to have a vector
832 // conversion.
833 if (!ToType->isVectorType() && !FromType->isVectorType())
834 return false;
835
836 // Identical types require no conversions.
837 if (Context.hasSameUnqualifiedType(FromType, ToType))
838 return false;
839
840 // There are no conversions between extended vector types, only identity.
841 if (ToType->isExtVectorType()) {
842 // There are no conversions between extended vector types other than the
843 // identity conversion.
844 if (FromType->isExtVectorType())
845 return false;
846
847 // Vector splat from any arithmetic type to a vector.
848 if (!FromType->isVectorType() && FromType->isArithmeticType()) {
849 ICK = ICK_Vector_Splat;
850 return true;
851 }
852 }
853
854 // If lax vector conversions are permitted and the vector types are of the
855 // same size, we can perform the conversion.
856 if (Context.getLangOptions().LaxVectorConversions &&
857 FromType->isVectorType() && ToType->isVectorType() &&
858 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
859 ICK = ICK_Vector_Conversion;
860 return true;
861 }
862
863 return false;
864}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000865
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000866/// IsStandardConversion - Determines whether there is a standard
867/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
868/// expression From to the type ToType. Standard conversion sequences
869/// only consider non-class types; for conversions that involve class
870/// types, use TryImplicitConversion. If a conversion exists, SCS will
871/// contain the standard conversion sequence required to perform this
872/// conversion and this routine will return true. Otherwise, this
873/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000874bool
875Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000876 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000877 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878 QualType FromType = From->getType();
879
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000880 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000881 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000882 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000883 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000884 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000885 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000887 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000888 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000889 if (FromType->isRecordType() || ToType->isRecordType()) {
890 if (getLangOptions().CPlusPlus)
891 return false;
892
Mike Stump11289f42009-09-09 15:08:12 +0000893 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000894 }
895
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896 // The first conversion can be an lvalue-to-rvalue conversion,
897 // array-to-pointer conversion, or function-to-pointer conversion
898 // (C++ 4p1).
899
Douglas Gregor980fb162010-04-29 18:24:40 +0000900 if (FromType == Context.OverloadTy) {
901 DeclAccessPair AccessPair;
902 if (FunctionDecl *Fn
903 = ResolveAddressOfOverloadedFunction(From, ToType, false,
904 AccessPair)) {
905 // We were able to resolve the address of the overloaded function,
906 // so we can convert to the type of that function.
907 FromType = Fn->getType();
908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
909 if (!Method->isStatic()) {
910 Type *ClassType
911 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
912 FromType = Context.getMemberPointerType(FromType, ClassType);
913 }
914 }
915
916 // If the "from" expression takes the address of the overloaded
917 // function, update the type of the resulting expression accordingly.
918 if (FromType->getAs<FunctionType>())
919 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
920 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
921 FromType = Context.getPointerType(FromType);
922
923 // Check that we've computed the proper type after overload resolution.
924 assert(Context.hasSameType(FromType,
925 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
926 } else {
927 return false;
928 }
929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000931 // An lvalue (3.10) of a non-function, non-array type T can be
932 // converted to an rvalue.
933 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000934 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000935 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000936 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000937 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938
939 // If T is a non-class type, the type of the rvalue is the
940 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000941 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
942 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000943 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000944 } else if (FromType->isArrayType()) {
945 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000946 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947
948 // An lvalue or rvalue of type "array of N T" or "array of unknown
949 // bound of T" can be converted to an rvalue of type "pointer to
950 // T" (C++ 4.2p1).
951 FromType = Context.getArrayDecayedType(FromType);
952
953 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
954 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000955 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956
957 // For the purpose of ranking in overload resolution
958 // (13.3.3.1.1), this conversion is considered an
959 // array-to-pointer conversion followed by a qualification
960 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000961 SCS.Second = ICK_Identity;
962 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000963 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000964 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000965 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000966 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
967 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000968 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969
970 // An lvalue of function type T can be converted to an rvalue of
971 // type "pointer to T." The result is a pointer to the
972 // function. (C++ 4.3p1).
973 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000974 } else {
975 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000976 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000978 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000979
980 // The second conversion can be an integral promotion, floating
981 // point promotion, integral conversion, floating point conversion,
982 // floating-integral conversion, pointer conversion,
983 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 // For overloading in C, this can also be a "compatible-type"
985 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000986 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000987 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000988 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000989 // The unqualified versions of the types are the same: there's no
990 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000991 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000992 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000993 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000994 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000995 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000996 } else if (IsFloatingPointPromotion(FromType, ToType)) {
997 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000998 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000999 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001000 } else if (IsComplexPromotion(FromType, ToType)) {
1001 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001002 SCS.Second = ICK_Complex_Promotion;
1003 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001004 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001005 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001006 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001007 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001009 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1010 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Conversion;
1012 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001013 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1014 (ToType->isComplexType() && FromType->isArithmeticType())) {
1015 // Complex-real conversions (C99 6.3.1.7)
1016 SCS.Second = ICK_Complex_Real;
1017 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001018 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001019 // Floating point conversions (C++ 4.8).
1020 SCS.Second = ICK_Floating_Conversion;
1021 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001022 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001023 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001024 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001025 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001026 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001027 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +00001029 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1030 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001031 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001032 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001033 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +00001034 } else if (IsMemberPointerConversion(From, FromType, ToType,
1035 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001036 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001037 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001038 } else if (ToType->isBooleanType() &&
1039 (FromType->isArithmeticType() ||
1040 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001041 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001042 FromType->isBlockPointerType() ||
1043 FromType->isMemberPointerType() ||
Douglas Gregordb48cf32010-06-22 16:52:27 +00001044 FromType->isNullPtrType()) &&
1045 /*FIXME*/!FromType->isVectorType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001046 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001047 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001048 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001049 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1050 SCS.Second = SecondICK;
1051 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001052 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001053 Context.typesAreCompatible(ToType, FromType)) {
1054 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001055 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001056 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001057 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1058 // Treat a conversion that strips "noreturn" as an identity conversion.
1059 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001060 } else {
1061 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001062 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001063 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001064 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001066 QualType CanonFrom;
1067 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001069 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001070 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001072 CanonFrom = Context.getCanonicalType(FromType);
1073 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001074 } else {
1075 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001076 SCS.Third = ICK_Identity;
1077
Mike Stump11289f42009-09-09 15:08:12 +00001078 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001079 // [...] Any difference in top-level cv-qualification is
1080 // subsumed by the initialization itself and does not constitute
1081 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001082 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001083 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001084 if (CanonFrom.getLocalUnqualifiedType()
1085 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001086 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1087 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001088 FromType = ToType;
1089 CanonFrom = CanonTo;
1090 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001091 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001092 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001093
1094 // If we have not converted the argument type to the parameter type,
1095 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001096 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001097 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001098
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100}
1101
1102/// IsIntegralPromotion - Determines whether the conversion from the
1103/// expression From (whose potentially-adjusted type is FromType) to
1104/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1105/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001106bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001107 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001108 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001109 if (!To) {
1110 return false;
1111 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001112
1113 // An rvalue of type char, signed char, unsigned char, short int, or
1114 // unsigned short int can be converted to an rvalue of type int if
1115 // int can represent all the values of the source type; otherwise,
1116 // the source rvalue can be converted to an rvalue of type unsigned
1117 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001118 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1119 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001120 if (// We can promote any signed, promotable integer type to an int
1121 (FromType->isSignedIntegerType() ||
1122 // We can promote any unsigned integer type whose size is
1123 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001124 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001125 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001127 }
1128
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 return To->getKind() == BuiltinType::UInt;
1130 }
1131
1132 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1133 // can be converted to an rvalue of the first of the following types
1134 // that can represent all the values of its underlying type: int,
1135 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001136
1137 // We pre-calculate the promotion type for enum types.
1138 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1139 if (ToType->isIntegerType())
1140 return Context.hasSameUnqualifiedType(ToType,
1141 FromEnumType->getDecl()->getPromotionType());
1142
1143 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001144 // Determine whether the type we're converting from is signed or
1145 // unsigned.
1146 bool FromIsSigned;
1147 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001148
1149 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1150 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001151
1152 // The types we'll try to promote to, in the appropriate
1153 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001154 QualType PromoteTypes[6] = {
1155 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001156 Context.LongTy, Context.UnsignedLongTy ,
1157 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001159 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001160 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1161 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001162 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1164 // We found the type that we can promote to. If this is the
1165 // type we wanted, we have a promotion. Otherwise, no
1166 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001167 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 }
1169 }
1170 }
1171
1172 // An rvalue for an integral bit-field (9.6) can be converted to an
1173 // rvalue of type int if int can represent all the values of the
1174 // bit-field; otherwise, it can be converted to unsigned int if
1175 // unsigned int can represent all the values of the bit-field. If
1176 // the bit-field is larger yet, no integral promotion applies to
1177 // it. If the bit-field has an enumerated type, it is treated as any
1178 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001179 // FIXME: We should delay checking of bit-fields until we actually perform the
1180 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001181 using llvm::APSInt;
1182 if (From)
1183 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001184 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001185 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001186 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1187 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1188 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001189
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001190 // Are we promoting to an int from a bitfield that fits in an int?
1191 if (BitWidth < ToSize ||
1192 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1193 return To->getKind() == BuiltinType::Int;
1194 }
Mike Stump11289f42009-09-09 15:08:12 +00001195
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001196 // Are we promoting to an unsigned int from an unsigned bitfield
1197 // that fits into an unsigned int?
1198 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1199 return To->getKind() == BuiltinType::UInt;
1200 }
Mike Stump11289f42009-09-09 15:08:12 +00001201
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001202 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001203 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001204 }
Mike Stump11289f42009-09-09 15:08:12 +00001205
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001206 // An rvalue of type bool can be converted to an rvalue of type int,
1207 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001208 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001209 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001210 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001211
1212 return false;
1213}
1214
1215/// IsFloatingPointPromotion - Determines whether the conversion from
1216/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1217/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001218bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001219 /// An rvalue of type float can be converted to an rvalue of type
1220 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001221 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1222 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001223 if (FromBuiltin->getKind() == BuiltinType::Float &&
1224 ToBuiltin->getKind() == BuiltinType::Double)
1225 return true;
1226
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001227 // C99 6.3.1.5p1:
1228 // When a float is promoted to double or long double, or a
1229 // double is promoted to long double [...].
1230 if (!getLangOptions().CPlusPlus &&
1231 (FromBuiltin->getKind() == BuiltinType::Float ||
1232 FromBuiltin->getKind() == BuiltinType::Double) &&
1233 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1234 return true;
1235 }
1236
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001237 return false;
1238}
1239
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001240/// \brief Determine if a conversion is a complex promotion.
1241///
1242/// A complex promotion is defined as a complex -> complex conversion
1243/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001244/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001245bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001246 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001247 if (!FromComplex)
1248 return false;
1249
John McCall9dd450b2009-09-21 23:43:11 +00001250 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001251 if (!ToComplex)
1252 return false;
1253
1254 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001255 ToComplex->getElementType()) ||
1256 IsIntegralPromotion(0, FromComplex->getElementType(),
1257 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001258}
1259
Douglas Gregor237f96c2008-11-26 23:31:11 +00001260/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1261/// the pointer type FromPtr to a pointer to type ToPointee, with the
1262/// same type qualifiers as FromPtr has on its pointee type. ToType,
1263/// if non-empty, will be a pointer to ToType that may or may not have
1264/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001265static QualType
1266BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001267 QualType ToPointee, QualType ToType,
1268 ASTContext &Context) {
1269 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1270 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001271 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001272
1273 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001274 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001275 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001276 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001277 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001278
1279 // Build a pointer to ToPointee. It has the right qualifiers
1280 // already.
1281 return Context.getPointerType(ToPointee);
1282 }
1283
1284 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001285 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001286 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1287 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001288}
1289
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001290/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1291/// the FromType, which is an objective-c pointer, to ToType, which may or may
1292/// not have the right set of qualifiers.
1293static QualType
1294BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1295 QualType ToType,
1296 ASTContext &Context) {
1297 QualType CanonFromType = Context.getCanonicalType(FromType);
1298 QualType CanonToType = Context.getCanonicalType(ToType);
1299 Qualifiers Quals = CanonFromType.getQualifiers();
1300
1301 // Exact qualifier match -> return the pointer type we're converting to.
1302 if (CanonToType.getLocalQualifiers() == Quals)
1303 return ToType;
1304
1305 // Just build a canonical type that has the right qualifiers.
1306 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1307}
1308
Mike Stump11289f42009-09-09 15:08:12 +00001309static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001310 bool InOverloadResolution,
1311 ASTContext &Context) {
1312 // Handle value-dependent integral null pointer constants correctly.
1313 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1314 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001315 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001316 return !InOverloadResolution;
1317
Douglas Gregor56751b52009-09-25 04:25:58 +00001318 return Expr->isNullPointerConstant(Context,
1319 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1320 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001321}
Mike Stump11289f42009-09-09 15:08:12 +00001322
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001323/// IsPointerConversion - Determines whether the conversion of the
1324/// expression From, which has the (possibly adjusted) type FromType,
1325/// can be converted to the type ToType via a pointer conversion (C++
1326/// 4.10). If so, returns true and places the converted type (that
1327/// might differ from ToType in its cv-qualifiers at some level) into
1328/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001329///
Douglas Gregora29dc052008-11-27 01:19:21 +00001330/// This routine also supports conversions to and from block pointers
1331/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1332/// pointers to interfaces. FIXME: Once we've determined the
1333/// appropriate overloading rules for Objective-C, we may want to
1334/// split the Objective-C checks into a different routine; however,
1335/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001336/// conversions, so for now they live here. IncompatibleObjC will be
1337/// set if the conversion is an allowed Objective-C conversion that
1338/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001339bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001340 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001341 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001342 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001343 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001344 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1345 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001346
Mike Stump11289f42009-09-09 15:08:12 +00001347 // Conversion from a null pointer constant to any Objective-C pointer type.
1348 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001349 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001350 ConvertedType = ToType;
1351 return true;
1352 }
1353
Douglas Gregor231d1c62008-11-27 00:15:41 +00001354 // Blocks: Block pointers can be converted to void*.
1355 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001356 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001357 ConvertedType = ToType;
1358 return true;
1359 }
1360 // Blocks: A null pointer constant can be converted to a block
1361 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001362 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001364 ConvertedType = ToType;
1365 return true;
1366 }
1367
Sebastian Redl576fd422009-05-10 18:38:11 +00001368 // If the left-hand-side is nullptr_t, the right side can be a null
1369 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001370 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001372 ConvertedType = ToType;
1373 return true;
1374 }
1375
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001376 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001377 if (!ToTypePtr)
1378 return false;
1379
1380 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001381 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001382 ConvertedType = ToType;
1383 return true;
1384 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001385
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001386 // Beyond this point, both types need to be pointers
1387 // , including objective-c pointers.
1388 QualType ToPointeeType = ToTypePtr->getPointeeType();
1389 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1390 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1391 ToType, Context);
1392 return true;
1393
1394 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001395 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001396 if (!FromTypePtr)
1397 return false;
1398
1399 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001400
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001401 // An rvalue of type "pointer to cv T," where T is an object type,
1402 // can be converted to an rvalue of type "pointer to cv void" (C++
1403 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001404 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001405 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001406 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001407 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001408 return true;
1409 }
1410
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001411 // When we're overloading in C, we allow a special kind of pointer
1412 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001413 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001414 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001415 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001416 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001417 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001418 return true;
1419 }
1420
Douglas Gregor5c407d92008-10-23 00:40:37 +00001421 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001422 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001423 // An rvalue of type "pointer to cv D," where D is a class type,
1424 // can be converted to an rvalue of type "pointer to cv B," where
1425 // B is a base class (clause 10) of D. If B is an inaccessible
1426 // (clause 11) or ambiguous (10.2) base class of D, a program that
1427 // necessitates this conversion is ill-formed. The result of the
1428 // conversion is a pointer to the base class sub-object of the
1429 // derived class object. The null pointer value is converted to
1430 // the null pointer value of the destination type.
1431 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001432 // Note that we do not check for ambiguity or inaccessibility
1433 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001434 if (getLangOptions().CPlusPlus &&
1435 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001436 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001437 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001438 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001439 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001440 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001441 ToType, Context);
1442 return true;
1443 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001444
Douglas Gregora119f102008-12-19 19:13:09 +00001445 return false;
1446}
1447
1448/// isObjCPointerConversion - Determines whether this is an
1449/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1450/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001451bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001452 QualType& ConvertedType,
1453 bool &IncompatibleObjC) {
1454 if (!getLangOptions().ObjC1)
1455 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001456
Steve Naroff7cae42b2009-07-10 23:34:53 +00001457 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001458 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001459 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001460 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001461
Steve Naroff7cae42b2009-07-10 23:34:53 +00001462 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001463 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001464 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001465 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001466 ConvertedType = ToType;
1467 return true;
1468 }
1469 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001470 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001471 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001472 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001473 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001474 ConvertedType = ToType;
1475 return true;
1476 }
1477 // Objective C++: We're able to convert from a pointer to an
1478 // interface to a pointer to a different interface.
1479 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001480 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1481 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1482 if (getLangOptions().CPlusPlus && LHS && RHS &&
1483 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1484 FromObjCPtr->getPointeeType()))
1485 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001486 ConvertedType = ToType;
1487 return true;
1488 }
1489
1490 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1491 // Okay: this is some kind of implicit downcast of Objective-C
1492 // interfaces, which is permitted. However, we're going to
1493 // complain about it.
1494 IncompatibleObjC = true;
1495 ConvertedType = FromType;
1496 return true;
1497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001499 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001500 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001501 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001502 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001503 else if (const BlockPointerType *ToBlockPtr =
1504 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001505 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001506 // to a block pointer type.
1507 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1508 ConvertedType = ToType;
1509 return true;
1510 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001511 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001512 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001513 else if (FromType->getAs<BlockPointerType>() &&
1514 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1515 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001516 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001517 ConvertedType = ToType;
1518 return true;
1519 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001520 else
Douglas Gregora119f102008-12-19 19:13:09 +00001521 return false;
1522
Douglas Gregor033f56d2008-12-23 00:53:59 +00001523 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001524 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001525 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001526 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001527 FromPointeeType = FromBlockPtr->getPointeeType();
1528 else
Douglas Gregora119f102008-12-19 19:13:09 +00001529 return false;
1530
Douglas Gregora119f102008-12-19 19:13:09 +00001531 // If we have pointers to pointers, recursively check whether this
1532 // is an Objective-C conversion.
1533 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1534 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1535 IncompatibleObjC)) {
1536 // We always complain about this conversion.
1537 IncompatibleObjC = true;
1538 ConvertedType = ToType;
1539 return true;
1540 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001541 // Allow conversion of pointee being objective-c pointer to another one;
1542 // as in I* to id.
1543 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1544 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1545 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1546 IncompatibleObjC)) {
1547 ConvertedType = ToType;
1548 return true;
1549 }
1550
Douglas Gregor033f56d2008-12-23 00:53:59 +00001551 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001552 // differences in the argument and result types are in Objective-C
1553 // pointer conversions. If so, we permit the conversion (but
1554 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001555 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001556 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001557 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001558 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001559 if (FromFunctionType && ToFunctionType) {
1560 // If the function types are exactly the same, this isn't an
1561 // Objective-C pointer conversion.
1562 if (Context.getCanonicalType(FromPointeeType)
1563 == Context.getCanonicalType(ToPointeeType))
1564 return false;
1565
1566 // Perform the quick checks that will tell us whether these
1567 // function types are obviously different.
1568 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1569 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1570 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1571 return false;
1572
1573 bool HasObjCConversion = false;
1574 if (Context.getCanonicalType(FromFunctionType->getResultType())
1575 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1576 // Okay, the types match exactly. Nothing to do.
1577 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1578 ToFunctionType->getResultType(),
1579 ConvertedType, IncompatibleObjC)) {
1580 // Okay, we have an Objective-C pointer conversion.
1581 HasObjCConversion = true;
1582 } else {
1583 // Function types are too different. Abort.
1584 return false;
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
Douglas Gregora119f102008-12-19 19:13:09 +00001587 // Check argument types.
1588 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1589 ArgIdx != NumArgs; ++ArgIdx) {
1590 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1591 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1592 if (Context.getCanonicalType(FromArgType)
1593 == Context.getCanonicalType(ToArgType)) {
1594 // Okay, the types match exactly. Nothing to do.
1595 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1596 ConvertedType, IncompatibleObjC)) {
1597 // Okay, we have an Objective-C pointer conversion.
1598 HasObjCConversion = true;
1599 } else {
1600 // Argument types are too different. Abort.
1601 return false;
1602 }
1603 }
1604
1605 if (HasObjCConversion) {
1606 // We had an Objective-C conversion. Allow this pointer
1607 // conversion, but complain about it.
1608 ConvertedType = ToType;
1609 IncompatibleObjC = true;
1610 return true;
1611 }
1612 }
1613
Sebastian Redl72b597d2009-01-25 19:43:20 +00001614 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001616
1617/// FunctionArgTypesAreEqual - This routine checks two function proto types
1618/// for equlity of their argument types. Caller has already checked that
1619/// they have same number of arguments. This routine assumes that Objective-C
1620/// pointer types which only differ in their protocol qualifiers are equal.
1621bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1622 FunctionProtoType* NewType){
1623 if (!getLangOptions().ObjC1)
1624 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1625 NewType->arg_type_begin());
1626
1627 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1628 N = NewType->arg_type_begin(),
1629 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1630 QualType ToType = (*O);
1631 QualType FromType = (*N);
1632 if (ToType != FromType) {
1633 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1634 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001635 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1636 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1637 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1638 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001639 continue;
1640 }
John McCall8b07ec22010-05-15 11:32:37 +00001641 else if (const ObjCObjectPointerType *PTTo =
1642 ToType->getAs<ObjCObjectPointerType>()) {
1643 if (const ObjCObjectPointerType *PTFr =
1644 FromType->getAs<ObjCObjectPointerType>())
1645 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1646 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001647 }
1648 return false;
1649 }
1650 }
1651 return true;
1652}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001653
Douglas Gregor39c16d42008-10-24 04:54:22 +00001654/// CheckPointerConversion - Check the pointer conversion from the
1655/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001656/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001657/// conversions for which IsPointerConversion has already returned
1658/// true. It returns true and produces a diagnostic if there was an
1659/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001660bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001661 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001662 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001663 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001664 QualType FromType = From->getType();
1665
Douglas Gregor4038cf42010-06-08 17:35:15 +00001666 if (CXXBoolLiteralExpr* LitBool
1667 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1668 if (LitBool->getValue() == false)
1669 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1670 << ToType;
1671
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001672 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1673 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001674 QualType FromPointeeType = FromPtrType->getPointeeType(),
1675 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001676
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001677 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1678 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001679 // We must have a derived-to-base conversion. Check an
1680 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001681 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1682 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001683 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001684 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001685 return true;
1686
1687 // The conversion was successful.
1688 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001689 }
1690 }
Mike Stump11289f42009-09-09 15:08:12 +00001691 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001692 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001693 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001694 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001695 // Objective-C++ conversions are always okay.
1696 // FIXME: We should have a different class of conversions for the
1697 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001698 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001699 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001700
Steve Naroff7cae42b2009-07-10 23:34:53 +00001701 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001702 return false;
1703}
1704
Sebastian Redl72b597d2009-01-25 19:43:20 +00001705/// IsMemberPointerConversion - Determines whether the conversion of the
1706/// expression From, which has the (possibly adjusted) type FromType, can be
1707/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1708/// If so, returns true and places the converted type (that might differ from
1709/// ToType in its cv-qualifiers at some level) into ConvertedType.
1710bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001711 QualType ToType,
1712 bool InOverloadResolution,
1713 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001714 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001715 if (!ToTypePtr)
1716 return false;
1717
1718 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001719 if (From->isNullPointerConstant(Context,
1720 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1721 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001722 ConvertedType = ToType;
1723 return true;
1724 }
1725
1726 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001727 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001728 if (!FromTypePtr)
1729 return false;
1730
1731 // A pointer to member of B can be converted to a pointer to member of D,
1732 // where D is derived from B (C++ 4.11p2).
1733 QualType FromClass(FromTypePtr->getClass(), 0);
1734 QualType ToClass(ToTypePtr->getClass(), 0);
1735 // FIXME: What happens when these are dependent? Is this function even called?
1736
1737 if (IsDerivedFrom(ToClass, FromClass)) {
1738 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1739 ToClass.getTypePtr());
1740 return true;
1741 }
1742
1743 return false;
1744}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001745
Sebastian Redl72b597d2009-01-25 19:43:20 +00001746/// CheckMemberPointerConversion - Check the member pointer conversion from the
1747/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001748/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001749/// for which IsMemberPointerConversion has already returned true. It returns
1750/// true and produces a diagnostic if there was an error, or returns false
1751/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001752bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001753 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001754 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001755 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001756 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001757 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001758 if (!FromPtrType) {
1759 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001760 assert(From->isNullPointerConstant(Context,
1761 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001762 "Expr must be null pointer constant!");
1763 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001764 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001765 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001766
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001767 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001768 assert(ToPtrType && "No member pointer cast has a target type "
1769 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001770
Sebastian Redled8f2002009-01-28 18:33:18 +00001771 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1772 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001773
Sebastian Redled8f2002009-01-28 18:33:18 +00001774 // FIXME: What about dependent types?
1775 assert(FromClass->isRecordType() && "Pointer into non-class.");
1776 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001777
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001778 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001779 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001780 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1781 assert(DerivationOkay &&
1782 "Should not have been called if derivation isn't OK.");
1783 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001784
Sebastian Redled8f2002009-01-28 18:33:18 +00001785 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1786 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001787 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1788 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1789 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1790 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001791 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001792
Douglas Gregor89ee6822009-02-28 01:32:25 +00001793 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001794 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1795 << FromClass << ToClass << QualType(VBase, 0)
1796 << From->getSourceRange();
1797 return true;
1798 }
1799
John McCall5b0829a2010-02-10 09:31:12 +00001800 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001801 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1802 Paths.front(),
1803 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001804
Anders Carlssond7923c62009-08-22 23:33:40 +00001805 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001806 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001807 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001808 return false;
1809}
1810
Douglas Gregor9a657932008-10-21 23:43:52 +00001811/// IsQualificationConversion - Determines whether the conversion from
1812/// an rvalue of type FromType to ToType is a qualification conversion
1813/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001814bool
1815Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001816 FromType = Context.getCanonicalType(FromType);
1817 ToType = Context.getCanonicalType(ToType);
1818
1819 // If FromType and ToType are the same type, this is not a
1820 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001821 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001822 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001823
Douglas Gregor9a657932008-10-21 23:43:52 +00001824 // (C++ 4.4p4):
1825 // A conversion can add cv-qualifiers at levels other than the first
1826 // in multi-level pointers, subject to the following rules: [...]
1827 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001828 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001829 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001830 // Within each iteration of the loop, we check the qualifiers to
1831 // determine if this still looks like a qualification
1832 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001833 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001834 // until there are no more pointers or pointers-to-members left to
1835 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001836 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001837
1838 // -- for every j > 0, if const is in cv 1,j then const is in cv
1839 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001840 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001842
Douglas Gregor9a657932008-10-21 23:43:52 +00001843 // -- if the cv 1,j and cv 2,j are different, then const is in
1844 // every cv for 0 < k < j.
1845 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001846 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001847 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001848
Douglas Gregor9a657932008-10-21 23:43:52 +00001849 // Keep track of whether all prior cv-qualifiers in the "to" type
1850 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001851 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001852 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001853 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001854
1855 // We are left with FromType and ToType being the pointee types
1856 // after unwrapping the original FromType and ToType the same number
1857 // of types. If we unwrapped any pointers, and if FromType and
1858 // ToType have the same unqualified type (since we checked
1859 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001860 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001861}
1862
Douglas Gregor576e98c2009-01-30 23:27:23 +00001863/// Determines whether there is a user-defined conversion sequence
1864/// (C++ [over.ics.user]) that converts expression From to the type
1865/// ToType. If such a conversion exists, User will contain the
1866/// user-defined conversion sequence that performs such a conversion
1867/// and this routine will return true. Otherwise, this routine returns
1868/// false and User is unspecified.
1869///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001870/// \param AllowExplicit true if the conversion should consider C++0x
1871/// "explicit" conversion functions as well as non-explicit conversion
1872/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001873OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1874 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001875 OverloadCandidateSet& CandidateSet,
1876 bool AllowExplicit) {
1877 // Whether we will only visit constructors.
1878 bool ConstructorsOnly = false;
1879
1880 // If the type we are conversion to is a class type, enumerate its
1881 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001882 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001883 // C++ [over.match.ctor]p1:
1884 // When objects of class type are direct-initialized (8.5), or
1885 // copy-initialized from an expression of the same or a
1886 // derived class type (8.5), overload resolution selects the
1887 // constructor. [...] For copy-initialization, the candidate
1888 // functions are all the converting constructors (12.3.1) of
1889 // that class. The argument list is the expression-list within
1890 // the parentheses of the initializer.
1891 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1892 (From->getType()->getAs<RecordType>() &&
1893 IsDerivedFrom(From->getType(), ToType)))
1894 ConstructorsOnly = true;
1895
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001896 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1897 // We're not going to find any constructors.
1898 } else if (CXXRecordDecl *ToRecordDecl
1899 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001900 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001901 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001902 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001903 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001904 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001905 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001906 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001907 NamedDecl *D = *Con;
1908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1909
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001910 // Find the constructor (which may be a template).
1911 CXXConstructorDecl *Constructor = 0;
1912 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001913 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001914 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001915 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1917 else
John McCalla0296f72010-03-19 07:35:19 +00001918 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001919
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001920 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001921 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001922 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001923 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001924 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001925 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001926 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001927 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001928 // Allow one user-defined conversion when user specifies a
1929 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001930 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001931 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001932 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001933 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001934 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001935 }
1936 }
1937
Douglas Gregor5ab11652010-04-17 22:01:05 +00001938 // Enumerate conversion functions, if we're allowed to.
1939 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001940 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001941 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001942 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001943 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001944 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001945 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001946 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1947 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001948 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001949 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001950 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001951 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001952 DeclAccessPair FoundDecl = I.getPair();
1953 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001954 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1955 if (isa<UsingShadowDecl>(D))
1956 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1957
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001958 CXXConversionDecl *Conv;
1959 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001960 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1961 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001962 else
John McCallda4458e2010-03-31 01:36:47 +00001963 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001964
1965 if (AllowExplicit || !Conv->isExplicit()) {
1966 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001967 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001968 ActingContext, From, ToType,
1969 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001970 else
John McCalla0296f72010-03-19 07:35:19 +00001971 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001972 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001973 }
1974 }
1975 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001976 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001977
1978 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001979 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001980 case OR_Success:
1981 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001982 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001983 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1984 // C++ [over.ics.user]p1:
1985 // If the user-defined conversion is specified by a
1986 // constructor (12.3.1), the initial standard conversion
1987 // sequence converts the source type to the type required by
1988 // the argument of the constructor.
1989 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001990 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001991 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001992 User.EllipsisConversion = true;
1993 else {
1994 User.Before = Best->Conversions[0].Standard;
1995 User.EllipsisConversion = false;
1996 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001997 User.ConversionFunction = Constructor;
1998 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001999 User.After.setFromType(
2000 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002001 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002002 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002003 } else if (CXXConversionDecl *Conversion
2004 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2005 // C++ [over.ics.user]p1:
2006 //
2007 // [...] If the user-defined conversion is specified by a
2008 // conversion function (12.3.2), the initial standard
2009 // conversion sequence converts the source type to the
2010 // implicit object parameter of the conversion function.
2011 User.Before = Best->Conversions[0].Standard;
2012 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002013 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002014
2015 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002016 // The second standard conversion sequence converts the
2017 // result of the user-defined conversion to the target type
2018 // for the sequence. Since an implicit conversion sequence
2019 // is an initialization, the special rules for
2020 // initialization by user-defined conversion apply when
2021 // selecting the best user-defined conversion for a
2022 // user-defined conversion sequence (see 13.3.3 and
2023 // 13.3.3.1).
2024 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002025 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002026 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002027 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002028 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002031 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002032 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002033 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002034 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002035 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002036
2037 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002038 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002039 }
2040
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002041 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002042}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002043
2044bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002045Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002046 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002047 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002048 OverloadingResult OvResult =
2049 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002050 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002051 if (OvResult == OR_Ambiguous)
2052 Diag(From->getSourceRange().getBegin(),
2053 diag::err_typecheck_ambiguous_condition)
2054 << From->getType() << ToType << From->getSourceRange();
2055 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2056 Diag(From->getSourceRange().getBegin(),
2057 diag::err_typecheck_nonviable_condition)
2058 << From->getType() << ToType << From->getSourceRange();
2059 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002060 return false;
John McCallad907772010-01-12 07:18:19 +00002061 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002062 return true;
2063}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002064
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002065/// CompareImplicitConversionSequences - Compare two implicit
2066/// conversion sequences to determine whether one is better than the
2067/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002068ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2070 const ImplicitConversionSequence& ICS2)
2071{
2072 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2073 // conversion sequences (as defined in 13.3.3.1)
2074 // -- a standard conversion sequence (13.3.3.1.1) is a better
2075 // conversion sequence than a user-defined conversion sequence or
2076 // an ellipsis conversion sequence, and
2077 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2078 // conversion sequence than an ellipsis conversion sequence
2079 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002080 //
John McCall0d1da222010-01-12 00:44:57 +00002081 // C++0x [over.best.ics]p10:
2082 // For the purpose of ranking implicit conversion sequences as
2083 // described in 13.3.3.2, the ambiguous conversion sequence is
2084 // treated as a user-defined sequence that is indistinguishable
2085 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002086 if (ICS1.getKindRank() < ICS2.getKindRank())
2087 return ImplicitConversionSequence::Better;
2088 else if (ICS2.getKindRank() < ICS1.getKindRank())
2089 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002090
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002091 // The following checks require both conversion sequences to be of
2092 // the same kind.
2093 if (ICS1.getKind() != ICS2.getKind())
2094 return ImplicitConversionSequence::Indistinguishable;
2095
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002096 // Two implicit conversion sequences of the same form are
2097 // indistinguishable conversion sequences unless one of the
2098 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002099 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002100 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002101 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002102 // User-defined conversion sequence U1 is a better conversion
2103 // sequence than another user-defined conversion sequence U2 if
2104 // they contain the same user-defined conversion function or
2105 // constructor and if the second standard conversion sequence of
2106 // U1 is better than the second standard conversion sequence of
2107 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002108 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002109 ICS2.UserDefined.ConversionFunction)
2110 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2111 ICS2.UserDefined.After);
2112 }
2113
2114 return ImplicitConversionSequence::Indistinguishable;
2115}
2116
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002117static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2118 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2119 Qualifiers Quals;
2120 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2121 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2122 }
2123
2124 return Context.hasSameUnqualifiedType(T1, T2);
2125}
2126
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002127// Per 13.3.3.2p3, compare the given standard conversion sequences to
2128// determine if one is a proper subset of the other.
2129static ImplicitConversionSequence::CompareKind
2130compareStandardConversionSubsets(ASTContext &Context,
2131 const StandardConversionSequence& SCS1,
2132 const StandardConversionSequence& SCS2) {
2133 ImplicitConversionSequence::CompareKind Result
2134 = ImplicitConversionSequence::Indistinguishable;
2135
Douglas Gregore87561a2010-05-23 22:10:15 +00002136 // the identity conversion sequence is considered to be a subsequence of
2137 // any non-identity conversion sequence
2138 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2139 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2140 return ImplicitConversionSequence::Better;
2141 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2142 return ImplicitConversionSequence::Worse;
2143 }
2144
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002145 if (SCS1.Second != SCS2.Second) {
2146 if (SCS1.Second == ICK_Identity)
2147 Result = ImplicitConversionSequence::Better;
2148 else if (SCS2.Second == ICK_Identity)
2149 Result = ImplicitConversionSequence::Worse;
2150 else
2151 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002152 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002153 return ImplicitConversionSequence::Indistinguishable;
2154
2155 if (SCS1.Third == SCS2.Third) {
2156 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2157 : ImplicitConversionSequence::Indistinguishable;
2158 }
2159
2160 if (SCS1.Third == ICK_Identity)
2161 return Result == ImplicitConversionSequence::Worse
2162 ? ImplicitConversionSequence::Indistinguishable
2163 : ImplicitConversionSequence::Better;
2164
2165 if (SCS2.Third == ICK_Identity)
2166 return Result == ImplicitConversionSequence::Better
2167 ? ImplicitConversionSequence::Indistinguishable
2168 : ImplicitConversionSequence::Worse;
2169
2170 return ImplicitConversionSequence::Indistinguishable;
2171}
2172
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002173/// CompareStandardConversionSequences - Compare two standard
2174/// conversion sequences to determine whether one is better than the
2175/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002176ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002177Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2178 const StandardConversionSequence& SCS2)
2179{
2180 // Standard conversion sequence S1 is a better conversion sequence
2181 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2182
2183 // -- S1 is a proper subsequence of S2 (comparing the conversion
2184 // sequences in the canonical form defined by 13.3.3.1.1,
2185 // excluding any Lvalue Transformation; the identity conversion
2186 // sequence is considered to be a subsequence of any
2187 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002188 if (ImplicitConversionSequence::CompareKind CK
2189 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2190 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002191
2192 // -- the rank of S1 is better than the rank of S2 (by the rules
2193 // defined below), or, if not that,
2194 ImplicitConversionRank Rank1 = SCS1.getRank();
2195 ImplicitConversionRank Rank2 = SCS2.getRank();
2196 if (Rank1 < Rank2)
2197 return ImplicitConversionSequence::Better;
2198 else if (Rank2 < Rank1)
2199 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002200
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002201 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2202 // are indistinguishable unless one of the following rules
2203 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002204
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002205 // A conversion that is not a conversion of a pointer, or
2206 // pointer to member, to bool is better than another conversion
2207 // that is such a conversion.
2208 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2209 return SCS2.isPointerConversionToBool()
2210 ? ImplicitConversionSequence::Better
2211 : ImplicitConversionSequence::Worse;
2212
Douglas Gregor5c407d92008-10-23 00:40:37 +00002213 // C++ [over.ics.rank]p4b2:
2214 //
2215 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002216 // conversion of B* to A* is better than conversion of B* to
2217 // void*, and conversion of A* to void* is better than conversion
2218 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002219 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002220 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002221 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002222 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002223 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2224 // Exactly one of the conversion sequences is a conversion to
2225 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002226 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2227 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002228 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2229 // Neither conversion sequence converts to a void pointer; compare
2230 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002231 if (ImplicitConversionSequence::CompareKind DerivedCK
2232 = CompareDerivedToBaseConversions(SCS1, SCS2))
2233 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002234 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2235 // Both conversion sequences are conversions to void
2236 // pointers. Compare the source types to determine if there's an
2237 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002238 QualType FromType1 = SCS1.getFromType();
2239 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002240
2241 // Adjust the types we're converting from via the array-to-pointer
2242 // conversion, if we need to.
2243 if (SCS1.First == ICK_Array_To_Pointer)
2244 FromType1 = Context.getArrayDecayedType(FromType1);
2245 if (SCS2.First == ICK_Array_To_Pointer)
2246 FromType2 = Context.getArrayDecayedType(FromType2);
2247
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002248 QualType FromPointee1
2249 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2250 QualType FromPointee2
2251 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002252
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002253 if (IsDerivedFrom(FromPointee2, FromPointee1))
2254 return ImplicitConversionSequence::Better;
2255 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2256 return ImplicitConversionSequence::Worse;
2257
2258 // Objective-C++: If one interface is more specific than the
2259 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002260 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2261 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002262 if (FromIface1 && FromIface1) {
2263 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2264 return ImplicitConversionSequence::Better;
2265 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2266 return ImplicitConversionSequence::Worse;
2267 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002268 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002269
2270 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2271 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002272 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002273 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002274 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002275
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002276 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002277 // C++0x [over.ics.rank]p3b4:
2278 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2279 // implicit object parameter of a non-static member function declared
2280 // without a ref-qualifier, and S1 binds an rvalue reference to an
2281 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002282 // FIXME: We don't know if we're dealing with the implicit object parameter,
2283 // or if the member function in this case has a ref qualifier.
2284 // (Of course, we don't have ref qualifiers yet.)
2285 if (SCS1.RRefBinding != SCS2.RRefBinding)
2286 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2287 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002288
2289 // C++ [over.ics.rank]p3b4:
2290 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2291 // which the references refer are the same type except for
2292 // top-level cv-qualifiers, and the type to which the reference
2293 // initialized by S2 refers is more cv-qualified than the type
2294 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002295 QualType T1 = SCS1.getToType(2);
2296 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002297 T1 = Context.getCanonicalType(T1);
2298 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002299 Qualifiers T1Quals, T2Quals;
2300 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2301 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2302 if (UnqualT1 == UnqualT2) {
2303 // If the type is an array type, promote the element qualifiers to the type
2304 // for comparison.
2305 if (isa<ArrayType>(T1) && T1Quals)
2306 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2307 if (isa<ArrayType>(T2) && T2Quals)
2308 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002309 if (T2.isMoreQualifiedThan(T1))
2310 return ImplicitConversionSequence::Better;
2311 else if (T1.isMoreQualifiedThan(T2))
2312 return ImplicitConversionSequence::Worse;
2313 }
2314 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002315
2316 return ImplicitConversionSequence::Indistinguishable;
2317}
2318
2319/// CompareQualificationConversions - Compares two standard conversion
2320/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002321/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2322ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002323Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002324 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002325 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002326 // -- S1 and S2 differ only in their qualification conversion and
2327 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2328 // cv-qualification signature of type T1 is a proper subset of
2329 // the cv-qualification signature of type T2, and S1 is not the
2330 // deprecated string literal array-to-pointer conversion (4.2).
2331 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2332 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2333 return ImplicitConversionSequence::Indistinguishable;
2334
2335 // FIXME: the example in the standard doesn't use a qualification
2336 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002337 QualType T1 = SCS1.getToType(2);
2338 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002339 T1 = Context.getCanonicalType(T1);
2340 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002341 Qualifiers T1Quals, T2Quals;
2342 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2343 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002344
2345 // If the types are the same, we won't learn anything by unwrapped
2346 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002347 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002348 return ImplicitConversionSequence::Indistinguishable;
2349
Chandler Carruth607f38e2009-12-29 07:16:59 +00002350 // If the type is an array type, promote the element qualifiers to the type
2351 // for comparison.
2352 if (isa<ArrayType>(T1) && T1Quals)
2353 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2354 if (isa<ArrayType>(T2) && T2Quals)
2355 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2356
Mike Stump11289f42009-09-09 15:08:12 +00002357 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002358 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002359 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002360 // Within each iteration of the loop, we check the qualifiers to
2361 // determine if this still looks like a qualification
2362 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002363 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002364 // until there are no more pointers or pointers-to-members left
2365 // to unwrap. This essentially mimics what
2366 // IsQualificationConversion does, but here we're checking for a
2367 // strict subset of qualifiers.
2368 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2369 // The qualifiers are the same, so this doesn't tell us anything
2370 // about how the sequences rank.
2371 ;
2372 else if (T2.isMoreQualifiedThan(T1)) {
2373 // T1 has fewer qualifiers, so it could be the better sequence.
2374 if (Result == ImplicitConversionSequence::Worse)
2375 // Neither has qualifiers that are a subset of the other's
2376 // qualifiers.
2377 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002379 Result = ImplicitConversionSequence::Better;
2380 } else if (T1.isMoreQualifiedThan(T2)) {
2381 // T2 has fewer qualifiers, so it could be the better sequence.
2382 if (Result == ImplicitConversionSequence::Better)
2383 // Neither has qualifiers that are a subset of the other's
2384 // qualifiers.
2385 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002386
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002387 Result = ImplicitConversionSequence::Worse;
2388 } else {
2389 // Qualifiers are disjoint.
2390 return ImplicitConversionSequence::Indistinguishable;
2391 }
2392
2393 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002394 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002395 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002396 }
2397
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002398 // Check that the winning standard conversion sequence isn't using
2399 // the deprecated string literal array to pointer conversion.
2400 switch (Result) {
2401 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002402 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002403 Result = ImplicitConversionSequence::Indistinguishable;
2404 break;
2405
2406 case ImplicitConversionSequence::Indistinguishable:
2407 break;
2408
2409 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002410 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002411 Result = ImplicitConversionSequence::Indistinguishable;
2412 break;
2413 }
2414
2415 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002416}
2417
Douglas Gregor5c407d92008-10-23 00:40:37 +00002418/// CompareDerivedToBaseConversions - Compares two standard conversion
2419/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002420/// various kinds of derived-to-base conversions (C++
2421/// [over.ics.rank]p4b3). As part of these checks, we also look at
2422/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002423ImplicitConversionSequence::CompareKind
2424Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2425 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002426 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002427 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002428 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002429 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002430
2431 // Adjust the types we're converting from via the array-to-pointer
2432 // conversion, if we need to.
2433 if (SCS1.First == ICK_Array_To_Pointer)
2434 FromType1 = Context.getArrayDecayedType(FromType1);
2435 if (SCS2.First == ICK_Array_To_Pointer)
2436 FromType2 = Context.getArrayDecayedType(FromType2);
2437
2438 // Canonicalize all of the types.
2439 FromType1 = Context.getCanonicalType(FromType1);
2440 ToType1 = Context.getCanonicalType(ToType1);
2441 FromType2 = Context.getCanonicalType(FromType2);
2442 ToType2 = Context.getCanonicalType(ToType2);
2443
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002444 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002445 //
2446 // If class B is derived directly or indirectly from class A and
2447 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002448 //
2449 // For Objective-C, we let A, B, and C also be Objective-C
2450 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002451
2452 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002453 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002454 SCS2.Second == ICK_Pointer_Conversion &&
2455 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2456 FromType1->isPointerType() && FromType2->isPointerType() &&
2457 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002458 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002459 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002460 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002461 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002462 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002463 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002464 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002465 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002466
John McCall8b07ec22010-05-15 11:32:37 +00002467 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2468 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2469 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2470 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002471
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002472 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002473 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2474 if (IsDerivedFrom(ToPointee1, ToPointee2))
2475 return ImplicitConversionSequence::Better;
2476 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2477 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002478
2479 if (ToIface1 && ToIface2) {
2480 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2481 return ImplicitConversionSequence::Better;
2482 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2483 return ImplicitConversionSequence::Worse;
2484 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002485 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002486
2487 // -- conversion of B* to A* is better than conversion of C* to A*,
2488 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2489 if (IsDerivedFrom(FromPointee2, FromPointee1))
2490 return ImplicitConversionSequence::Better;
2491 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2492 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002493
Douglas Gregor237f96c2008-11-26 23:31:11 +00002494 if (FromIface1 && FromIface2) {
2495 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2496 return ImplicitConversionSequence::Better;
2497 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2498 return ImplicitConversionSequence::Worse;
2499 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002500 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002501 }
2502
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002503 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002504 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2505 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2506 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2507 const MemberPointerType * FromMemPointer1 =
2508 FromType1->getAs<MemberPointerType>();
2509 const MemberPointerType * ToMemPointer1 =
2510 ToType1->getAs<MemberPointerType>();
2511 const MemberPointerType * FromMemPointer2 =
2512 FromType2->getAs<MemberPointerType>();
2513 const MemberPointerType * ToMemPointer2 =
2514 ToType2->getAs<MemberPointerType>();
2515 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2516 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2517 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2518 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2519 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2520 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2521 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2522 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002523 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002524 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2525 if (IsDerivedFrom(ToPointee1, ToPointee2))
2526 return ImplicitConversionSequence::Worse;
2527 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2528 return ImplicitConversionSequence::Better;
2529 }
2530 // conversion of B::* to C::* is better than conversion of A::* to C::*
2531 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2532 if (IsDerivedFrom(FromPointee1, FromPointee2))
2533 return ImplicitConversionSequence::Better;
2534 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2535 return ImplicitConversionSequence::Worse;
2536 }
2537 }
2538
Douglas Gregor5ab11652010-04-17 22:01:05 +00002539 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002540 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002541 // -- binding of an expression of type C to a reference of type
2542 // B& is better than binding an expression of type C to a
2543 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002544 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2545 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002546 if (IsDerivedFrom(ToType1, ToType2))
2547 return ImplicitConversionSequence::Better;
2548 else if (IsDerivedFrom(ToType2, ToType1))
2549 return ImplicitConversionSequence::Worse;
2550 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002551
Douglas Gregor2fe98832008-11-03 19:09:14 +00002552 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002553 // -- binding of an expression of type B to a reference of type
2554 // A& is better than binding an expression of type C to a
2555 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002556 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2557 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002558 if (IsDerivedFrom(FromType2, FromType1))
2559 return ImplicitConversionSequence::Better;
2560 else if (IsDerivedFrom(FromType1, FromType2))
2561 return ImplicitConversionSequence::Worse;
2562 }
2563 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002564
Douglas Gregor5c407d92008-10-23 00:40:37 +00002565 return ImplicitConversionSequence::Indistinguishable;
2566}
2567
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002568/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2569/// determine whether they are reference-related,
2570/// reference-compatible, reference-compatible with added
2571/// qualification, or incompatible, for use in C++ initialization by
2572/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2573/// type, and the first type (T1) is the pointee type of the reference
2574/// type being initialized.
2575Sema::ReferenceCompareResult
2576Sema::CompareReferenceRelationship(SourceLocation Loc,
2577 QualType OrigT1, QualType OrigT2,
2578 bool& DerivedToBase) {
2579 assert(!OrigT1->isReferenceType() &&
2580 "T1 must be the pointee type of the reference type");
2581 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2582
2583 QualType T1 = Context.getCanonicalType(OrigT1);
2584 QualType T2 = Context.getCanonicalType(OrigT2);
2585 Qualifiers T1Quals, T2Quals;
2586 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2587 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2588
2589 // C++ [dcl.init.ref]p4:
2590 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2591 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2592 // T1 is a base class of T2.
2593 if (UnqualT1 == UnqualT2)
2594 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002595 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002596 IsDerivedFrom(UnqualT2, UnqualT1))
2597 DerivedToBase = true;
2598 else
2599 return Ref_Incompatible;
2600
2601 // At this point, we know that T1 and T2 are reference-related (at
2602 // least).
2603
2604 // If the type is an array type, promote the element qualifiers to the type
2605 // for comparison.
2606 if (isa<ArrayType>(T1) && T1Quals)
2607 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2608 if (isa<ArrayType>(T2) && T2Quals)
2609 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2610
2611 // C++ [dcl.init.ref]p4:
2612 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2613 // reference-related to T2 and cv1 is the same cv-qualification
2614 // as, or greater cv-qualification than, cv2. For purposes of
2615 // overload resolution, cases for which cv1 is greater
2616 // cv-qualification than cv2 are identified as
2617 // reference-compatible with added qualification (see 13.3.3.2).
2618 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2619 return Ref_Compatible;
2620 else if (T1.isMoreQualifiedThan(T2))
2621 return Ref_Compatible_With_Added_Qualification;
2622 else
2623 return Ref_Related;
2624}
2625
2626/// \brief Compute an implicit conversion sequence for reference
2627/// initialization.
2628static ImplicitConversionSequence
2629TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2630 SourceLocation DeclLoc,
2631 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002632 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002633 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2634
2635 // Most paths end in a failed conversion.
2636 ImplicitConversionSequence ICS;
2637 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2638
2639 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2640 QualType T2 = Init->getType();
2641
2642 // If the initializer is the address of an overloaded function, try
2643 // to resolve the overloaded function. If all goes well, T2 is the
2644 // type of the resulting function.
2645 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2646 DeclAccessPair Found;
2647 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2648 false, Found))
2649 T2 = Fn->getType();
2650 }
2651
2652 // Compute some basic properties of the types and the initializer.
2653 bool isRValRef = DeclType->isRValueReferenceType();
2654 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002655 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002656 Sema::ReferenceCompareResult RefRelationship
2657 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2658
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002659
2660 // C++ [over.ics.ref]p3:
2661 // Except for an implicit object parameter, for which see 13.3.1,
2662 // a standard conversion sequence cannot be formed if it requires
2663 // binding an lvalue reference to non-const to an rvalue or
2664 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002665 //
2666 // FIXME: DPG doesn't trust this code. It seems far too early to
2667 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002668 if (isRValRef && InitLvalue == Expr::LV_Valid)
2669 return ICS;
2670
Douglas Gregor870f3742010-04-18 09:22:00 +00002671 // C++0x [dcl.init.ref]p16:
2672 // A reference to type "cv1 T1" is initialized by an expression
2673 // of type "cv2 T2" as follows:
2674
2675 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002676 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2677 // reference-compatible with "cv2 T2," or
2678 //
2679 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2680 if (InitLvalue == Expr::LV_Valid &&
2681 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2682 // C++ [over.ics.ref]p1:
2683 // When a parameter of reference type binds directly (8.5.3)
2684 // to an argument expression, the implicit conversion sequence
2685 // is the identity conversion, unless the argument expression
2686 // has a type that is a derived class of the parameter type,
2687 // in which case the implicit conversion sequence is a
2688 // derived-to-base Conversion (13.3.3.1).
2689 ICS.setStandard();
2690 ICS.Standard.First = ICK_Identity;
2691 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2692 ICS.Standard.Third = ICK_Identity;
2693 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2694 ICS.Standard.setToType(0, T2);
2695 ICS.Standard.setToType(1, T1);
2696 ICS.Standard.setToType(2, T1);
2697 ICS.Standard.ReferenceBinding = true;
2698 ICS.Standard.DirectBinding = true;
2699 ICS.Standard.RRefBinding = false;
2700 ICS.Standard.CopyConstructor = 0;
2701
2702 // Nothing more to do: the inaccessibility/ambiguity check for
2703 // derived-to-base conversions is suppressed when we're
2704 // computing the implicit conversion sequence (C++
2705 // [over.best.ics]p2).
2706 return ICS;
2707 }
2708
2709 // -- has a class type (i.e., T2 is a class type), where T1 is
2710 // not reference-related to T2, and can be implicitly
2711 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2712 // is reference-compatible with "cv3 T3" 92) (this
2713 // conversion is selected by enumerating the applicable
2714 // conversion functions (13.3.1.6) and choosing the best
2715 // one through overload resolution (13.3)),
2716 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2717 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2718 RefRelationship == Sema::Ref_Incompatible) {
2719 CXXRecordDecl *T2RecordDecl
2720 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2721
2722 OverloadCandidateSet CandidateSet(DeclLoc);
2723 const UnresolvedSetImpl *Conversions
2724 = T2RecordDecl->getVisibleConversionFunctions();
2725 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2726 E = Conversions->end(); I != E; ++I) {
2727 NamedDecl *D = *I;
2728 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2729 if (isa<UsingShadowDecl>(D))
2730 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2731
2732 FunctionTemplateDecl *ConvTemplate
2733 = dyn_cast<FunctionTemplateDecl>(D);
2734 CXXConversionDecl *Conv;
2735 if (ConvTemplate)
2736 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2737 else
2738 Conv = cast<CXXConversionDecl>(D);
2739
2740 // If the conversion function doesn't return a reference type,
2741 // it can't be considered for this conversion.
2742 if (Conv->getConversionType()->isLValueReferenceType() &&
2743 (AllowExplicit || !Conv->isExplicit())) {
2744 if (ConvTemplate)
2745 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2746 Init, DeclType, CandidateSet);
2747 else
2748 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2749 DeclType, CandidateSet);
2750 }
2751 }
2752
2753 OverloadCandidateSet::iterator Best;
2754 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2755 case OR_Success:
2756 // C++ [over.ics.ref]p1:
2757 //
2758 // [...] If the parameter binds directly to the result of
2759 // applying a conversion function to the argument
2760 // expression, the implicit conversion sequence is a
2761 // user-defined conversion sequence (13.3.3.1.2), with the
2762 // second standard conversion sequence either an identity
2763 // conversion or, if the conversion function returns an
2764 // entity of a type that is a derived class of the parameter
2765 // type, a derived-to-base Conversion.
2766 if (!Best->FinalConversion.DirectBinding)
2767 break;
2768
2769 ICS.setUserDefined();
2770 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2771 ICS.UserDefined.After = Best->FinalConversion;
2772 ICS.UserDefined.ConversionFunction = Best->Function;
2773 ICS.UserDefined.EllipsisConversion = false;
2774 assert(ICS.UserDefined.After.ReferenceBinding &&
2775 ICS.UserDefined.After.DirectBinding &&
2776 "Expected a direct reference binding!");
2777 return ICS;
2778
2779 case OR_Ambiguous:
2780 ICS.setAmbiguous();
2781 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2782 Cand != CandidateSet.end(); ++Cand)
2783 if (Cand->Viable)
2784 ICS.Ambiguous.addConversion(Cand->Function);
2785 return ICS;
2786
2787 case OR_No_Viable_Function:
2788 case OR_Deleted:
2789 // There was no suitable conversion, or we found a deleted
2790 // conversion; continue with other checks.
2791 break;
2792 }
2793 }
2794
2795 // -- Otherwise, the reference shall be to a non-volatile const
2796 // type (i.e., cv1 shall be const), or the reference shall be an
2797 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002798 //
2799 // We actually handle one oddity of C++ [over.ics.ref] at this
2800 // point, which is that, due to p2 (which short-circuits reference
2801 // binding by only attempting a simple conversion for non-direct
2802 // bindings) and p3's strange wording, we allow a const volatile
2803 // reference to bind to an rvalue. Hence the check for the presence
2804 // of "const" rather than checking for "const" being the only
2805 // qualifier.
2806 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002807 return ICS;
2808
Douglas Gregorf93df192010-04-18 08:46:23 +00002809 // -- if T2 is a class type and
2810 // -- the initializer expression is an rvalue and "cv1 T1"
2811 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002812 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002813 // -- T1 is not reference-related to T2 and the initializer
2814 // expression can be implicitly converted to an rvalue
2815 // of type "cv3 T3" (this conversion is selected by
2816 // enumerating the applicable conversion functions
2817 // (13.3.1.6) and choosing the best one through overload
2818 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002819 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002820 // then the reference is bound to the initializer
2821 // expression rvalue in the first case and to the object
2822 // that is the result of the conversion in the second case
2823 // (or, in either case, to the appropriate base class
2824 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002825 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002826 // We're only checking the first case here, which is a direct
2827 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002828 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2829 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2830 ICS.setStandard();
2831 ICS.Standard.First = ICK_Identity;
2832 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2833 ICS.Standard.Third = ICK_Identity;
2834 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2835 ICS.Standard.setToType(0, T2);
2836 ICS.Standard.setToType(1, T1);
2837 ICS.Standard.setToType(2, T1);
2838 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002839 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002840 ICS.Standard.RRefBinding = isRValRef;
2841 ICS.Standard.CopyConstructor = 0;
2842 return ICS;
2843 }
2844
2845 // -- Otherwise, a temporary of type "cv1 T1" is created and
2846 // initialized from the initializer expression using the
2847 // rules for a non-reference copy initialization (8.5). The
2848 // reference is then bound to the temporary. If T1 is
2849 // reference-related to T2, cv1 must be the same
2850 // cv-qualification as, or greater cv-qualification than,
2851 // cv2; otherwise, the program is ill-formed.
2852 if (RefRelationship == Sema::Ref_Related) {
2853 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2854 // we would be reference-compatible or reference-compatible with
2855 // added qualification. But that wasn't the case, so the reference
2856 // initialization fails.
2857 return ICS;
2858 }
2859
2860 // If at least one of the types is a class type, the types are not
2861 // related, and we aren't allowed any user conversions, the
2862 // reference binding fails. This case is important for breaking
2863 // recursion, since TryImplicitConversion below will attempt to
2864 // create a temporary through the use of a copy constructor.
2865 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2866 (T1->isRecordType() || T2->isRecordType()))
2867 return ICS;
2868
2869 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002870 // When a parameter of reference type is not bound directly to
2871 // an argument expression, the conversion sequence is the one
2872 // required to convert the argument expression to the
2873 // underlying type of the reference according to
2874 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2875 // to copy-initializing a temporary of the underlying type with
2876 // the argument expression. Any difference in top-level
2877 // cv-qualification is subsumed by the initialization itself
2878 // and does not constitute a conversion.
2879 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2880 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002881 /*InOverloadResolution=*/false);
2882
2883 // Of course, that's still a reference binding.
2884 if (ICS.isStandard()) {
2885 ICS.Standard.ReferenceBinding = true;
2886 ICS.Standard.RRefBinding = isRValRef;
2887 } else if (ICS.isUserDefined()) {
2888 ICS.UserDefined.After.ReferenceBinding = true;
2889 ICS.UserDefined.After.RRefBinding = isRValRef;
2890 }
2891 return ICS;
2892}
2893
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002894/// TryCopyInitialization - Try to copy-initialize a value of type
2895/// ToType from the expression From. Return the implicit conversion
2896/// sequence required to pass this argument, which may be a bad
2897/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002898/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002899/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002900static ImplicitConversionSequence
2901TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002902 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002903 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002904 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002905 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002906 /*FIXME:*/From->getLocStart(),
2907 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002908 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002909
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002910 return S.TryImplicitConversion(From, ToType,
2911 SuppressUserConversions,
2912 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002913 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002914}
2915
Douglas Gregor436424c2008-11-18 23:14:02 +00002916/// TryObjectArgumentInitialization - Try to initialize the object
2917/// parameter of the given member function (@c Method) from the
2918/// expression @p From.
2919ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002920Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002921 CXXMethodDecl *Method,
2922 CXXRecordDecl *ActingContext) {
2923 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002924 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2925 // const volatile object.
2926 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2927 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2928 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002929
2930 // Set up the conversion sequence as a "bad" conversion, to allow us
2931 // to exit early.
2932 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002933
2934 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002935 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002936 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002937 FromType = PT->getPointeeType();
2938
2939 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002940
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002941 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002942 // where X is the class of which the function is a member
2943 // (C++ [over.match.funcs]p4). However, when finding an implicit
2944 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002945 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002946 // (C++ [over.match.funcs]p5). We perform a simplified version of
2947 // reference binding here, that allows class rvalues to bind to
2948 // non-constant references.
2949
2950 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2951 // with the implicit object parameter (C++ [over.match.funcs]p5).
2952 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002953 if (ImplicitParamType.getCVRQualifiers()
2954 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002955 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002956 ICS.setBad(BadConversionSequence::bad_qualifiers,
2957 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002958 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002959 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002960
2961 // Check that we have either the same type or a derived type. It
2962 // affects the conversion rank.
2963 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002964 ImplicitConversionKind SecondKind;
2965 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2966 SecondKind = ICK_Identity;
2967 } else if (IsDerivedFrom(FromType, ClassType))
2968 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002969 else {
John McCall65eb8792010-02-25 01:37:24 +00002970 ICS.setBad(BadConversionSequence::unrelated_class,
2971 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002972 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002973 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002974
2975 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002976 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002977 ICS.Standard.setAsIdentityConversion();
2978 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002979 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002980 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002981 ICS.Standard.ReferenceBinding = true;
2982 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002983 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002984 return ICS;
2985}
2986
2987/// PerformObjectArgumentInitialization - Perform initialization of
2988/// the implicit object parameter for the given Method with the given
2989/// expression.
2990bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002991Sema::PerformObjectArgumentInitialization(Expr *&From,
2992 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002993 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002994 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002995 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002996 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002997 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002998
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002999 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003000 FromRecordType = PT->getPointeeType();
3001 DestType = Method->getThisType(Context);
3002 } else {
3003 FromRecordType = From->getType();
3004 DestType = ImplicitParamRecordType;
3005 }
3006
John McCall6e9f8f62009-12-03 04:06:58 +00003007 // Note that we always use the true parent context when performing
3008 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003009 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003010 = TryObjectArgumentInitialization(From->getType(), Method,
3011 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003012 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003013 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003014 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003015 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003016
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003017 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003018 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003019
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003020 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003021 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
3022 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003023 return false;
3024}
3025
Douglas Gregor5fb53972009-01-14 15:45:31 +00003026/// TryContextuallyConvertToBool - Attempt to contextually convert the
3027/// expression From to bool (C++0x [conv]p3).
3028ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003029 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003030 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003031 // FIXME: Are these flags correct?
3032 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003033 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003034 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003035}
3036
3037/// PerformContextuallyConvertToBool - Perform a contextual conversion
3038/// of the expression From to bool (C++0x [conv]p3).
3039bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3040 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003041 if (!ICS.isBad())
3042 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003043
Fariborz Jahanian76197412009-11-18 18:26:29 +00003044 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003045 return Diag(From->getSourceRange().getBegin(),
3046 diag::err_typecheck_bool_condition)
3047 << From->getType() << From->getSourceRange();
3048 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003049}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003050
3051/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3052/// expression From to 'id'.
3053ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003054 QualType Ty = Context.getObjCIdType();
3055 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003056 // FIXME: Are these flags correct?
3057 /*SuppressUserConversions=*/false,
3058 /*AllowExplicit=*/true,
3059 /*InOverloadResolution=*/false);
3060}
3061
3062/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3063/// of the expression From to 'id'.
3064bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003065 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003066 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3067 if (!ICS.isBad())
3068 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3069 return true;
3070}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003071
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003072/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003073/// candidate functions, using the given function call arguments. If
3074/// @p SuppressUserConversions, then don't allow user-defined
3075/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003076///
3077/// \para PartialOverloading true if we are performing "partial" overloading
3078/// based on an incomplete set of function arguments. This feature is used by
3079/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003080void
3081Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003082 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003083 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003084 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003085 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003086 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003087 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003088 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003089 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003090 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003091 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003092
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003093 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003094 if (!isa<CXXConstructorDecl>(Method)) {
3095 // If we get here, it's because we're calling a member function
3096 // that is named without a member access expression (e.g.,
3097 // "this->f") that was either written explicitly or created
3098 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003099 // function, e.g., X::f(). We use an empty type for the implied
3100 // object argument (C++ [over.call.func]p3), and the acting context
3101 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003102 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003103 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003104 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003105 return;
3106 }
3107 // We treat a constructor like a non-member function, since its object
3108 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003109 }
3110
Douglas Gregorff7028a2009-11-13 23:59:09 +00003111 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003112 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003113
Douglas Gregor27381f32009-11-23 12:27:39 +00003114 // Overload resolution is always an unevaluated context.
3115 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3116
Douglas Gregorffe14e32009-11-14 01:20:54 +00003117 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3118 // C++ [class.copy]p3:
3119 // A member function template is never instantiated to perform the copy
3120 // of a class object to an object of its class type.
3121 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3122 if (NumArgs == 1 &&
3123 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003124 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3125 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003126 return;
3127 }
3128
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003129 // Add this candidate
3130 CandidateSet.push_back(OverloadCandidate());
3131 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003132 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003133 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003134 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003135 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003136 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003137
3138 unsigned NumArgsInProto = Proto->getNumArgs();
3139
3140 // (C++ 13.3.2p2): A candidate function having fewer than m
3141 // parameters is viable only if it has an ellipsis in its parameter
3142 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003143 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3144 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003145 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003146 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003147 return;
3148 }
3149
3150 // (C++ 13.3.2p2): A candidate function having more than m parameters
3151 // is viable only if the (m+1)st parameter has a default argument
3152 // (8.3.6). For the purposes of overload resolution, the
3153 // parameter list is truncated on the right, so that there are
3154 // exactly m parameters.
3155 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003156 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003157 // Not enough arguments.
3158 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003159 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003160 return;
3161 }
3162
3163 // Determine the implicit conversion sequences for each of the
3164 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003165 Candidate.Conversions.resize(NumArgs);
3166 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3167 if (ArgIdx < NumArgsInProto) {
3168 // (C++ 13.3.2p3): for F to be a viable function, there shall
3169 // exist for each argument an implicit conversion sequence
3170 // (13.3.3.1) that converts that argument to the corresponding
3171 // parameter of F.
3172 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003173 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003174 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003175 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003176 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003177 if (Candidate.Conversions[ArgIdx].isBad()) {
3178 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003179 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003180 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003181 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003182 } else {
3183 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3184 // argument for which there is no corresponding parameter is
3185 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003186 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003187 }
3188 }
3189}
3190
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003191/// \brief Add all of the function declarations in the given function set to
3192/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003193void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003194 Expr **Args, unsigned NumArgs,
3195 OverloadCandidateSet& CandidateSet,
3196 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003197 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003198 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3199 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003200 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003201 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003202 cast<CXXMethodDecl>(FD)->getParent(),
3203 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003204 CandidateSet, SuppressUserConversions);
3205 else
John McCalla0296f72010-03-19 07:35:19 +00003206 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003207 SuppressUserConversions);
3208 } else {
John McCalla0296f72010-03-19 07:35:19 +00003209 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003210 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3211 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003212 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003213 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003214 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003215 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003216 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003217 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003218 else
John McCalla0296f72010-03-19 07:35:19 +00003219 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003220 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003221 Args, NumArgs, CandidateSet,
3222 SuppressUserConversions);
3223 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003224 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003225}
3226
John McCallf0f1cf02009-11-17 07:50:12 +00003227/// AddMethodCandidate - Adds a named decl (which is some kind of
3228/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003229void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003230 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003231 Expr **Args, unsigned NumArgs,
3232 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003233 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003234 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003235 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003236
3237 if (isa<UsingShadowDecl>(Decl))
3238 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3239
3240 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3241 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3242 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003243 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3244 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003245 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003246 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003247 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003248 } else {
John McCalla0296f72010-03-19 07:35:19 +00003249 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003250 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003251 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003252 }
3253}
3254
Douglas Gregor436424c2008-11-18 23:14:02 +00003255/// AddMethodCandidate - Adds the given C++ member function to the set
3256/// of candidate functions, using the given function call arguments
3257/// and the object argument (@c Object). For example, in a call
3258/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3259/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3260/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003261/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003262void
John McCalla0296f72010-03-19 07:35:19 +00003263Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003264 CXXRecordDecl *ActingContext, QualType ObjectType,
3265 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003266 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003267 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003268 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003269 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003270 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003271 assert(!isa<CXXConstructorDecl>(Method) &&
3272 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003273
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003274 if (!CandidateSet.isNewCandidate(Method))
3275 return;
3276
Douglas Gregor27381f32009-11-23 12:27:39 +00003277 // Overload resolution is always an unevaluated context.
3278 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3279
Douglas Gregor436424c2008-11-18 23:14:02 +00003280 // Add this candidate
3281 CandidateSet.push_back(OverloadCandidate());
3282 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003283 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003284 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003285 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003286 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003287
3288 unsigned NumArgsInProto = Proto->getNumArgs();
3289
3290 // (C++ 13.3.2p2): A candidate function having fewer than m
3291 // parameters is viable only if it has an ellipsis in its parameter
3292 // list (8.3.5).
3293 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3294 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003295 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003296 return;
3297 }
3298
3299 // (C++ 13.3.2p2): A candidate function having more than m parameters
3300 // is viable only if the (m+1)st parameter has a default argument
3301 // (8.3.6). For the purposes of overload resolution, the
3302 // parameter list is truncated on the right, so that there are
3303 // exactly m parameters.
3304 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3305 if (NumArgs < MinRequiredArgs) {
3306 // Not enough arguments.
3307 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003308 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003309 return;
3310 }
3311
3312 Candidate.Viable = true;
3313 Candidate.Conversions.resize(NumArgs + 1);
3314
John McCall6e9f8f62009-12-03 04:06:58 +00003315 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003316 // The implicit object argument is ignored.
3317 Candidate.IgnoreObjectArgument = true;
3318 else {
3319 // Determine the implicit conversion sequence for the object
3320 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003321 Candidate.Conversions[0]
3322 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003323 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003324 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003325 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003326 return;
3327 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003328 }
3329
3330 // Determine the implicit conversion sequences for each of the
3331 // arguments.
3332 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3333 if (ArgIdx < NumArgsInProto) {
3334 // (C++ 13.3.2p3): for F to be a viable function, there shall
3335 // exist for each argument an implicit conversion sequence
3336 // (13.3.3.1) that converts that argument to the corresponding
3337 // parameter of F.
3338 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003339 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003340 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003341 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003342 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003343 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003344 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003345 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003346 break;
3347 }
3348 } else {
3349 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3350 // argument for which there is no corresponding parameter is
3351 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003352 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003353 }
3354 }
3355}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003356
Douglas Gregor97628d62009-08-21 00:16:32 +00003357/// \brief Add a C++ member function template as a candidate to the candidate
3358/// set, using template argument deduction to produce an appropriate member
3359/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003360void
Douglas Gregor97628d62009-08-21 00:16:32 +00003361Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003362 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003363 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003364 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003365 QualType ObjectType,
3366 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003367 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003368 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003369 if (!CandidateSet.isNewCandidate(MethodTmpl))
3370 return;
3371
Douglas Gregor97628d62009-08-21 00:16:32 +00003372 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003373 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003374 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003375 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003376 // candidate functions in the usual way.113) A given name can refer to one
3377 // or more function templates and also to a set of overloaded non-template
3378 // functions. In such a case, the candidate functions generated from each
3379 // function template are combined with the set of non-template candidate
3380 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003381 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003382 FunctionDecl *Specialization = 0;
3383 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003384 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003385 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003386 CandidateSet.push_back(OverloadCandidate());
3387 OverloadCandidate &Candidate = CandidateSet.back();
3388 Candidate.FoundDecl = FoundDecl;
3389 Candidate.Function = MethodTmpl->getTemplatedDecl();
3390 Candidate.Viable = false;
3391 Candidate.FailureKind = ovl_fail_bad_deduction;
3392 Candidate.IsSurrogate = false;
3393 Candidate.IgnoreObjectArgument = false;
3394 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3395 Info);
3396 return;
3397 }
Mike Stump11289f42009-09-09 15:08:12 +00003398
Douglas Gregor97628d62009-08-21 00:16:32 +00003399 // Add the function template specialization produced by template argument
3400 // deduction as a candidate.
3401 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003402 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003403 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003404 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003405 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003406 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003407}
3408
Douglas Gregor05155d82009-08-21 23:19:43 +00003409/// \brief Add a C++ function template specialization as a candidate
3410/// in the candidate set, using template argument deduction to produce
3411/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003412void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003413Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003414 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003415 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003416 Expr **Args, unsigned NumArgs,
3417 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003418 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003419 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3420 return;
3421
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003422 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003423 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003424 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003425 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003426 // candidate functions in the usual way.113) A given name can refer to one
3427 // or more function templates and also to a set of overloaded non-template
3428 // functions. In such a case, the candidate functions generated from each
3429 // function template are combined with the set of non-template candidate
3430 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003431 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003432 FunctionDecl *Specialization = 0;
3433 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003434 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003435 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003436 CandidateSet.push_back(OverloadCandidate());
3437 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003438 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003439 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3440 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003441 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003442 Candidate.IsSurrogate = false;
3443 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003444 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3445 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003446 return;
3447 }
Mike Stump11289f42009-09-09 15:08:12 +00003448
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003449 // Add the function template specialization produced by template argument
3450 // deduction as a candidate.
3451 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003452 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003453 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003454}
Mike Stump11289f42009-09-09 15:08:12 +00003455
Douglas Gregora1f013e2008-11-07 22:36:19 +00003456/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003457/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003458/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003459/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003460/// (which may or may not be the same type as the type that the
3461/// conversion function produces).
3462void
3463Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003464 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003465 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003466 Expr *From, QualType ToType,
3467 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003468 assert(!Conversion->getDescribedFunctionTemplate() &&
3469 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003470 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003471 if (!CandidateSet.isNewCandidate(Conversion))
3472 return;
3473
Douglas Gregor27381f32009-11-23 12:27:39 +00003474 // Overload resolution is always an unevaluated context.
3475 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3476
Douglas Gregora1f013e2008-11-07 22:36:19 +00003477 // Add this candidate
3478 CandidateSet.push_back(OverloadCandidate());
3479 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003480 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003481 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003482 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003483 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003484 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003485 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003486 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003487
Douglas Gregor436424c2008-11-18 23:14:02 +00003488 // Determine the implicit conversion sequence for the implicit
3489 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003490 Candidate.Viable = true;
3491 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003492 Candidate.Conversions[0]
3493 = TryObjectArgumentInitialization(From->getType(), Conversion,
3494 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003495 // Conversion functions to a different type in the base class is visible in
3496 // the derived class. So, a derived to base conversion should not participate
3497 // in overload resolution.
3498 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3499 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003500 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003501 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003502 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003503 return;
3504 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003505
3506 // We won't go through a user-define type conversion function to convert a
3507 // derived to base as such conversions are given Conversion Rank. They only
3508 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3509 QualType FromCanon
3510 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3511 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3512 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3513 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003514 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003515 return;
3516 }
3517
Douglas Gregora1f013e2008-11-07 22:36:19 +00003518 // To determine what the conversion from the result of calling the
3519 // conversion function to the type we're eventually trying to
3520 // convert to (ToType), we need to synthesize a call to the
3521 // conversion function and attempt copy initialization from it. This
3522 // makes sure that we get the right semantics with respect to
3523 // lvalues/rvalues and the type. Fortunately, we can allocate this
3524 // call on the stack and we don't need its arguments to be
3525 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003526 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003527 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003528 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003529 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003530 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003531
3532 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003533 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3534 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003535 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003536 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003537 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003538 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003539 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003540 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003541 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003542
John McCall0d1da222010-01-12 00:44:57 +00003543 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003544 case ImplicitConversionSequence::StandardConversion:
3545 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003546
3547 // C++ [over.ics.user]p3:
3548 // If the user-defined conversion is specified by a specialization of a
3549 // conversion function template, the second standard conversion sequence
3550 // shall have exact match rank.
3551 if (Conversion->getPrimaryTemplate() &&
3552 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3553 Candidate.Viable = false;
3554 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3555 }
3556
Douglas Gregora1f013e2008-11-07 22:36:19 +00003557 break;
3558
3559 case ImplicitConversionSequence::BadConversion:
3560 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003561 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003562 break;
3563
3564 default:
Mike Stump11289f42009-09-09 15:08:12 +00003565 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003566 "Can only end up with a standard conversion sequence or failure");
3567 }
3568}
3569
Douglas Gregor05155d82009-08-21 23:19:43 +00003570/// \brief Adds a conversion function template specialization
3571/// candidate to the overload set, using template argument deduction
3572/// to deduce the template arguments of the conversion function
3573/// template from the type that we are converting to (C++
3574/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003575void
Douglas Gregor05155d82009-08-21 23:19:43 +00003576Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003577 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003578 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003579 Expr *From, QualType ToType,
3580 OverloadCandidateSet &CandidateSet) {
3581 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3582 "Only conversion function templates permitted here");
3583
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003584 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3585 return;
3586
John McCallbc077cf2010-02-08 23:07:23 +00003587 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003588 CXXConversionDecl *Specialization = 0;
3589 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003590 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003591 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003592 CandidateSet.push_back(OverloadCandidate());
3593 OverloadCandidate &Candidate = CandidateSet.back();
3594 Candidate.FoundDecl = FoundDecl;
3595 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3596 Candidate.Viable = false;
3597 Candidate.FailureKind = ovl_fail_bad_deduction;
3598 Candidate.IsSurrogate = false;
3599 Candidate.IgnoreObjectArgument = false;
3600 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3601 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003602 return;
3603 }
Mike Stump11289f42009-09-09 15:08:12 +00003604
Douglas Gregor05155d82009-08-21 23:19:43 +00003605 // Add the conversion function template specialization produced by
3606 // template argument deduction as a candidate.
3607 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003608 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003609 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003610}
3611
Douglas Gregorab7897a2008-11-19 22:57:39 +00003612/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3613/// converts the given @c Object to a function pointer via the
3614/// conversion function @c Conversion, and then attempts to call it
3615/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3616/// the type of function that we'll eventually be calling.
3617void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003618 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003619 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003620 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003621 QualType ObjectType,
3622 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003623 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003624 if (!CandidateSet.isNewCandidate(Conversion))
3625 return;
3626
Douglas Gregor27381f32009-11-23 12:27:39 +00003627 // Overload resolution is always an unevaluated context.
3628 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3629
Douglas Gregorab7897a2008-11-19 22:57:39 +00003630 CandidateSet.push_back(OverloadCandidate());
3631 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003632 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003633 Candidate.Function = 0;
3634 Candidate.Surrogate = Conversion;
3635 Candidate.Viable = true;
3636 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003637 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003638 Candidate.Conversions.resize(NumArgs + 1);
3639
3640 // Determine the implicit conversion sequence for the implicit
3641 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003642 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003643 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003644 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003645 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003646 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003647 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003648 return;
3649 }
3650
3651 // The first conversion is actually a user-defined conversion whose
3652 // first conversion is ObjectInit's standard conversion (which is
3653 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003654 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003655 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003656 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003657 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003658 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003659 = Candidate.Conversions[0].UserDefined.Before;
3660 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3661
Mike Stump11289f42009-09-09 15:08:12 +00003662 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003663 unsigned NumArgsInProto = Proto->getNumArgs();
3664
3665 // (C++ 13.3.2p2): A candidate function having fewer than m
3666 // parameters is viable only if it has an ellipsis in its parameter
3667 // list (8.3.5).
3668 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3669 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003670 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003671 return;
3672 }
3673
3674 // Function types don't have any default arguments, so just check if
3675 // we have enough arguments.
3676 if (NumArgs < NumArgsInProto) {
3677 // Not enough arguments.
3678 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003679 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003680 return;
3681 }
3682
3683 // Determine the implicit conversion sequences for each of the
3684 // arguments.
3685 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3686 if (ArgIdx < NumArgsInProto) {
3687 // (C++ 13.3.2p3): for F to be a viable function, there shall
3688 // exist for each argument an implicit conversion sequence
3689 // (13.3.3.1) that converts that argument to the corresponding
3690 // parameter of F.
3691 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003692 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003693 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003694 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003695 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003696 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003697 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003698 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003699 break;
3700 }
3701 } else {
3702 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3703 // argument for which there is no corresponding parameter is
3704 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003705 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003706 }
3707 }
3708}
3709
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003710/// \brief Add overload candidates for overloaded operators that are
3711/// member functions.
3712///
3713/// Add the overloaded operator candidates that are member functions
3714/// for the operator Op that was used in an operator expression such
3715/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3716/// CandidateSet will store the added overload candidates. (C++
3717/// [over.match.oper]).
3718void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3719 SourceLocation OpLoc,
3720 Expr **Args, unsigned NumArgs,
3721 OverloadCandidateSet& CandidateSet,
3722 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003723 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3724
3725 // C++ [over.match.oper]p3:
3726 // For a unary operator @ with an operand of a type whose
3727 // cv-unqualified version is T1, and for a binary operator @ with
3728 // a left operand of a type whose cv-unqualified version is T1 and
3729 // a right operand of a type whose cv-unqualified version is T2,
3730 // three sets of candidate functions, designated member
3731 // candidates, non-member candidates and built-in candidates, are
3732 // constructed as follows:
3733 QualType T1 = Args[0]->getType();
3734 QualType T2;
3735 if (NumArgs > 1)
3736 T2 = Args[1]->getType();
3737
3738 // -- If T1 is a class type, the set of member candidates is the
3739 // result of the qualified lookup of T1::operator@
3740 // (13.3.1.1.1); otherwise, the set of member candidates is
3741 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003742 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003743 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003744 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003745 return;
Mike Stump11289f42009-09-09 15:08:12 +00003746
John McCall27b18f82009-11-17 02:14:36 +00003747 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3748 LookupQualifiedName(Operators, T1Rec->getDecl());
3749 Operators.suppressDiagnostics();
3750
Mike Stump11289f42009-09-09 15:08:12 +00003751 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003752 OperEnd = Operators.end();
3753 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003754 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003755 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003756 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003757 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003758 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003759}
3760
Douglas Gregora11693b2008-11-12 17:17:38 +00003761/// AddBuiltinCandidate - Add a candidate for a built-in
3762/// operator. ResultTy and ParamTys are the result and parameter types
3763/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003764/// arguments being passed to the candidate. IsAssignmentOperator
3765/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003766/// operator. NumContextualBoolArguments is the number of arguments
3767/// (at the beginning of the argument list) that will be contextually
3768/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003769void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003770 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003771 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003772 bool IsAssignmentOperator,
3773 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003774 // Overload resolution is always an unevaluated context.
3775 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3776
Douglas Gregora11693b2008-11-12 17:17:38 +00003777 // Add this candidate
3778 CandidateSet.push_back(OverloadCandidate());
3779 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003780 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003781 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003782 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003783 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003784 Candidate.BuiltinTypes.ResultTy = ResultTy;
3785 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3786 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3787
3788 // Determine the implicit conversion sequences for each of the
3789 // arguments.
3790 Candidate.Viable = true;
3791 Candidate.Conversions.resize(NumArgs);
3792 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003793 // C++ [over.match.oper]p4:
3794 // For the built-in assignment operators, conversions of the
3795 // left operand are restricted as follows:
3796 // -- no temporaries are introduced to hold the left operand, and
3797 // -- no user-defined conversions are applied to the left
3798 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003799 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003800 //
3801 // We block these conversions by turning off user-defined
3802 // conversions, since that is the only way that initialization of
3803 // a reference to a non-class type can occur from something that
3804 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003805 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003806 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003807 "Contextual conversion to bool requires bool type");
3808 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3809 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003810 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003811 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003812 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003813 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003814 }
John McCall0d1da222010-01-12 00:44:57 +00003815 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003816 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003817 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003818 break;
3819 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003820 }
3821}
3822
3823/// BuiltinCandidateTypeSet - A set of types that will be used for the
3824/// candidate operator functions for built-in operators (C++
3825/// [over.built]). The types are separated into pointer types and
3826/// enumeration types.
3827class BuiltinCandidateTypeSet {
3828 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003829 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003830
3831 /// PointerTypes - The set of pointer types that will be used in the
3832 /// built-in candidates.
3833 TypeSet PointerTypes;
3834
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003835 /// MemberPointerTypes - The set of member pointer types that will be
3836 /// used in the built-in candidates.
3837 TypeSet MemberPointerTypes;
3838
Douglas Gregora11693b2008-11-12 17:17:38 +00003839 /// EnumerationTypes - The set of enumeration types that will be
3840 /// used in the built-in candidates.
3841 TypeSet EnumerationTypes;
3842
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003843 /// \brief The set of vector types that will be used in the built-in
3844 /// candidates.
3845 TypeSet VectorTypes;
3846
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003847 /// Sema - The semantic analysis instance where we are building the
3848 /// candidate type set.
3849 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003850
Douglas Gregora11693b2008-11-12 17:17:38 +00003851 /// Context - The AST context in which we will build the type sets.
3852 ASTContext &Context;
3853
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003854 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3855 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003856 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003857
3858public:
3859 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003860 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003861
Mike Stump11289f42009-09-09 15:08:12 +00003862 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003863 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003864
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003865 void AddTypesConvertedFrom(QualType Ty,
3866 SourceLocation Loc,
3867 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003868 bool AllowExplicitConversions,
3869 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003870
3871 /// pointer_begin - First pointer type found;
3872 iterator pointer_begin() { return PointerTypes.begin(); }
3873
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003874 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003875 iterator pointer_end() { return PointerTypes.end(); }
3876
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003877 /// member_pointer_begin - First member pointer type found;
3878 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3879
3880 /// member_pointer_end - Past the last member pointer type found;
3881 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3882
Douglas Gregora11693b2008-11-12 17:17:38 +00003883 /// enumeration_begin - First enumeration type found;
3884 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3885
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003886 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003887 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003888
3889 iterator vector_begin() { return VectorTypes.begin(); }
3890 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00003891};
3892
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003893/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003894/// the set of pointer types along with any more-qualified variants of
3895/// that type. For example, if @p Ty is "int const *", this routine
3896/// will add "int const *", "int const volatile *", "int const
3897/// restrict *", and "int const volatile restrict *" to the set of
3898/// pointer types. Returns true if the add of @p Ty itself succeeded,
3899/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003900///
3901/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003902bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003903BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3904 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003905
Douglas Gregora11693b2008-11-12 17:17:38 +00003906 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003907 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003908 return false;
3909
John McCall8ccfcb52009-09-24 19:53:00 +00003910 const PointerType *PointerTy = Ty->getAs<PointerType>();
3911 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003912
John McCall8ccfcb52009-09-24 19:53:00 +00003913 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003914 // Don't add qualified variants of arrays. For one, they're not allowed
3915 // (the qualifier would sink to the element type), and for another, the
3916 // only overload situation where it matters is subscript or pointer +- int,
3917 // and those shouldn't have qualifier variants anyway.
3918 if (PointeeTy->isArrayType())
3919 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003920 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003921 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003922 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003923 bool hasVolatile = VisibleQuals.hasVolatile();
3924 bool hasRestrict = VisibleQuals.hasRestrict();
3925
John McCall8ccfcb52009-09-24 19:53:00 +00003926 // Iterate through all strict supersets of BaseCVR.
3927 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3928 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003929 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3930 // in the types.
3931 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3932 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003933 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3934 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003935 }
3936
3937 return true;
3938}
3939
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003940/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3941/// to the set of pointer types along with any more-qualified variants of
3942/// that type. For example, if @p Ty is "int const *", this routine
3943/// will add "int const *", "int const volatile *", "int const
3944/// restrict *", and "int const volatile restrict *" to the set of
3945/// pointer types. Returns true if the add of @p Ty itself succeeded,
3946/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003947///
3948/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003949bool
3950BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3951 QualType Ty) {
3952 // Insert this type.
3953 if (!MemberPointerTypes.insert(Ty))
3954 return false;
3955
John McCall8ccfcb52009-09-24 19:53:00 +00003956 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3957 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003958
John McCall8ccfcb52009-09-24 19:53:00 +00003959 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003960 // Don't add qualified variants of arrays. For one, they're not allowed
3961 // (the qualifier would sink to the element type), and for another, the
3962 // only overload situation where it matters is subscript or pointer +- int,
3963 // and those shouldn't have qualifier variants anyway.
3964 if (PointeeTy->isArrayType())
3965 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003966 const Type *ClassTy = PointerTy->getClass();
3967
3968 // Iterate through all strict supersets of the pointee type's CVR
3969 // qualifiers.
3970 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3971 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3972 if ((CVR | BaseCVR) != CVR) continue;
3973
3974 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3975 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003976 }
3977
3978 return true;
3979}
3980
Douglas Gregora11693b2008-11-12 17:17:38 +00003981/// AddTypesConvertedFrom - Add each of the types to which the type @p
3982/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003983/// primarily interested in pointer types and enumeration types. We also
3984/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003985/// AllowUserConversions is true if we should look at the conversion
3986/// functions of a class type, and AllowExplicitConversions if we
3987/// should also include the explicit conversion functions of a class
3988/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003989void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003990BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003991 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003992 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003993 bool AllowExplicitConversions,
3994 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003995 // Only deal with canonical types.
3996 Ty = Context.getCanonicalType(Ty);
3997
3998 // Look through reference types; they aren't part of the type of an
3999 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004000 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004001 Ty = RefTy->getPointeeType();
4002
4003 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004004 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004005
Sebastian Redl65ae2002009-11-05 16:36:20 +00004006 // If we're dealing with an array type, decay to the pointer.
4007 if (Ty->isArrayType())
4008 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4009
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004010 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004011 QualType PointeeTy = PointerTy->getPointeeType();
4012
4013 // Insert our type, and its more-qualified variants, into the set
4014 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004015 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004016 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004017 } else if (Ty->isMemberPointerType()) {
4018 // Member pointers are far easier, since the pointee can't be converted.
4019 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4020 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004021 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004022 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004023 } else if (Ty->isVectorType()) {
4024 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004025 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004026 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004027 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004028 // No conversion functions in incomplete types.
4029 return;
4030 }
Mike Stump11289f42009-09-09 15:08:12 +00004031
Douglas Gregora11693b2008-11-12 17:17:38 +00004032 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004033 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004034 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004035 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004036 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004037 NamedDecl *D = I.getDecl();
4038 if (isa<UsingShadowDecl>(D))
4039 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004040
Mike Stump11289f42009-09-09 15:08:12 +00004041 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004042 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004043 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004044 continue;
4045
John McCallda4458e2010-03-31 01:36:47 +00004046 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004047 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004048 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004049 VisibleQuals);
4050 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004051 }
4052 }
4053 }
4054}
4055
Douglas Gregor84605ae2009-08-24 13:43:27 +00004056/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4057/// the volatile- and non-volatile-qualified assignment operators for the
4058/// given type to the candidate set.
4059static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4060 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004061 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004062 unsigned NumArgs,
4063 OverloadCandidateSet &CandidateSet) {
4064 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004065
Douglas Gregor84605ae2009-08-24 13:43:27 +00004066 // T& operator=(T&, T)
4067 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4068 ParamTypes[1] = T;
4069 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4070 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004071
Douglas Gregor84605ae2009-08-24 13:43:27 +00004072 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4073 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004074 ParamTypes[0]
4075 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004076 ParamTypes[1] = T;
4077 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004078 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004079 }
4080}
Mike Stump11289f42009-09-09 15:08:12 +00004081
Sebastian Redl1054fae2009-10-25 17:03:50 +00004082/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4083/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004084static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4085 Qualifiers VRQuals;
4086 const RecordType *TyRec;
4087 if (const MemberPointerType *RHSMPType =
4088 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004089 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004090 else
4091 TyRec = ArgExpr->getType()->getAs<RecordType>();
4092 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004093 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004094 VRQuals.addVolatile();
4095 VRQuals.addRestrict();
4096 return VRQuals;
4097 }
4098
4099 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004100 if (!ClassDecl->hasDefinition())
4101 return VRQuals;
4102
John McCallad371252010-01-20 00:46:10 +00004103 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004104 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004105
John McCallad371252010-01-20 00:46:10 +00004106 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004107 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004108 NamedDecl *D = I.getDecl();
4109 if (isa<UsingShadowDecl>(D))
4110 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4111 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004112 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4113 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4114 CanTy = ResTypeRef->getPointeeType();
4115 // Need to go down the pointer/mempointer chain and add qualifiers
4116 // as see them.
4117 bool done = false;
4118 while (!done) {
4119 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4120 CanTy = ResTypePtr->getPointeeType();
4121 else if (const MemberPointerType *ResTypeMPtr =
4122 CanTy->getAs<MemberPointerType>())
4123 CanTy = ResTypeMPtr->getPointeeType();
4124 else
4125 done = true;
4126 if (CanTy.isVolatileQualified())
4127 VRQuals.addVolatile();
4128 if (CanTy.isRestrictQualified())
4129 VRQuals.addRestrict();
4130 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4131 return VRQuals;
4132 }
4133 }
4134 }
4135 return VRQuals;
4136}
4137
Douglas Gregord08452f2008-11-19 15:42:04 +00004138/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4139/// operator overloads to the candidate set (C++ [over.built]), based
4140/// on the operator @p Op and the arguments given. For example, if the
4141/// operator is a binary '+', this routine might add "int
4142/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004143void
Mike Stump11289f42009-09-09 15:08:12 +00004144Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004145 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004146 Expr **Args, unsigned NumArgs,
4147 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004148 // The set of "promoted arithmetic types", which are the arithmetic
4149 // types are that preserved by promotion (C++ [over.built]p2). Note
4150 // that the first few of these types are the promoted integral
4151 // types; these types need to be first.
4152 // FIXME: What about complex?
4153 const unsigned FirstIntegralType = 0;
4154 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004155 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004156 LastPromotedIntegralType = 13;
4157 const unsigned FirstPromotedArithmeticType = 7,
4158 LastPromotedArithmeticType = 16;
4159 const unsigned NumArithmeticTypes = 16;
4160 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004161 Context.BoolTy, Context.CharTy, Context.WCharTy,
4162// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004163 Context.SignedCharTy, Context.ShortTy,
4164 Context.UnsignedCharTy, Context.UnsignedShortTy,
4165 Context.IntTy, Context.LongTy, Context.LongLongTy,
4166 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4167 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4168 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004169 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4170 "Invalid first promoted integral type");
4171 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4172 == Context.UnsignedLongLongTy &&
4173 "Invalid last promoted integral type");
4174 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4175 "Invalid first promoted arithmetic type");
4176 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4177 == Context.LongDoubleTy &&
4178 "Invalid last promoted arithmetic type");
4179
Douglas Gregora11693b2008-11-12 17:17:38 +00004180 // Find all of the types that the arguments can convert to, but only
4181 // if the operator we're looking at has built-in operator candidates
4182 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004183 Qualifiers VisibleTypeConversionsQuals;
4184 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004185 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4186 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4187
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004188 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004189 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4190 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4191 OpLoc,
4192 true,
4193 (Op == OO_Exclaim ||
4194 Op == OO_AmpAmp ||
4195 Op == OO_PipePipe),
4196 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004197
4198 bool isComparison = false;
4199 switch (Op) {
4200 case OO_None:
4201 case NUM_OVERLOADED_OPERATORS:
4202 assert(false && "Expected an overloaded operator");
4203 break;
4204
Douglas Gregord08452f2008-11-19 15:42:04 +00004205 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004206 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004207 goto UnaryStar;
4208 else
4209 goto BinaryStar;
4210 break;
4211
4212 case OO_Plus: // '+' is either unary or binary
4213 if (NumArgs == 1)
4214 goto UnaryPlus;
4215 else
4216 goto BinaryPlus;
4217 break;
4218
4219 case OO_Minus: // '-' is either unary or binary
4220 if (NumArgs == 1)
4221 goto UnaryMinus;
4222 else
4223 goto BinaryMinus;
4224 break;
4225
4226 case OO_Amp: // '&' is either unary or binary
4227 if (NumArgs == 1)
4228 goto UnaryAmp;
4229 else
4230 goto BinaryAmp;
4231
4232 case OO_PlusPlus:
4233 case OO_MinusMinus:
4234 // C++ [over.built]p3:
4235 //
4236 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4237 // is either volatile or empty, there exist candidate operator
4238 // functions of the form
4239 //
4240 // VQ T& operator++(VQ T&);
4241 // T operator++(VQ T&, int);
4242 //
4243 // C++ [over.built]p4:
4244 //
4245 // For every pair (T, VQ), where T is an arithmetic type other
4246 // than bool, and VQ is either volatile or empty, there exist
4247 // candidate operator functions of the form
4248 //
4249 // VQ T& operator--(VQ T&);
4250 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004251 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004252 Arith < NumArithmeticTypes; ++Arith) {
4253 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004254 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004255 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004256
4257 // Non-volatile version.
4258 if (NumArgs == 1)
4259 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4260 else
4261 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004262 // heuristic to reduce number of builtin candidates in the set.
4263 // Add volatile version only if there are conversions to a volatile type.
4264 if (VisibleTypeConversionsQuals.hasVolatile()) {
4265 // Volatile version
4266 ParamTypes[0]
4267 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4268 if (NumArgs == 1)
4269 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4270 else
4271 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4272 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004273 }
4274
4275 // C++ [over.built]p5:
4276 //
4277 // For every pair (T, VQ), where T is a cv-qualified or
4278 // cv-unqualified object type, and VQ is either volatile or
4279 // empty, there exist candidate operator functions of the form
4280 //
4281 // T*VQ& operator++(T*VQ&);
4282 // T*VQ& operator--(T*VQ&);
4283 // T* operator++(T*VQ&, int);
4284 // T* operator--(T*VQ&, int);
4285 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4286 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4287 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004288 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004289 continue;
4290
Mike Stump11289f42009-09-09 15:08:12 +00004291 QualType ParamTypes[2] = {
4292 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004293 };
Mike Stump11289f42009-09-09 15:08:12 +00004294
Douglas Gregord08452f2008-11-19 15:42:04 +00004295 // Without volatile
4296 if (NumArgs == 1)
4297 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4298 else
4299 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4300
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004301 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4302 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004303 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004304 ParamTypes[0]
4305 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004306 if (NumArgs == 1)
4307 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4308 else
4309 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4310 }
4311 }
4312 break;
4313
4314 UnaryStar:
4315 // C++ [over.built]p6:
4316 // For every cv-qualified or cv-unqualified object type T, there
4317 // exist candidate operator functions of the form
4318 //
4319 // T& operator*(T*);
4320 //
4321 // C++ [over.built]p7:
4322 // For every function type T, there exist candidate operator
4323 // functions of the form
4324 // T& operator*(T*);
4325 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4326 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4327 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004328 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004329 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004330 &ParamTy, Args, 1, CandidateSet);
4331 }
4332 break;
4333
4334 UnaryPlus:
4335 // C++ [over.built]p8:
4336 // For every type T, there exist candidate operator functions of
4337 // the form
4338 //
4339 // T* operator+(T*);
4340 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4341 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4342 QualType ParamTy = *Ptr;
4343 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4344 }
Mike Stump11289f42009-09-09 15:08:12 +00004345
Douglas Gregord08452f2008-11-19 15:42:04 +00004346 // Fall through
4347
4348 UnaryMinus:
4349 // C++ [over.built]p9:
4350 // For every promoted arithmetic type T, there exist candidate
4351 // operator functions of the form
4352 //
4353 // T operator+(T);
4354 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004355 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004356 Arith < LastPromotedArithmeticType; ++Arith) {
4357 QualType ArithTy = ArithmeticTypes[Arith];
4358 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4359 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004360
4361 // Extension: We also add these operators for vector types.
4362 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4363 VecEnd = CandidateTypes.vector_end();
4364 Vec != VecEnd; ++Vec) {
4365 QualType VecTy = *Vec;
4366 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4367 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004368 break;
4369
4370 case OO_Tilde:
4371 // C++ [over.built]p10:
4372 // For every promoted integral type T, there exist candidate
4373 // operator functions of the form
4374 //
4375 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004376 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004377 Int < LastPromotedIntegralType; ++Int) {
4378 QualType IntTy = ArithmeticTypes[Int];
4379 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4380 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004381
4382 // Extension: We also add this operator for vector types.
4383 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4384 VecEnd = CandidateTypes.vector_end();
4385 Vec != VecEnd; ++Vec) {
4386 QualType VecTy = *Vec;
4387 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4388 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004389 break;
4390
Douglas Gregora11693b2008-11-12 17:17:38 +00004391 case OO_New:
4392 case OO_Delete:
4393 case OO_Array_New:
4394 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004395 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004396 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004397 break;
4398
4399 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004400 UnaryAmp:
4401 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004402 // C++ [over.match.oper]p3:
4403 // -- For the operator ',', the unary operator '&', or the
4404 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004405 break;
4406
Douglas Gregor84605ae2009-08-24 13:43:27 +00004407 case OO_EqualEqual:
4408 case OO_ExclaimEqual:
4409 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004410 // For every pointer to member type T, there exist candidate operator
4411 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004412 //
4413 // bool operator==(T,T);
4414 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004415 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004416 MemPtr = CandidateTypes.member_pointer_begin(),
4417 MemPtrEnd = CandidateTypes.member_pointer_end();
4418 MemPtr != MemPtrEnd;
4419 ++MemPtr) {
4420 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4421 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4422 }
Mike Stump11289f42009-09-09 15:08:12 +00004423
Douglas Gregor84605ae2009-08-24 13:43:27 +00004424 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004425
Douglas Gregora11693b2008-11-12 17:17:38 +00004426 case OO_Less:
4427 case OO_Greater:
4428 case OO_LessEqual:
4429 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004430 // C++ [over.built]p15:
4431 //
4432 // For every pointer or enumeration type T, there exist
4433 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004434 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004435 // bool operator<(T, T);
4436 // bool operator>(T, T);
4437 // bool operator<=(T, T);
4438 // bool operator>=(T, T);
4439 // bool operator==(T, T);
4440 // bool operator!=(T, T);
4441 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4442 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4443 QualType ParamTypes[2] = { *Ptr, *Ptr };
4444 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4445 }
Mike Stump11289f42009-09-09 15:08:12 +00004446 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004447 = CandidateTypes.enumeration_begin();
4448 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4449 QualType ParamTypes[2] = { *Enum, *Enum };
4450 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4451 }
4452
4453 // Fall through.
4454 isComparison = true;
4455
Douglas Gregord08452f2008-11-19 15:42:04 +00004456 BinaryPlus:
4457 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004458 if (!isComparison) {
4459 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4460
4461 // C++ [over.built]p13:
4462 //
4463 // For every cv-qualified or cv-unqualified object type T
4464 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004465 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004466 // T* operator+(T*, ptrdiff_t);
4467 // T& operator[](T*, ptrdiff_t); [BELOW]
4468 // T* operator-(T*, ptrdiff_t);
4469 // T* operator+(ptrdiff_t, T*);
4470 // T& operator[](ptrdiff_t, T*); [BELOW]
4471 //
4472 // C++ [over.built]p14:
4473 //
4474 // For every T, where T is a pointer to object type, there
4475 // exist candidate operator functions of the form
4476 //
4477 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004478 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004479 = CandidateTypes.pointer_begin();
4480 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4481 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4482
4483 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4484 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4485
4486 if (Op == OO_Plus) {
4487 // T* operator+(ptrdiff_t, T*);
4488 ParamTypes[0] = ParamTypes[1];
4489 ParamTypes[1] = *Ptr;
4490 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4491 } else {
4492 // ptrdiff_t operator-(T, T);
4493 ParamTypes[1] = *Ptr;
4494 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4495 Args, 2, CandidateSet);
4496 }
4497 }
4498 }
4499 // Fall through
4500
Douglas Gregora11693b2008-11-12 17:17:38 +00004501 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004502 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004503 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004504 // C++ [over.built]p12:
4505 //
4506 // For every pair of promoted arithmetic types L and R, there
4507 // exist candidate operator functions of the form
4508 //
4509 // LR operator*(L, R);
4510 // LR operator/(L, R);
4511 // LR operator+(L, R);
4512 // LR operator-(L, R);
4513 // bool operator<(L, R);
4514 // bool operator>(L, R);
4515 // bool operator<=(L, R);
4516 // bool operator>=(L, R);
4517 // bool operator==(L, R);
4518 // bool operator!=(L, R);
4519 //
4520 // where LR is the result of the usual arithmetic conversions
4521 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004522 //
4523 // C++ [over.built]p24:
4524 //
4525 // For every pair of promoted arithmetic types L and R, there exist
4526 // candidate operator functions of the form
4527 //
4528 // LR operator?(bool, L, R);
4529 //
4530 // where LR is the result of the usual arithmetic conversions
4531 // between types L and R.
4532 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004533 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004534 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004535 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004536 Right < LastPromotedArithmeticType; ++Right) {
4537 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004538 QualType Result
4539 = isComparison
4540 ? Context.BoolTy
4541 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004542 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4543 }
4544 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004545
4546 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4547 // conditional operator for vector types.
4548 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4549 Vec1End = CandidateTypes.vector_end();
4550 Vec1 != Vec1End; ++Vec1)
4551 for (BuiltinCandidateTypeSet::iterator
4552 Vec2 = CandidateTypes.vector_begin(),
4553 Vec2End = CandidateTypes.vector_end();
4554 Vec2 != Vec2End; ++Vec2) {
4555 QualType LandR[2] = { *Vec1, *Vec2 };
4556 QualType Result;
4557 if (isComparison)
4558 Result = Context.BoolTy;
4559 else {
4560 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4561 Result = *Vec1;
4562 else
4563 Result = *Vec2;
4564 }
4565
4566 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4567 }
4568
Douglas Gregora11693b2008-11-12 17:17:38 +00004569 break;
4570
4571 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004572 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004573 case OO_Caret:
4574 case OO_Pipe:
4575 case OO_LessLess:
4576 case OO_GreaterGreater:
4577 // C++ [over.built]p17:
4578 //
4579 // For every pair of promoted integral types L and R, there
4580 // exist candidate operator functions of the form
4581 //
4582 // LR operator%(L, R);
4583 // LR operator&(L, R);
4584 // LR operator^(L, R);
4585 // LR operator|(L, R);
4586 // L operator<<(L, R);
4587 // L operator>>(L, R);
4588 //
4589 // where LR is the result of the usual arithmetic conversions
4590 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004591 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004592 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004593 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004594 Right < LastPromotedIntegralType; ++Right) {
4595 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4596 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4597 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004598 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004599 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4600 }
4601 }
4602 break;
4603
4604 case OO_Equal:
4605 // C++ [over.built]p20:
4606 //
4607 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004608 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004609 // empty, there exist candidate operator functions of the form
4610 //
4611 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004612 for (BuiltinCandidateTypeSet::iterator
4613 Enum = CandidateTypes.enumeration_begin(),
4614 EnumEnd = CandidateTypes.enumeration_end();
4615 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004616 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004617 CandidateSet);
4618 for (BuiltinCandidateTypeSet::iterator
4619 MemPtr = CandidateTypes.member_pointer_begin(),
4620 MemPtrEnd = CandidateTypes.member_pointer_end();
4621 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004622 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004623 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004624
4625 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004626
4627 case OO_PlusEqual:
4628 case OO_MinusEqual:
4629 // C++ [over.built]p19:
4630 //
4631 // For every pair (T, VQ), where T is any type and VQ is either
4632 // volatile or empty, there exist candidate operator functions
4633 // of the form
4634 //
4635 // T*VQ& operator=(T*VQ&, T*);
4636 //
4637 // C++ [over.built]p21:
4638 //
4639 // For every pair (T, VQ), where T is a cv-qualified or
4640 // cv-unqualified object type and VQ is either volatile or
4641 // empty, there exist candidate operator functions of the form
4642 //
4643 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4644 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4645 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4646 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4647 QualType ParamTypes[2];
4648 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4649
4650 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004651 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004652 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4653 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004654
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004655 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4656 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004657 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004658 ParamTypes[0]
4659 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004660 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4661 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004662 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004663 }
4664 // Fall through.
4665
4666 case OO_StarEqual:
4667 case OO_SlashEqual:
4668 // C++ [over.built]p18:
4669 //
4670 // For every triple (L, VQ, R), where L is an arithmetic type,
4671 // VQ is either volatile or empty, and R is a promoted
4672 // arithmetic type, there exist candidate operator functions of
4673 // the form
4674 //
4675 // VQ L& operator=(VQ L&, R);
4676 // VQ L& operator*=(VQ L&, R);
4677 // VQ L& operator/=(VQ L&, R);
4678 // VQ L& operator+=(VQ L&, R);
4679 // VQ L& operator-=(VQ L&, R);
4680 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004681 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004682 Right < LastPromotedArithmeticType; ++Right) {
4683 QualType ParamTypes[2];
4684 ParamTypes[1] = ArithmeticTypes[Right];
4685
4686 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004687 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004688 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4689 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004690
4691 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004692 if (VisibleTypeConversionsQuals.hasVolatile()) {
4693 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4694 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4695 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4696 /*IsAssigmentOperator=*/Op == OO_Equal);
4697 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004698 }
4699 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004700
4701 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4702 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4703 Vec1End = CandidateTypes.vector_end();
4704 Vec1 != Vec1End; ++Vec1)
4705 for (BuiltinCandidateTypeSet::iterator
4706 Vec2 = CandidateTypes.vector_begin(),
4707 Vec2End = CandidateTypes.vector_end();
4708 Vec2 != Vec2End; ++Vec2) {
4709 QualType ParamTypes[2];
4710 ParamTypes[1] = *Vec2;
4711 // Add this built-in operator as a candidate (VQ is empty).
4712 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4713 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4714 /*IsAssigmentOperator=*/Op == OO_Equal);
4715
4716 // Add this built-in operator as a candidate (VQ is 'volatile').
4717 if (VisibleTypeConversionsQuals.hasVolatile()) {
4718 ParamTypes[0] = Context.getVolatileType(*Vec1);
4719 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4720 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4721 /*IsAssigmentOperator=*/Op == OO_Equal);
4722 }
4723 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004724 break;
4725
4726 case OO_PercentEqual:
4727 case OO_LessLessEqual:
4728 case OO_GreaterGreaterEqual:
4729 case OO_AmpEqual:
4730 case OO_CaretEqual:
4731 case OO_PipeEqual:
4732 // C++ [over.built]p22:
4733 //
4734 // For every triple (L, VQ, R), where L is an integral type, VQ
4735 // is either volatile or empty, and R is a promoted integral
4736 // type, there exist candidate operator functions of the form
4737 //
4738 // VQ L& operator%=(VQ L&, R);
4739 // VQ L& operator<<=(VQ L&, R);
4740 // VQ L& operator>>=(VQ L&, R);
4741 // VQ L& operator&=(VQ L&, R);
4742 // VQ L& operator^=(VQ L&, R);
4743 // VQ L& operator|=(VQ L&, R);
4744 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004745 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004746 Right < LastPromotedIntegralType; ++Right) {
4747 QualType ParamTypes[2];
4748 ParamTypes[1] = ArithmeticTypes[Right];
4749
4750 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004751 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004752 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004753 if (VisibleTypeConversionsQuals.hasVolatile()) {
4754 // Add this built-in operator as a candidate (VQ is 'volatile').
4755 ParamTypes[0] = ArithmeticTypes[Left];
4756 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4757 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4758 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4759 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004760 }
4761 }
4762 break;
4763
Douglas Gregord08452f2008-11-19 15:42:04 +00004764 case OO_Exclaim: {
4765 // C++ [over.operator]p23:
4766 //
4767 // There also exist candidate operator functions of the form
4768 //
Mike Stump11289f42009-09-09 15:08:12 +00004769 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004770 // bool operator&&(bool, bool); [BELOW]
4771 // bool operator||(bool, bool); [BELOW]
4772 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004773 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4774 /*IsAssignmentOperator=*/false,
4775 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004776 break;
4777 }
4778
Douglas Gregora11693b2008-11-12 17:17:38 +00004779 case OO_AmpAmp:
4780 case OO_PipePipe: {
4781 // C++ [over.operator]p23:
4782 //
4783 // There also exist candidate operator functions of the form
4784 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004785 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004786 // bool operator&&(bool, bool);
4787 // bool operator||(bool, bool);
4788 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004789 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4790 /*IsAssignmentOperator=*/false,
4791 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004792 break;
4793 }
4794
4795 case OO_Subscript:
4796 // C++ [over.built]p13:
4797 //
4798 // For every cv-qualified or cv-unqualified object type T there
4799 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004800 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004801 // T* operator+(T*, ptrdiff_t); [ABOVE]
4802 // T& operator[](T*, ptrdiff_t);
4803 // T* operator-(T*, ptrdiff_t); [ABOVE]
4804 // T* operator+(ptrdiff_t, T*); [ABOVE]
4805 // T& operator[](ptrdiff_t, T*);
4806 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4807 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4808 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004809 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004810 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004811
4812 // T& operator[](T*, ptrdiff_t)
4813 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4814
4815 // T& operator[](ptrdiff_t, T*);
4816 ParamTypes[0] = ParamTypes[1];
4817 ParamTypes[1] = *Ptr;
4818 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004819 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004820 break;
4821
4822 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004823 // C++ [over.built]p11:
4824 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4825 // C1 is the same type as C2 or is a derived class of C2, T is an object
4826 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4827 // there exist candidate operator functions of the form
4828 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4829 // where CV12 is the union of CV1 and CV2.
4830 {
4831 for (BuiltinCandidateTypeSet::iterator Ptr =
4832 CandidateTypes.pointer_begin();
4833 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4834 QualType C1Ty = (*Ptr);
4835 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004836 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004837 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004838 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004839 if (!isa<RecordType>(C1))
4840 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004841 // heuristic to reduce number of builtin candidates in the set.
4842 // Add volatile/restrict version only if there are conversions to a
4843 // volatile/restrict type.
4844 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4845 continue;
4846 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4847 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004848 }
4849 for (BuiltinCandidateTypeSet::iterator
4850 MemPtr = CandidateTypes.member_pointer_begin(),
4851 MemPtrEnd = CandidateTypes.member_pointer_end();
4852 MemPtr != MemPtrEnd; ++MemPtr) {
4853 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4854 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004855 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004856 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4857 break;
4858 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4859 // build CV12 T&
4860 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004861 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4862 T.isVolatileQualified())
4863 continue;
4864 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4865 T.isRestrictQualified())
4866 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004867 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004868 QualType ResultTy = Context.getLValueReferenceType(T);
4869 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4870 }
4871 }
4872 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004873 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004874
4875 case OO_Conditional:
4876 // Note that we don't consider the first argument, since it has been
4877 // contextually converted to bool long ago. The candidates below are
4878 // therefore added as binary.
4879 //
4880 // C++ [over.built]p24:
4881 // For every type T, where T is a pointer or pointer-to-member type,
4882 // there exist candidate operator functions of the form
4883 //
4884 // T operator?(bool, T, T);
4885 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004886 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4887 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4888 QualType ParamTypes[2] = { *Ptr, *Ptr };
4889 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4890 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004891 for (BuiltinCandidateTypeSet::iterator Ptr =
4892 CandidateTypes.member_pointer_begin(),
4893 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4894 QualType ParamTypes[2] = { *Ptr, *Ptr };
4895 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4896 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004897 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004898 }
4899}
4900
Douglas Gregore254f902009-02-04 00:32:51 +00004901/// \brief Add function candidates found via argument-dependent lookup
4902/// to the set of overloading candidates.
4903///
4904/// This routine performs argument-dependent name lookup based on the
4905/// given function name (which may also be an operator name) and adds
4906/// all of the overload candidates found by ADL to the overload
4907/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004908void
Douglas Gregore254f902009-02-04 00:32:51 +00004909Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004910 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004911 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004912 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004913 OverloadCandidateSet& CandidateSet,
4914 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004915 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004916
John McCall91f61fc2010-01-26 06:04:06 +00004917 // FIXME: This approach for uniquing ADL results (and removing
4918 // redundant candidates from the set) relies on pointer-equality,
4919 // which means we need to key off the canonical decl. However,
4920 // always going back to the canonical decl might not get us the
4921 // right set of default arguments. What default arguments are
4922 // we supposed to consider on ADL candidates, anyway?
4923
Douglas Gregorcabea402009-09-22 15:41:20 +00004924 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004925 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004926
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004927 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004928 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4929 CandEnd = CandidateSet.end();
4930 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004931 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004932 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004933 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004934 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004935 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004936
4937 // For each of the ADL candidates we found, add it to the overload
4938 // set.
John McCall8fe68082010-01-26 07:16:45 +00004939 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004940 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004941 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004942 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004943 continue;
4944
John McCalla0296f72010-03-19 07:35:19 +00004945 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004946 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004947 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004948 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004949 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004950 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004951 }
Douglas Gregore254f902009-02-04 00:32:51 +00004952}
4953
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004954/// isBetterOverloadCandidate - Determines whether the first overload
4955/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004956bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004957Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004958 const OverloadCandidate& Cand2,
4959 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004960 // Define viable functions to be better candidates than non-viable
4961 // functions.
4962 if (!Cand2.Viable)
4963 return Cand1.Viable;
4964 else if (!Cand1.Viable)
4965 return false;
4966
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004967 // C++ [over.match.best]p1:
4968 //
4969 // -- if F is a static member function, ICS1(F) is defined such
4970 // that ICS1(F) is neither better nor worse than ICS1(G) for
4971 // any function G, and, symmetrically, ICS1(G) is neither
4972 // better nor worse than ICS1(F).
4973 unsigned StartArg = 0;
4974 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4975 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004976
Douglas Gregord3cb3562009-07-07 23:38:56 +00004977 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004978 // A viable function F1 is defined to be a better function than another
4979 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004980 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004981 unsigned NumArgs = Cand1.Conversions.size();
4982 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4983 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004984 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004985 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4986 Cand2.Conversions[ArgIdx])) {
4987 case ImplicitConversionSequence::Better:
4988 // Cand1 has a better conversion sequence.
4989 HasBetterConversion = true;
4990 break;
4991
4992 case ImplicitConversionSequence::Worse:
4993 // Cand1 can't be better than Cand2.
4994 return false;
4995
4996 case ImplicitConversionSequence::Indistinguishable:
4997 // Do nothing.
4998 break;
4999 }
5000 }
5001
Mike Stump11289f42009-09-09 15:08:12 +00005002 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005003 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005004 if (HasBetterConversion)
5005 return true;
5006
Mike Stump11289f42009-09-09 15:08:12 +00005007 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005008 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005009 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005010 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5011 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005012
5013 // -- F1 and F2 are function template specializations, and the function
5014 // template for F1 is more specialized than the template for F2
5015 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005016 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005017 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5018 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005019 if (FunctionTemplateDecl *BetterTemplate
5020 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5021 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005022 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005023 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5024 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005025 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005026
Douglas Gregora1f013e2008-11-07 22:36:19 +00005027 // -- the context is an initialization by user-defined conversion
5028 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5029 // from the return type of F1 to the destination type (i.e.,
5030 // the type of the entity being initialized) is a better
5031 // conversion sequence than the standard conversion sequence
5032 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005033 if (Cand1.Function && Cand2.Function &&
5034 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005035 isa<CXXConversionDecl>(Cand2.Function)) {
5036 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5037 Cand2.FinalConversion)) {
5038 case ImplicitConversionSequence::Better:
5039 // Cand1 has a better conversion sequence.
5040 return true;
5041
5042 case ImplicitConversionSequence::Worse:
5043 // Cand1 can't be better than Cand2.
5044 return false;
5045
5046 case ImplicitConversionSequence::Indistinguishable:
5047 // Do nothing
5048 break;
5049 }
5050 }
5051
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005052 return false;
5053}
5054
Mike Stump11289f42009-09-09 15:08:12 +00005055/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005056/// within an overload candidate set.
5057///
5058/// \param CandidateSet the set of candidate functions.
5059///
5060/// \param Loc the location of the function name (or operator symbol) for
5061/// which overload resolution occurs.
5062///
Mike Stump11289f42009-09-09 15:08:12 +00005063/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005064/// function, Best points to the candidate function found.
5065///
5066/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005067OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5068 SourceLocation Loc,
5069 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005070 // Find the best viable function.
5071 Best = CandidateSet.end();
5072 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5073 Cand != CandidateSet.end(); ++Cand) {
5074 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005075 if (Best == CandidateSet.end() ||
5076 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005077 Best = Cand;
5078 }
5079 }
5080
5081 // If we didn't find any viable functions, abort.
5082 if (Best == CandidateSet.end())
5083 return OR_No_Viable_Function;
5084
5085 // Make sure that this function is better than every other viable
5086 // function. If not, we have an ambiguity.
5087 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5088 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005089 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005090 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005091 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005092 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005093 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005094 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005095 }
Mike Stump11289f42009-09-09 15:08:12 +00005096
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005097 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005098 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005099 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005100 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005101 return OR_Deleted;
5102
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005103 // C++ [basic.def.odr]p2:
5104 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005105 // when referred to from a potentially-evaluated expression. [Note: this
5106 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005107 // (clause 13), user-defined conversions (12.3.2), allocation function for
5108 // placement new (5.3.4), as well as non-default initialization (8.5).
5109 if (Best->Function)
5110 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005111 return OR_Success;
5112}
5113
John McCall53262c92010-01-12 02:15:36 +00005114namespace {
5115
5116enum OverloadCandidateKind {
5117 oc_function,
5118 oc_method,
5119 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005120 oc_function_template,
5121 oc_method_template,
5122 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005123 oc_implicit_default_constructor,
5124 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005125 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005126};
5127
John McCalle1ac8d12010-01-13 00:25:19 +00005128OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5129 FunctionDecl *Fn,
5130 std::string &Description) {
5131 bool isTemplate = false;
5132
5133 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5134 isTemplate = true;
5135 Description = S.getTemplateArgumentBindingsText(
5136 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5137 }
John McCallfd0b2f82010-01-06 09:43:14 +00005138
5139 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005140 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005141 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005142
John McCall53262c92010-01-12 02:15:36 +00005143 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5144 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005145 }
5146
5147 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5148 // This actually gets spelled 'candidate function' for now, but
5149 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005150 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005151 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005152
5153 assert(Meth->isCopyAssignment()
5154 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005155 return oc_implicit_copy_assignment;
5156 }
5157
John McCalle1ac8d12010-01-13 00:25:19 +00005158 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005159}
5160
5161} // end anonymous namespace
5162
5163// Notes the location of an overload candidate.
5164void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005165 std::string FnDesc;
5166 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5167 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5168 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005169}
5170
John McCall0d1da222010-01-12 00:44:57 +00005171/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5172/// "lead" diagnostic; it will be given two arguments, the source and
5173/// target types of the conversion.
5174void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5175 SourceLocation CaretLoc,
5176 const PartialDiagnostic &PDiag) {
5177 Diag(CaretLoc, PDiag)
5178 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5179 for (AmbiguousConversionSequence::const_iterator
5180 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5181 NoteOverloadCandidate(*I);
5182 }
John McCall12f97bc2010-01-08 04:41:39 +00005183}
5184
John McCall0d1da222010-01-12 00:44:57 +00005185namespace {
5186
John McCall6a61b522010-01-13 09:16:55 +00005187void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5188 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5189 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005190 assert(Cand->Function && "for now, candidate must be a function");
5191 FunctionDecl *Fn = Cand->Function;
5192
5193 // There's a conversion slot for the object argument if this is a
5194 // non-constructor method. Note that 'I' corresponds the
5195 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005196 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005197 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005198 if (I == 0)
5199 isObjectArgument = true;
5200 else
5201 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005202 }
5203
John McCalle1ac8d12010-01-13 00:25:19 +00005204 std::string FnDesc;
5205 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5206
John McCall6a61b522010-01-13 09:16:55 +00005207 Expr *FromExpr = Conv.Bad.FromExpr;
5208 QualType FromTy = Conv.Bad.getFromType();
5209 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005210
John McCallfb7ad0f2010-02-02 02:42:52 +00005211 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005212 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005213 Expr *E = FromExpr->IgnoreParens();
5214 if (isa<UnaryOperator>(E))
5215 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005216 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005217
5218 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5219 << (unsigned) FnKind << FnDesc
5220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5221 << ToTy << Name << I+1;
5222 return;
5223 }
5224
John McCall6d174642010-01-23 08:10:49 +00005225 // Do some hand-waving analysis to see if the non-viability is due
5226 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005227 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5228 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5229 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5230 CToTy = RT->getPointeeType();
5231 else {
5232 // TODO: detect and diagnose the full richness of const mismatches.
5233 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5234 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5235 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5236 }
5237
5238 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5239 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5240 // It is dumb that we have to do this here.
5241 while (isa<ArrayType>(CFromTy))
5242 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5243 while (isa<ArrayType>(CToTy))
5244 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5245
5246 Qualifiers FromQs = CFromTy.getQualifiers();
5247 Qualifiers ToQs = CToTy.getQualifiers();
5248
5249 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5251 << (unsigned) FnKind << FnDesc
5252 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5253 << FromTy
5254 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5255 << (unsigned) isObjectArgument << I+1;
5256 return;
5257 }
5258
5259 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5260 assert(CVR && "unexpected qualifiers mismatch");
5261
5262 if (isObjectArgument) {
5263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5264 << (unsigned) FnKind << FnDesc
5265 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5266 << FromTy << (CVR - 1);
5267 } else {
5268 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5269 << (unsigned) FnKind << FnDesc
5270 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5271 << FromTy << (CVR - 1) << I+1;
5272 }
5273 return;
5274 }
5275
John McCall6d174642010-01-23 08:10:49 +00005276 // Diagnose references or pointers to incomplete types differently,
5277 // since it's far from impossible that the incompleteness triggered
5278 // the failure.
5279 QualType TempFromTy = FromTy.getNonReferenceType();
5280 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5281 TempFromTy = PTy->getPointeeType();
5282 if (TempFromTy->isIncompleteType()) {
5283 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5284 << (unsigned) FnKind << FnDesc
5285 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5286 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5287 return;
5288 }
5289
John McCall47000992010-01-14 03:28:57 +00005290 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5292 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005293 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005294 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005295}
5296
5297void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5298 unsigned NumFormalArgs) {
5299 // TODO: treat calls to a missing default constructor as a special case
5300
5301 FunctionDecl *Fn = Cand->Function;
5302 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5303
5304 unsigned MinParams = Fn->getMinRequiredArguments();
5305
5306 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005307 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005308 unsigned mode, modeCount;
5309 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005310 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5311 (Cand->FailureKind == ovl_fail_bad_deduction &&
5312 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005313 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5314 mode = 0; // "at least"
5315 else
5316 mode = 2; // "exactly"
5317 modeCount = MinParams;
5318 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005319 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5320 (Cand->FailureKind == ovl_fail_bad_deduction &&
5321 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005322 if (MinParams != FnTy->getNumArgs())
5323 mode = 1; // "at most"
5324 else
5325 mode = 2; // "exactly"
5326 modeCount = FnTy->getNumArgs();
5327 }
5328
5329 std::string Description;
5330 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5331
5332 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005333 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5334 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005335}
5336
John McCall8b9ed552010-02-01 18:53:26 +00005337/// Diagnose a failed template-argument deduction.
5338void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5339 Expr **Args, unsigned NumArgs) {
5340 FunctionDecl *Fn = Cand->Function; // pattern
5341
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005342 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005343 NamedDecl *ParamD;
5344 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5345 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5346 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005347 switch (Cand->DeductionFailure.Result) {
5348 case Sema::TDK_Success:
5349 llvm_unreachable("TDK_success while diagnosing bad deduction");
5350
5351 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005352 assert(ParamD && "no parameter found for incomplete deduction result");
5353 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5354 << ParamD->getDeclName();
5355 return;
5356 }
5357
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005358 case Sema::TDK_Inconsistent:
5359 case Sema::TDK_InconsistentQuals: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005360 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005361 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005362 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005363 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005364 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005365 which = 1;
5366 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005367 which = 2;
5368 }
5369
5370 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5371 << which << ParamD->getDeclName()
5372 << *Cand->DeductionFailure.getFirstArg()
5373 << *Cand->DeductionFailure.getSecondArg();
5374 return;
5375 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005376
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005377 case Sema::TDK_InvalidExplicitArguments:
5378 assert(ParamD && "no parameter found for invalid explicit arguments");
5379 if (ParamD->getDeclName())
5380 S.Diag(Fn->getLocation(),
5381 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5382 << ParamD->getDeclName();
5383 else {
5384 int index = 0;
5385 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5386 index = TTP->getIndex();
5387 else if (NonTypeTemplateParmDecl *NTTP
5388 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5389 index = NTTP->getIndex();
5390 else
5391 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5392 S.Diag(Fn->getLocation(),
5393 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5394 << (index + 1);
5395 }
5396 return;
5397
Douglas Gregor02eb4832010-05-08 18:13:28 +00005398 case Sema::TDK_TooManyArguments:
5399 case Sema::TDK_TooFewArguments:
5400 DiagnoseArityMismatch(S, Cand, NumArgs);
5401 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005402
5403 case Sema::TDK_InstantiationDepth:
5404 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5405 return;
5406
5407 case Sema::TDK_SubstitutionFailure: {
5408 std::string ArgString;
5409 if (TemplateArgumentList *Args
5410 = Cand->DeductionFailure.getTemplateArgumentList())
5411 ArgString = S.getTemplateArgumentBindingsText(
5412 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5413 *Args);
5414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5415 << ArgString;
5416 return;
5417 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005418
John McCall8b9ed552010-02-01 18:53:26 +00005419 // TODO: diagnose these individually, then kill off
5420 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005421 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005422 case Sema::TDK_FailedOverloadResolution:
5423 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5424 return;
5425 }
5426}
5427
5428/// Generates a 'note' diagnostic for an overload candidate. We've
5429/// already generated a primary error at the call site.
5430///
5431/// It really does need to be a single diagnostic with its caret
5432/// pointed at the candidate declaration. Yes, this creates some
5433/// major challenges of technical writing. Yes, this makes pointing
5434/// out problems with specific arguments quite awkward. It's still
5435/// better than generating twenty screens of text for every failed
5436/// overload.
5437///
5438/// It would be great to be able to express per-candidate problems
5439/// more richly for those diagnostic clients that cared, but we'd
5440/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005441void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5442 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005443 FunctionDecl *Fn = Cand->Function;
5444
John McCall12f97bc2010-01-08 04:41:39 +00005445 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005446 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005447 std::string FnDesc;
5448 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005449
5450 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005451 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005452 return;
John McCall12f97bc2010-01-08 04:41:39 +00005453 }
5454
John McCalle1ac8d12010-01-13 00:25:19 +00005455 // We don't really have anything else to say about viable candidates.
5456 if (Cand->Viable) {
5457 S.NoteOverloadCandidate(Fn);
5458 return;
5459 }
John McCall0d1da222010-01-12 00:44:57 +00005460
John McCall6a61b522010-01-13 09:16:55 +00005461 switch (Cand->FailureKind) {
5462 case ovl_fail_too_many_arguments:
5463 case ovl_fail_too_few_arguments:
5464 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005465
John McCall6a61b522010-01-13 09:16:55 +00005466 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005467 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5468
John McCallfe796dd2010-01-23 05:17:32 +00005469 case ovl_fail_trivial_conversion:
5470 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005471 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005472 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005473
John McCall65eb8792010-02-25 01:37:24 +00005474 case ovl_fail_bad_conversion: {
5475 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5476 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005477 if (Cand->Conversions[I].isBad())
5478 return DiagnoseBadConversion(S, Cand, I);
5479
5480 // FIXME: this currently happens when we're called from SemaInit
5481 // when user-conversion overload fails. Figure out how to handle
5482 // those conditions and diagnose them well.
5483 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005484 }
John McCall65eb8792010-02-25 01:37:24 +00005485 }
John McCalld3224162010-01-08 00:58:21 +00005486}
5487
5488void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5489 // Desugar the type of the surrogate down to a function type,
5490 // retaining as many typedefs as possible while still showing
5491 // the function type (and, therefore, its parameter types).
5492 QualType FnType = Cand->Surrogate->getConversionType();
5493 bool isLValueReference = false;
5494 bool isRValueReference = false;
5495 bool isPointer = false;
5496 if (const LValueReferenceType *FnTypeRef =
5497 FnType->getAs<LValueReferenceType>()) {
5498 FnType = FnTypeRef->getPointeeType();
5499 isLValueReference = true;
5500 } else if (const RValueReferenceType *FnTypeRef =
5501 FnType->getAs<RValueReferenceType>()) {
5502 FnType = FnTypeRef->getPointeeType();
5503 isRValueReference = true;
5504 }
5505 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5506 FnType = FnTypePtr->getPointeeType();
5507 isPointer = true;
5508 }
5509 // Desugar down to a function type.
5510 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5511 // Reconstruct the pointer/reference as appropriate.
5512 if (isPointer) FnType = S.Context.getPointerType(FnType);
5513 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5514 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5515
5516 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5517 << FnType;
5518}
5519
5520void NoteBuiltinOperatorCandidate(Sema &S,
5521 const char *Opc,
5522 SourceLocation OpLoc,
5523 OverloadCandidate *Cand) {
5524 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5525 std::string TypeStr("operator");
5526 TypeStr += Opc;
5527 TypeStr += "(";
5528 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5529 if (Cand->Conversions.size() == 1) {
5530 TypeStr += ")";
5531 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5532 } else {
5533 TypeStr += ", ";
5534 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5535 TypeStr += ")";
5536 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5537 }
5538}
5539
5540void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5541 OverloadCandidate *Cand) {
5542 unsigned NoOperands = Cand->Conversions.size();
5543 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5544 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005545 if (ICS.isBad()) break; // all meaningless after first invalid
5546 if (!ICS.isAmbiguous()) continue;
5547
5548 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005549 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005550 }
5551}
5552
John McCall3712d9e2010-01-15 23:32:50 +00005553SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5554 if (Cand->Function)
5555 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005556 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005557 return Cand->Surrogate->getLocation();
5558 return SourceLocation();
5559}
5560
John McCallad2587a2010-01-12 00:48:53 +00005561struct CompareOverloadCandidatesForDisplay {
5562 Sema &S;
5563 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005564
5565 bool operator()(const OverloadCandidate *L,
5566 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005567 // Fast-path this check.
5568 if (L == R) return false;
5569
John McCall12f97bc2010-01-08 04:41:39 +00005570 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005571 if (L->Viable) {
5572 if (!R->Viable) return true;
5573
5574 // TODO: introduce a tri-valued comparison for overload
5575 // candidates. Would be more worthwhile if we had a sort
5576 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005577 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5578 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005579 } else if (R->Viable)
5580 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005581
John McCall3712d9e2010-01-15 23:32:50 +00005582 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005583
John McCall3712d9e2010-01-15 23:32:50 +00005584 // Criteria by which we can sort non-viable candidates:
5585 if (!L->Viable) {
5586 // 1. Arity mismatches come after other candidates.
5587 if (L->FailureKind == ovl_fail_too_many_arguments ||
5588 L->FailureKind == ovl_fail_too_few_arguments)
5589 return false;
5590 if (R->FailureKind == ovl_fail_too_many_arguments ||
5591 R->FailureKind == ovl_fail_too_few_arguments)
5592 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005593
John McCallfe796dd2010-01-23 05:17:32 +00005594 // 2. Bad conversions come first and are ordered by the number
5595 // of bad conversions and quality of good conversions.
5596 if (L->FailureKind == ovl_fail_bad_conversion) {
5597 if (R->FailureKind != ovl_fail_bad_conversion)
5598 return true;
5599
5600 // If there's any ordering between the defined conversions...
5601 // FIXME: this might not be transitive.
5602 assert(L->Conversions.size() == R->Conversions.size());
5603
5604 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005605 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5606 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005607 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5608 R->Conversions[I])) {
5609 case ImplicitConversionSequence::Better:
5610 leftBetter++;
5611 break;
5612
5613 case ImplicitConversionSequence::Worse:
5614 leftBetter--;
5615 break;
5616
5617 case ImplicitConversionSequence::Indistinguishable:
5618 break;
5619 }
5620 }
5621 if (leftBetter > 0) return true;
5622 if (leftBetter < 0) return false;
5623
5624 } else if (R->FailureKind == ovl_fail_bad_conversion)
5625 return false;
5626
John McCall3712d9e2010-01-15 23:32:50 +00005627 // TODO: others?
5628 }
5629
5630 // Sort everything else by location.
5631 SourceLocation LLoc = GetLocationForCandidate(L);
5632 SourceLocation RLoc = GetLocationForCandidate(R);
5633
5634 // Put candidates without locations (e.g. builtins) at the end.
5635 if (LLoc.isInvalid()) return false;
5636 if (RLoc.isInvalid()) return true;
5637
5638 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005639 }
5640};
5641
John McCallfe796dd2010-01-23 05:17:32 +00005642/// CompleteNonViableCandidate - Normally, overload resolution only
5643/// computes up to the first
5644void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5645 Expr **Args, unsigned NumArgs) {
5646 assert(!Cand->Viable);
5647
5648 // Don't do anything on failures other than bad conversion.
5649 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5650
5651 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005652 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005653 unsigned ConvCount = Cand->Conversions.size();
5654 while (true) {
5655 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5656 ConvIdx++;
5657 if (Cand->Conversions[ConvIdx - 1].isBad())
5658 break;
5659 }
5660
5661 if (ConvIdx == ConvCount)
5662 return;
5663
John McCall65eb8792010-02-25 01:37:24 +00005664 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5665 "remaining conversion is initialized?");
5666
Douglas Gregoradc7a702010-04-16 17:45:54 +00005667 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005668 // operation somehow.
5669 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005670
5671 const FunctionProtoType* Proto;
5672 unsigned ArgIdx = ConvIdx;
5673
5674 if (Cand->IsSurrogate) {
5675 QualType ConvType
5676 = Cand->Surrogate->getConversionType().getNonReferenceType();
5677 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5678 ConvType = ConvPtrType->getPointeeType();
5679 Proto = ConvType->getAs<FunctionProtoType>();
5680 ArgIdx--;
5681 } else if (Cand->Function) {
5682 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5683 if (isa<CXXMethodDecl>(Cand->Function) &&
5684 !isa<CXXConstructorDecl>(Cand->Function))
5685 ArgIdx--;
5686 } else {
5687 // Builtin binary operator with a bad first conversion.
5688 assert(ConvCount <= 3);
5689 for (; ConvIdx != ConvCount; ++ConvIdx)
5690 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005691 = TryCopyInitialization(S, Args[ConvIdx],
5692 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5693 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005694 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005695 return;
5696 }
5697
5698 // Fill in the rest of the conversions.
5699 unsigned NumArgsInProto = Proto->getNumArgs();
5700 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5701 if (ArgIdx < NumArgsInProto)
5702 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005703 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5704 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005705 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005706 else
5707 Cand->Conversions[ConvIdx].setEllipsis();
5708 }
5709}
5710
John McCalld3224162010-01-08 00:58:21 +00005711} // end anonymous namespace
5712
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005713/// PrintOverloadCandidates - When overload resolution fails, prints
5714/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005715/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005716void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005717Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005718 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005719 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005720 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005721 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005722 // Sort the candidates by viability and position. Sorting directly would
5723 // be prohibitive, so we make a set of pointers and sort those.
5724 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5725 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5726 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5727 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005728 Cand != LastCand; ++Cand) {
5729 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005730 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005731 else if (OCD == OCD_AllCandidates) {
5732 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005733 if (Cand->Function || Cand->IsSurrogate)
5734 Cands.push_back(Cand);
5735 // Otherwise, this a non-viable builtin candidate. We do not, in general,
5736 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00005737 }
5738 }
5739
John McCallad2587a2010-01-12 00:48:53 +00005740 std::sort(Cands.begin(), Cands.end(),
5741 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005742
John McCall0d1da222010-01-12 00:44:57 +00005743 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005744
John McCall12f97bc2010-01-08 04:41:39 +00005745 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005746 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
5747 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00005748 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5749 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005750
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005751 // Set an arbitrary limit on the number of candidate functions we'll spam
5752 // the user with. FIXME: This limit should depend on details of the
5753 // candidate list.
5754 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
5755 break;
5756 }
5757 ++CandsShown;
5758
John McCalld3224162010-01-08 00:58:21 +00005759 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005760 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005761 else if (Cand->IsSurrogate)
5762 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005763 else {
5764 assert(Cand->Viable &&
5765 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00005766 // Generally we only see ambiguities including viable builtin
5767 // operators if overload resolution got screwed up by an
5768 // ambiguous user-defined conversion.
5769 //
5770 // FIXME: It's quite possible for different conversions to see
5771 // different ambiguities, though.
5772 if (!ReportedAmbiguousConversions) {
5773 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5774 ReportedAmbiguousConversions = true;
5775 }
John McCalld3224162010-01-08 00:58:21 +00005776
John McCall0d1da222010-01-12 00:44:57 +00005777 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005778 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005779 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005780 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005781
5782 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00005783 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005784}
5785
John McCalla0296f72010-03-19 07:35:19 +00005786static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005787 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005788 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005789
John McCalla0296f72010-03-19 07:35:19 +00005790 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005791}
5792
Douglas Gregorcd695e52008-11-10 20:40:00 +00005793/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5794/// an overloaded function (C++ [over.over]), where @p From is an
5795/// expression with overloaded function type and @p ToType is the type
5796/// we're trying to resolve to. For example:
5797///
5798/// @code
5799/// int f(double);
5800/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005801///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005802/// int (*pfd)(double) = f; // selects f(double)
5803/// @endcode
5804///
5805/// This routine returns the resulting FunctionDecl if it could be
5806/// resolved, and NULL otherwise. When @p Complain is true, this
5807/// routine will emit diagnostics if there is an error.
5808FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005809Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005810 bool Complain,
5811 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005812 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005813 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005814 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005815 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005816 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005817 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005818 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005819 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005820 FunctionType = MemTypePtr->getPointeeType();
5821 IsMember = true;
5822 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005823
Douglas Gregorcd695e52008-11-10 20:40:00 +00005824 // C++ [over.over]p1:
5825 // [...] [Note: any redundant set of parentheses surrounding the
5826 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005827 // C++ [over.over]p1:
5828 // [...] The overloaded function name can be preceded by the &
5829 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005830 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5831 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5832 if (OvlExpr->hasExplicitTemplateArgs()) {
5833 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5834 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005835 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005836
5837 // We expect a pointer or reference to function, or a function pointer.
5838 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5839 if (!FunctionType->isFunctionType()) {
5840 if (Complain)
5841 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5842 << OvlExpr->getName() << ToType;
5843
5844 return 0;
5845 }
5846
5847 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005848
Douglas Gregorcd695e52008-11-10 20:40:00 +00005849 // Look through all of the overloaded functions, searching for one
5850 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005851 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005852 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5853
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005854 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005855 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5856 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005857 // Look through any using declarations to find the underlying function.
5858 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5859
Douglas Gregorcd695e52008-11-10 20:40:00 +00005860 // C++ [over.over]p3:
5861 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005862 // targets of type "pointer-to-function" or "reference-to-function."
5863 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005864 // type "pointer-to-member-function."
5865 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005866
Mike Stump11289f42009-09-09 15:08:12 +00005867 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005868 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005869 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005870 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005871 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005872 // static when converting to member pointer.
5873 if (Method->isStatic() == IsMember)
5874 continue;
5875 } else if (IsMember)
5876 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005877
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005878 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005879 // If the name is a function template, template argument deduction is
5880 // done (14.8.2.2), and if the argument deduction succeeds, the
5881 // resulting template argument list is used to generate a single
5882 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005883 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005884 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005885 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005886 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005887 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005888 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005889 FunctionType, Specialization, Info)) {
5890 // FIXME: make a note of the failed deduction for diagnostics.
5891 (void)Result;
5892 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005893 // FIXME: If the match isn't exact, shouldn't we just drop this as
5894 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005895 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005896 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005897 Matches.push_back(std::make_pair(I.getPair(),
5898 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005899 }
John McCalld14a8642009-11-21 08:51:07 +00005900
5901 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005902 }
Mike Stump11289f42009-09-09 15:08:12 +00005903
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005904 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005905 // Skip non-static functions when converting to pointer, and static
5906 // when converting to member pointer.
5907 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005908 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005909
5910 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005911 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005912 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005913 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005914 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005915
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005916 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005917 QualType ResultTy;
5918 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5919 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5920 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005921 Matches.push_back(std::make_pair(I.getPair(),
5922 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005923 FoundNonTemplateFunction = true;
5924 }
Mike Stump11289f42009-09-09 15:08:12 +00005925 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005926 }
5927
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005928 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005929 if (Matches.empty()) {
5930 if (Complain) {
5931 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5932 << OvlExpr->getName() << FunctionType;
5933 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5934 E = OvlExpr->decls_end();
5935 I != E; ++I)
5936 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5937 NoteOverloadCandidate(F);
5938 }
5939
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005940 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005941 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005942 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005943 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005944 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005945 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005946 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005947 return Result;
5948 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005949
5950 // C++ [over.over]p4:
5951 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005952 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005953 // [...] and any given function template specialization F1 is
5954 // eliminated if the set contains a second function template
5955 // specialization whose function template is more specialized
5956 // than the function template of F1 according to the partial
5957 // ordering rules of 14.5.5.2.
5958
5959 // The algorithm specified above is quadratic. We instead use a
5960 // two-pass algorithm (similar to the one used to identify the
5961 // best viable function in an overload set) that identifies the
5962 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005963
5964 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5965 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5966 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005967
5968 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005969 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005970 TPOC_Other, From->getLocStart(),
5971 PDiag(),
5972 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005973 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005974 PDiag(diag::note_ovl_candidate)
5975 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005976 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005977 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005978 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005979 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005980 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005981 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5982 }
John McCall58cc69d2010-01-27 01:50:18 +00005983 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005984 }
Mike Stump11289f42009-09-09 15:08:12 +00005985
Douglas Gregorfae1d712009-09-26 03:56:17 +00005986 // [...] any function template specializations in the set are
5987 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005988 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005989 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005990 ++I;
5991 else {
John McCalla0296f72010-03-19 07:35:19 +00005992 Matches[I] = Matches[--N];
5993 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005994 }
5995 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005996
Mike Stump11289f42009-09-09 15:08:12 +00005997 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005998 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005999 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006000 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006001 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006002 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006003 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006004 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6005 }
John McCalla0296f72010-03-19 07:35:19 +00006006 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006007 }
Mike Stump11289f42009-09-09 15:08:12 +00006008
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006009 // FIXME: We should probably return the same thing that BestViableFunction
6010 // returns (even if we issue the diagnostics here).
6011 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006012 << Matches[0].second->getDeclName();
6013 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6014 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006015 return 0;
6016}
6017
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006018/// \brief Given an expression that refers to an overloaded function, try to
6019/// resolve that overloaded function expression down to a single function.
6020///
6021/// This routine can only resolve template-ids that refer to a single function
6022/// template, where that template-id refers to a single template whose template
6023/// arguments are either provided by the template-id or have defaults,
6024/// as described in C++0x [temp.arg.explicit]p3.
6025FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6026 // C++ [over.over]p1:
6027 // [...] [Note: any redundant set of parentheses surrounding the
6028 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006029 // C++ [over.over]p1:
6030 // [...] The overloaded function name can be preceded by the &
6031 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006032
6033 if (From->getType() != Context.OverloadTy)
6034 return 0;
6035
6036 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006037
6038 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006039 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006040 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006041
6042 TemplateArgumentListInfo ExplicitTemplateArgs;
6043 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006044
6045 // Look through all of the overloaded functions, searching for one
6046 // whose type matches exactly.
6047 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006048 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6049 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006050 // C++0x [temp.arg.explicit]p3:
6051 // [...] In contexts where deduction is done and fails, or in contexts
6052 // where deduction is not done, if a template argument list is
6053 // specified and it, along with any default template arguments,
6054 // identifies a single function template specialization, then the
6055 // template-id is an lvalue for the function template specialization.
6056 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
6057
6058 // C++ [over.over]p2:
6059 // If the name is a function template, template argument deduction is
6060 // done (14.8.2.2), and if the argument deduction succeeds, the
6061 // resulting template argument list is used to generate a single
6062 // function template specialization, which is added to the set of
6063 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006064 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006065 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006066 if (TemplateDeductionResult Result
6067 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6068 Specialization, Info)) {
6069 // FIXME: make a note of the failed deduction for diagnostics.
6070 (void)Result;
6071 continue;
6072 }
6073
6074 // Multiple matches; we can't resolve to a single declaration.
6075 if (Matched)
6076 return 0;
6077
6078 Matched = Specialization;
6079 }
6080
6081 return Matched;
6082}
6083
Douglas Gregorcabea402009-09-22 15:41:20 +00006084/// \brief Add a single candidate to the overload set.
6085static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006086 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006087 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006088 Expr **Args, unsigned NumArgs,
6089 OverloadCandidateSet &CandidateSet,
6090 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006091 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006092 if (isa<UsingShadowDecl>(Callee))
6093 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6094
Douglas Gregorcabea402009-09-22 15:41:20 +00006095 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006096 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006097 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006098 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006099 return;
John McCalld14a8642009-11-21 08:51:07 +00006100 }
6101
6102 if (FunctionTemplateDecl *FuncTemplate
6103 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006104 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6105 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006106 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006107 return;
6108 }
6109
6110 assert(false && "unhandled case in overloaded call candidate");
6111
6112 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006113}
6114
6115/// \brief Add the overload candidates named by callee and/or found by argument
6116/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006117void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006118 Expr **Args, unsigned NumArgs,
6119 OverloadCandidateSet &CandidateSet,
6120 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006121
6122#ifndef NDEBUG
6123 // Verify that ArgumentDependentLookup is consistent with the rules
6124 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006125 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006126 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6127 // and let Y be the lookup set produced by argument dependent
6128 // lookup (defined as follows). If X contains
6129 //
6130 // -- a declaration of a class member, or
6131 //
6132 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006133 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006134 //
6135 // -- a declaration that is neither a function or a function
6136 // template
6137 //
6138 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006139
John McCall57500772009-12-16 12:17:52 +00006140 if (ULE->requiresADL()) {
6141 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6142 E = ULE->decls_end(); I != E; ++I) {
6143 assert(!(*I)->getDeclContext()->isRecord());
6144 assert(isa<UsingShadowDecl>(*I) ||
6145 !(*I)->getDeclContext()->isFunctionOrMethod());
6146 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006147 }
6148 }
6149#endif
6150
John McCall57500772009-12-16 12:17:52 +00006151 // It would be nice to avoid this copy.
6152 TemplateArgumentListInfo TABuffer;
6153 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6154 if (ULE->hasExplicitTemplateArgs()) {
6155 ULE->copyTemplateArgumentsInto(TABuffer);
6156 ExplicitTemplateArgs = &TABuffer;
6157 }
6158
6159 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6160 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006161 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006162 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006163 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006164
John McCall57500772009-12-16 12:17:52 +00006165 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006166 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6167 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006168 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006169 CandidateSet,
6170 PartialOverloading);
6171}
John McCalld681c392009-12-16 08:11:27 +00006172
John McCall57500772009-12-16 12:17:52 +00006173static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6174 Expr **Args, unsigned NumArgs) {
6175 Fn->Destroy(SemaRef.Context);
6176 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6177 Args[Arg]->Destroy(SemaRef.Context);
6178 return SemaRef.ExprError();
6179}
6180
John McCalld681c392009-12-16 08:11:27 +00006181/// Attempts to recover from a call where no functions were found.
6182///
6183/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006184static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006185BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006186 UnresolvedLookupExpr *ULE,
6187 SourceLocation LParenLoc,
6188 Expr **Args, unsigned NumArgs,
6189 SourceLocation *CommaLocs,
6190 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006191
6192 CXXScopeSpec SS;
6193 if (ULE->getQualifier()) {
6194 SS.setScopeRep(ULE->getQualifier());
6195 SS.setRange(ULE->getQualifierRange());
6196 }
6197
John McCall57500772009-12-16 12:17:52 +00006198 TemplateArgumentListInfo TABuffer;
6199 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6200 if (ULE->hasExplicitTemplateArgs()) {
6201 ULE->copyTemplateArgumentsInto(TABuffer);
6202 ExplicitTemplateArgs = &TABuffer;
6203 }
6204
John McCalld681c392009-12-16 08:11:27 +00006205 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6206 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006207 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall57500772009-12-16 12:17:52 +00006208 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00006209
John McCall57500772009-12-16 12:17:52 +00006210 assert(!R.empty() && "lookup results empty despite recovery");
6211
6212 // Build an implicit member call if appropriate. Just drop the
6213 // casts and such from the call, we don't really care.
6214 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6215 if ((*R.begin())->isCXXClassMember())
6216 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6217 else if (ExplicitTemplateArgs)
6218 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6219 else
6220 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6221
6222 if (NewFn.isInvalid())
6223 return Destroy(SemaRef, Fn, Args, NumArgs);
6224
6225 Fn->Destroy(SemaRef.Context);
6226
6227 // This shouldn't cause an infinite loop because we're giving it
6228 // an expression with non-empty lookup results, which should never
6229 // end up here.
6230 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6231 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6232 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006233}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006234
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006235/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006236/// (which eventually refers to the declaration Func) and the call
6237/// arguments Args/NumArgs, attempt to resolve the function call down
6238/// to a specific function. If overload resolution succeeds, returns
6239/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006240/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006241/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006242Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006243Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006244 SourceLocation LParenLoc,
6245 Expr **Args, unsigned NumArgs,
6246 SourceLocation *CommaLocs,
6247 SourceLocation RParenLoc) {
6248#ifndef NDEBUG
6249 if (ULE->requiresADL()) {
6250 // To do ADL, we must have found an unqualified name.
6251 assert(!ULE->getQualifier() && "qualified name with ADL");
6252
6253 // We don't perform ADL for implicit declarations of builtins.
6254 // Verify that this was correctly set up.
6255 FunctionDecl *F;
6256 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6257 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6258 F->getBuiltinID() && F->isImplicit())
6259 assert(0 && "performing ADL for builtin");
6260
6261 // We don't perform ADL in C.
6262 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6263 }
6264#endif
6265
John McCallbc077cf2010-02-08 23:07:23 +00006266 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006267
John McCall57500772009-12-16 12:17:52 +00006268 // Add the functions denoted by the callee to the set of candidate
6269 // functions, including those from argument-dependent lookup.
6270 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006271
6272 // If we found nothing, try to recover.
6273 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6274 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006275 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006276 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006277 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006278
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006279 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006280 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006281 case OR_Success: {
6282 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006283 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006284 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006285 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006286 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6287 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006288
6289 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006290 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006291 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006292 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006293 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006294 break;
6295
6296 case OR_Ambiguous:
6297 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006298 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006299 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006300 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006301
6302 case OR_Deleted:
6303 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6304 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006305 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006306 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006307 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006308 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006309 }
6310
6311 // Overload resolution failed. Destroy all of the subexpressions and
6312 // return NULL.
6313 Fn->Destroy(Context);
6314 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6315 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006316 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006317}
6318
John McCall4c4c1df2010-01-26 03:27:55 +00006319static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006320 return Functions.size() > 1 ||
6321 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6322}
6323
Douglas Gregor084d8552009-03-13 23:49:33 +00006324/// \brief Create a unary operation that may resolve to an overloaded
6325/// operator.
6326///
6327/// \param OpLoc The location of the operator itself (e.g., '*').
6328///
6329/// \param OpcIn The UnaryOperator::Opcode that describes this
6330/// operator.
6331///
6332/// \param Functions The set of non-member functions that will be
6333/// considered by overload resolution. The caller needs to build this
6334/// set based on the context using, e.g.,
6335/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6336/// set should not contain any member functions; those will be added
6337/// by CreateOverloadedUnaryOp().
6338///
6339/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006340Sema::OwningExprResult
6341Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6342 const UnresolvedSetImpl &Fns,
6343 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006344 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6345 Expr *Input = (Expr *)input.get();
6346
6347 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6348 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6349 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6350
6351 Expr *Args[2] = { Input, 0 };
6352 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006353
Douglas Gregor084d8552009-03-13 23:49:33 +00006354 // For post-increment and post-decrement, add the implicit '0' as
6355 // the second argument, so that we know this is a post-increment or
6356 // post-decrement.
6357 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6358 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006359 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006360 SourceLocation());
6361 NumArgs = 2;
6362 }
6363
6364 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006365 if (Fns.empty())
6366 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6367 Opc,
6368 Context.DependentTy,
6369 OpLoc));
6370
John McCall58cc69d2010-01-27 01:50:18 +00006371 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006372 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006373 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006374 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006375 /*ADL*/ true, IsOverloaded(Fns),
6376 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006377 input.release();
6378 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6379 &Args[0], NumArgs,
6380 Context.DependentTy,
6381 OpLoc));
6382 }
6383
6384 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006385 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006386
6387 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006388 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006389
6390 // Add operator candidates that are member functions.
6391 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6392
John McCall4c4c1df2010-01-26 03:27:55 +00006393 // Add candidates from ADL.
6394 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006395 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006396 /*ExplicitTemplateArgs*/ 0,
6397 CandidateSet);
6398
Douglas Gregor084d8552009-03-13 23:49:33 +00006399 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006400 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006401
6402 // Perform overload resolution.
6403 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006404 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006405 case OR_Success: {
6406 // We found a built-in operator or an overloaded operator.
6407 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006408
Douglas Gregor084d8552009-03-13 23:49:33 +00006409 if (FnDecl) {
6410 // We matched an overloaded operator. Build a call to that
6411 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006412
Douglas Gregor084d8552009-03-13 23:49:33 +00006413 // Convert the arguments.
6414 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006415 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006416
John McCall16df1e52010-03-30 21:47:33 +00006417 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6418 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006419 return ExprError();
6420 } else {
6421 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006422 OwningExprResult InputInit
6423 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006424 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006425 SourceLocation(),
6426 move(input));
6427 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006428 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006429
Douglas Gregore6600372009-12-23 17:40:29 +00006430 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006431 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006432 }
6433
John McCall4fa0d5f2010-05-06 18:15:07 +00006434 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6435
Douglas Gregor084d8552009-03-13 23:49:33 +00006436 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006437 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006438
Douglas Gregor084d8552009-03-13 23:49:33 +00006439 // Build the actual expression node.
6440 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6441 SourceLocation());
6442 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006443
Douglas Gregor084d8552009-03-13 23:49:33 +00006444 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006445 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006446 ExprOwningPtr<CallExpr> TheCall(this,
6447 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006448 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006449
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006450 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6451 FnDecl))
6452 return ExprError();
6453
6454 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006455 } else {
6456 // We matched a built-in operator. Convert the arguments, then
6457 // break out so that we will build the appropriate built-in
6458 // operator node.
6459 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006460 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006461 return ExprError();
6462
6463 break;
6464 }
6465 }
6466
6467 case OR_No_Viable_Function:
6468 // No viable function; fall through to handling this as a
6469 // built-in operator, which will produce an error message for us.
6470 break;
6471
6472 case OR_Ambiguous:
6473 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6474 << UnaryOperator::getOpcodeStr(Opc)
6475 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006476 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006477 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006478 return ExprError();
6479
6480 case OR_Deleted:
6481 Diag(OpLoc, diag::err_ovl_deleted_oper)
6482 << Best->Function->isDeleted()
6483 << UnaryOperator::getOpcodeStr(Opc)
6484 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006485 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006486 return ExprError();
6487 }
6488
6489 // Either we found no viable overloaded operator or we matched a
6490 // built-in operator. In either case, fall through to trying to
6491 // build a built-in operation.
6492 input.release();
6493 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6494}
6495
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006496/// \brief Create a binary operation that may resolve to an overloaded
6497/// operator.
6498///
6499/// \param OpLoc The location of the operator itself (e.g., '+').
6500///
6501/// \param OpcIn The BinaryOperator::Opcode that describes this
6502/// operator.
6503///
6504/// \param Functions The set of non-member functions that will be
6505/// considered by overload resolution. The caller needs to build this
6506/// set based on the context using, e.g.,
6507/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6508/// set should not contain any member functions; those will be added
6509/// by CreateOverloadedBinOp().
6510///
6511/// \param LHS Left-hand argument.
6512/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006513Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006514Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006515 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006516 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006517 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006518 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006519 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006520
6521 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6522 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6523 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6524
6525 // If either side is type-dependent, create an appropriate dependent
6526 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006527 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006528 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006529 // If there are no functions to store, just build a dependent
6530 // BinaryOperator or CompoundAssignment.
6531 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6532 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6533 Context.DependentTy, OpLoc));
6534
6535 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6536 Context.DependentTy,
6537 Context.DependentTy,
6538 Context.DependentTy,
6539 OpLoc));
6540 }
John McCall4c4c1df2010-01-26 03:27:55 +00006541
6542 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006543 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006544 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006545 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006546 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006547 /*ADL*/ true, IsOverloaded(Fns),
6548 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006549 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006550 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006551 Context.DependentTy,
6552 OpLoc));
6553 }
6554
6555 // If this is the .* operator, which is not overloadable, just
6556 // create a built-in binary operator.
6557 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006558 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006559
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006560 // If this is the assignment operator, we only perform overload resolution
6561 // if the left-hand side is a class or enumeration type. This is actually
6562 // a hack. The standard requires that we do overload resolution between the
6563 // various built-in candidates, but as DR507 points out, this can lead to
6564 // problems. So we do it this way, which pretty much follows what GCC does.
6565 // Note that we go the traditional code path for compound assignment forms.
6566 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006567 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006568
Douglas Gregor084d8552009-03-13 23:49:33 +00006569 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006570 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006571
6572 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006573 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006574
6575 // Add operator candidates that are member functions.
6576 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6577
John McCall4c4c1df2010-01-26 03:27:55 +00006578 // Add candidates from ADL.
6579 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6580 Args, 2,
6581 /*ExplicitTemplateArgs*/ 0,
6582 CandidateSet);
6583
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006584 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006585 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006586
6587 // Perform overload resolution.
6588 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006589 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006590 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006591 // We found a built-in operator or an overloaded operator.
6592 FunctionDecl *FnDecl = Best->Function;
6593
6594 if (FnDecl) {
6595 // We matched an overloaded operator. Build a call to that
6596 // operator.
6597
6598 // Convert the arguments.
6599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006600 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006601 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006602
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006603 OwningExprResult Arg1
6604 = PerformCopyInitialization(
6605 InitializedEntity::InitializeParameter(
6606 FnDecl->getParamDecl(0)),
6607 SourceLocation(),
6608 Owned(Args[1]));
6609 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006610 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006611
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006612 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006613 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006614 return ExprError();
6615
6616 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006617 } else {
6618 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006619 OwningExprResult Arg0
6620 = PerformCopyInitialization(
6621 InitializedEntity::InitializeParameter(
6622 FnDecl->getParamDecl(0)),
6623 SourceLocation(),
6624 Owned(Args[0]));
6625 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006626 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006627
6628 OwningExprResult Arg1
6629 = PerformCopyInitialization(
6630 InitializedEntity::InitializeParameter(
6631 FnDecl->getParamDecl(1)),
6632 SourceLocation(),
6633 Owned(Args[1]));
6634 if (Arg1.isInvalid())
6635 return ExprError();
6636 Args[0] = LHS = Arg0.takeAs<Expr>();
6637 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006638 }
6639
John McCall4fa0d5f2010-05-06 18:15:07 +00006640 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6641
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006642 // Determine the result type
6643 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006644 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006645 ResultTy = ResultTy.getNonReferenceType();
6646
6647 // Build the actual expression node.
6648 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006649 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006650 UsualUnaryConversions(FnExpr);
6651
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006652 ExprOwningPtr<CXXOperatorCallExpr>
6653 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6654 Args, 2, ResultTy,
6655 OpLoc));
6656
6657 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6658 FnDecl))
6659 return ExprError();
6660
6661 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006662 } else {
6663 // We matched a built-in operator. Convert the arguments, then
6664 // break out so that we will build the appropriate built-in
6665 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006666 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006667 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006668 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006669 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006670 return ExprError();
6671
6672 break;
6673 }
6674 }
6675
Douglas Gregor66950a32009-09-30 21:46:01 +00006676 case OR_No_Viable_Function: {
6677 // C++ [over.match.oper]p9:
6678 // If the operator is the operator , [...] and there are no
6679 // viable functions, then the operator is assumed to be the
6680 // built-in operator and interpreted according to clause 5.
6681 if (Opc == BinaryOperator::Comma)
6682 break;
6683
Sebastian Redl027de2a2009-05-21 11:50:50 +00006684 // For class as left operand for assignment or compound assigment operator
6685 // do not fall through to handling in built-in, but report that no overloaded
6686 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006687 OwningExprResult Result = ExprError();
6688 if (Args[0]->getType()->isRecordType() &&
6689 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006690 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6691 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006692 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006693 } else {
6694 // No viable function; try to create a built-in operation, which will
6695 // produce an error. Then, show the non-viable candidates.
6696 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006697 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006698 assert(Result.isInvalid() &&
6699 "C++ binary operator overloading is missing candidates!");
6700 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006701 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006702 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006703 return move(Result);
6704 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006705
6706 case OR_Ambiguous:
6707 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6708 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006709 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006710 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006711 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006712 return ExprError();
6713
6714 case OR_Deleted:
6715 Diag(OpLoc, diag::err_ovl_deleted_oper)
6716 << Best->Function->isDeleted()
6717 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006718 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006719 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006720 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006721 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006722
Douglas Gregor66950a32009-09-30 21:46:01 +00006723 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006724 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006725}
6726
Sebastian Redladba46e2009-10-29 20:17:01 +00006727Action::OwningExprResult
6728Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6729 SourceLocation RLoc,
6730 ExprArg Base, ExprArg Idx) {
6731 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6732 static_cast<Expr*>(Idx.get()) };
6733 DeclarationName OpName =
6734 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6735
6736 // If either side is type-dependent, create an appropriate dependent
6737 // expression.
6738 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6739
John McCall58cc69d2010-01-27 01:50:18 +00006740 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006741 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006742 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006743 0, SourceRange(), OpName, LLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006744 /*ADL*/ true, /*Overloaded*/ false,
6745 UnresolvedSetIterator(),
6746 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00006747 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006748
6749 Base.release();
6750 Idx.release();
6751 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6752 Args, 2,
6753 Context.DependentTy,
6754 RLoc));
6755 }
6756
6757 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006758 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006759
6760 // Subscript can only be overloaded as a member function.
6761
6762 // Add operator candidates that are member functions.
6763 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6764
6765 // Add builtin operator candidates.
6766 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6767
6768 // Perform overload resolution.
6769 OverloadCandidateSet::iterator Best;
6770 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6771 case OR_Success: {
6772 // We found a built-in operator or an overloaded operator.
6773 FunctionDecl *FnDecl = Best->Function;
6774
6775 if (FnDecl) {
6776 // We matched an overloaded operator. Build a call to that
6777 // operator.
6778
John McCalla0296f72010-03-19 07:35:19 +00006779 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006780 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006781
Sebastian Redladba46e2009-10-29 20:17:01 +00006782 // Convert the arguments.
6783 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006784 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006785 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006786 return ExprError();
6787
Anders Carlssona68e51e2010-01-29 18:37:50 +00006788 // Convert the arguments.
6789 OwningExprResult InputInit
6790 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6791 FnDecl->getParamDecl(0)),
6792 SourceLocation(),
6793 Owned(Args[1]));
6794 if (InputInit.isInvalid())
6795 return ExprError();
6796
6797 Args[1] = InputInit.takeAs<Expr>();
6798
Sebastian Redladba46e2009-10-29 20:17:01 +00006799 // Determine the result type
6800 QualType ResultTy
6801 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6802 ResultTy = ResultTy.getNonReferenceType();
6803
6804 // Build the actual expression node.
6805 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6806 LLoc);
6807 UsualUnaryConversions(FnExpr);
6808
6809 Base.release();
6810 Idx.release();
6811 ExprOwningPtr<CXXOperatorCallExpr>
6812 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6813 FnExpr, Args, 2,
6814 ResultTy, RLoc));
6815
6816 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6817 FnDecl))
6818 return ExprError();
6819
6820 return MaybeBindToTemporary(TheCall.release());
6821 } else {
6822 // We matched a built-in operator. Convert the arguments, then
6823 // break out so that we will build the appropriate built-in
6824 // operator node.
6825 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006826 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006827 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006828 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006829 return ExprError();
6830
6831 break;
6832 }
6833 }
6834
6835 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006836 if (CandidateSet.empty())
6837 Diag(LLoc, diag::err_ovl_no_oper)
6838 << Args[0]->getType() << /*subscript*/ 0
6839 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6840 else
6841 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6842 << Args[0]->getType()
6843 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006844 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006845 "[]", LLoc);
6846 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006847 }
6848
6849 case OR_Ambiguous:
6850 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6851 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006852 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006853 "[]", LLoc);
6854 return ExprError();
6855
6856 case OR_Deleted:
6857 Diag(LLoc, diag::err_ovl_deleted_oper)
6858 << Best->Function->isDeleted() << "[]"
6859 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006860 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006861 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006862 return ExprError();
6863 }
6864
6865 // We matched a built-in operator; build it.
6866 Base.release();
6867 Idx.release();
6868 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6869 Owned(Args[1]), RLoc);
6870}
6871
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006872/// BuildCallToMemberFunction - Build a call to a member
6873/// function. MemExpr is the expression that refers to the member
6874/// function (and includes the object parameter), Args/NumArgs are the
6875/// arguments to the function call (not including the object
6876/// parameter). The caller needs to validate that the member
6877/// expression refers to a member function or an overloaded member
6878/// function.
John McCall2d74de92009-12-01 22:10:20 +00006879Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006880Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6881 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006882 unsigned NumArgs, SourceLocation *CommaLocs,
6883 SourceLocation RParenLoc) {
6884 // Dig out the member expression. This holds both the object
6885 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006886 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6887
John McCall10eae182009-11-30 22:42:35 +00006888 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006889 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006890 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006891 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006892 if (isa<MemberExpr>(NakedMemExpr)) {
6893 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006894 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006895 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006896 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006897 } else {
6898 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006899 Qualifier = UnresExpr->getQualifier();
6900
John McCall6e9f8f62009-12-03 04:06:58 +00006901 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006902
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006903 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006904 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006905
John McCall2d74de92009-12-01 22:10:20 +00006906 // FIXME: avoid copy.
6907 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6908 if (UnresExpr->hasExplicitTemplateArgs()) {
6909 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6910 TemplateArgs = &TemplateArgsBuffer;
6911 }
6912
John McCall10eae182009-11-30 22:42:35 +00006913 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6914 E = UnresExpr->decls_end(); I != E; ++I) {
6915
John McCall6e9f8f62009-12-03 04:06:58 +00006916 NamedDecl *Func = *I;
6917 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6918 if (isa<UsingShadowDecl>(Func))
6919 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6920
John McCall10eae182009-11-30 22:42:35 +00006921 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006922 // If explicit template arguments were provided, we can't call a
6923 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006924 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006925 continue;
6926
John McCalla0296f72010-03-19 07:35:19 +00006927 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006928 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006929 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006930 } else {
John McCall10eae182009-11-30 22:42:35 +00006931 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006932 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006933 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006934 CandidateSet,
6935 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006936 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006937 }
Mike Stump11289f42009-09-09 15:08:12 +00006938
John McCall10eae182009-11-30 22:42:35 +00006939 DeclarationName DeclName = UnresExpr->getMemberName();
6940
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006941 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006942 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006943 case OR_Success:
6944 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006945 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006946 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006947 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006948 break;
6949
6950 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006951 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006952 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006953 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006954 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006955 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006956 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006957
6958 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006959 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006960 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006961 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006962 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006963 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006964
6965 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006966 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006967 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006968 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006969 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006970 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006971 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006972 }
6973
John McCall16df1e52010-03-30 21:47:33 +00006974 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006975
John McCall2d74de92009-12-01 22:10:20 +00006976 // If overload resolution picked a static member, build a
6977 // non-member call based on that function.
6978 if (Method->isStatic()) {
6979 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6980 Args, NumArgs, RParenLoc);
6981 }
6982
John McCall10eae182009-11-30 22:42:35 +00006983 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006984 }
6985
6986 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006987 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006988 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006989 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006990 Method->getResultType().getNonReferenceType(),
6991 RParenLoc));
6992
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006993 // Check for a valid return type.
6994 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6995 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006996 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006997
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006998 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006999 // We only need to do this if there was actually an overload; otherwise
7000 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007001 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007002 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007003 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7004 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007005 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007006 MemExpr->setBase(ObjectArg);
7007
7008 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007009 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00007010 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007011 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007012 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007013
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007014 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00007015 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007016
John McCall2d74de92009-12-01 22:10:20 +00007017 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007018}
7019
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007020/// BuildCallToObjectOfClassType - Build a call to an object of class
7021/// type (C++ [over.call.object]), which can end up invoking an
7022/// overloaded function call operator (@c operator()) or performing a
7023/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007024Sema::ExprResult
7025Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007026 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007027 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007028 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007029 SourceLocation RParenLoc) {
7030 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007031 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007032
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007033 // C++ [over.call.object]p1:
7034 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007035 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007036 // candidate functions includes at least the function call
7037 // operators of T. The function call operators of T are obtained by
7038 // ordinary lookup of the name operator() in the context of
7039 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007040 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007041 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007042
7043 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007044 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007045 << Object->getSourceRange()))
7046 return true;
7047
John McCall27b18f82009-11-17 02:14:36 +00007048 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7049 LookupQualifiedName(R, Record->getDecl());
7050 R.suppressDiagnostics();
7051
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007052 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007053 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007054 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007055 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007056 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007057 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007058
Douglas Gregorab7897a2008-11-19 22:57:39 +00007059 // C++ [over.call.object]p2:
7060 // In addition, for each conversion function declared in T of the
7061 // form
7062 //
7063 // operator conversion-type-id () cv-qualifier;
7064 //
7065 // where cv-qualifier is the same cv-qualification as, or a
7066 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007067 // denotes the type "pointer to function of (P1,...,Pn) returning
7068 // R", or the type "reference to pointer to function of
7069 // (P1,...,Pn) returning R", or the type "reference to function
7070 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007071 // is also considered as a candidate function. Similarly,
7072 // surrogate call functions are added to the set of candidate
7073 // functions for each conversion function declared in an
7074 // accessible base class provided the function is not hidden
7075 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007076 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007077 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007078 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007079 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007080 NamedDecl *D = *I;
7081 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7082 if (isa<UsingShadowDecl>(D))
7083 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7084
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007085 // Skip over templated conversion functions; they aren't
7086 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007087 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007088 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007089
John McCall6e9f8f62009-12-03 04:06:58 +00007090 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007091
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007092 // Strip the reference type (if any) and then the pointer type (if
7093 // any) to get down to what might be a function type.
7094 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7095 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7096 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007097
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007098 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007099 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007100 Object->getType(), Args, NumArgs,
7101 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007102 }
Mike Stump11289f42009-09-09 15:08:12 +00007103
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007104 // Perform overload resolution.
7105 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007106 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007107 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007108 // Overload resolution succeeded; we'll build the appropriate call
7109 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007110 break;
7111
7112 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007113 if (CandidateSet.empty())
7114 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7115 << Object->getType() << /*call*/ 1
7116 << Object->getSourceRange();
7117 else
7118 Diag(Object->getSourceRange().getBegin(),
7119 diag::err_ovl_no_viable_object_call)
7120 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007121 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007122 break;
7123
7124 case OR_Ambiguous:
7125 Diag(Object->getSourceRange().getBegin(),
7126 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007127 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007128 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007129 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007130
7131 case OR_Deleted:
7132 Diag(Object->getSourceRange().getBegin(),
7133 diag::err_ovl_deleted_object_call)
7134 << Best->Function->isDeleted()
7135 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007136 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007137 break;
Mike Stump11289f42009-09-09 15:08:12 +00007138 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007139
Douglas Gregorab7897a2008-11-19 22:57:39 +00007140 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007141 // We had an error; delete all of the subexpressions and return
7142 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00007143 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007144 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00007145 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007146 return true;
7147 }
7148
Douglas Gregorab7897a2008-11-19 22:57:39 +00007149 if (Best->Function == 0) {
7150 // Since there is no function declaration, this is one of the
7151 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007152 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007153 = cast<CXXConversionDecl>(
7154 Best->Conversions[0].UserDefined.ConversionFunction);
7155
John McCalla0296f72010-03-19 07:35:19 +00007156 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007157 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007158
Douglas Gregorab7897a2008-11-19 22:57:39 +00007159 // We selected one of the surrogate functions that converts the
7160 // object parameter to a function pointer. Perform the conversion
7161 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007162
7163 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007164 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007165 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7166 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007167
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007168 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007169 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007170 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007171 }
7172
John McCalla0296f72010-03-19 07:35:19 +00007173 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007174 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007175
Douglas Gregorab7897a2008-11-19 22:57:39 +00007176 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7177 // that calls this method, using Object for the implicit object
7178 // parameter and passing along the remaining arguments.
7179 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007180 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007181
7182 unsigned NumArgsInProto = Proto->getNumArgs();
7183 unsigned NumArgsToCheck = NumArgs;
7184
7185 // Build the full argument list for the method call (the
7186 // implicit object parameter is placed at the beginning of the
7187 // list).
7188 Expr **MethodArgs;
7189 if (NumArgs < NumArgsInProto) {
7190 NumArgsToCheck = NumArgsInProto;
7191 MethodArgs = new Expr*[NumArgsInProto + 1];
7192 } else {
7193 MethodArgs = new Expr*[NumArgs + 1];
7194 }
7195 MethodArgs[0] = Object;
7196 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7197 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007198
7199 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007200 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007201 UsualUnaryConversions(NewFn);
7202
7203 // Once we've built TheCall, all of the expressions are properly
7204 // owned.
7205 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00007206 ExprOwningPtr<CXXOperatorCallExpr>
7207 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007208 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007209 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007210 delete [] MethodArgs;
7211
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007212 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7213 Method))
7214 return true;
7215
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007216 // We may have default arguments. If so, we need to allocate more
7217 // slots in the call for them.
7218 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007219 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007220 else if (NumArgs > NumArgsInProto)
7221 NumArgsToCheck = NumArgsInProto;
7222
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007223 bool IsError = false;
7224
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007225 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007226 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007227 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007228 TheCall->setArg(0, Object);
7229
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007230
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007231 // Check the argument types.
7232 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007233 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007234 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007235 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007236
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007237 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007238
7239 OwningExprResult InputInit
7240 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7241 Method->getParamDecl(i)),
7242 SourceLocation(), Owned(Arg));
7243
7244 IsError |= InputInit.isInvalid();
7245 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007246 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007247 OwningExprResult DefArg
7248 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7249 if (DefArg.isInvalid()) {
7250 IsError = true;
7251 break;
7252 }
7253
7254 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007255 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007256
7257 TheCall->setArg(i + 1, Arg);
7258 }
7259
7260 // If this is a variadic call, handle args passed through "...".
7261 if (Proto->isVariadic()) {
7262 // Promote the arguments (C99 6.5.2.2p7).
7263 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7264 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007265 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007266 TheCall->setArg(i + 1, Arg);
7267 }
7268 }
7269
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007270 if (IsError) return true;
7271
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007272 if (CheckFunctionCall(Method, TheCall.get()))
7273 return true;
7274
Douglas Gregore5e775b2010-04-13 15:50:39 +00007275 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007276}
7277
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007278/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007279/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007280/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007281Sema::OwningExprResult
7282Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7283 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007284 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007285
John McCallbc077cf2010-02-08 23:07:23 +00007286 SourceLocation Loc = Base->getExprLoc();
7287
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007288 // C++ [over.ref]p1:
7289 //
7290 // [...] An expression x->m is interpreted as (x.operator->())->m
7291 // for a class object x of type T if T::operator->() exists and if
7292 // the operator is selected as the best match function by the
7293 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007294 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007295 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007296 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007297
John McCallbc077cf2010-02-08 23:07:23 +00007298 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007299 PDiag(diag::err_typecheck_incomplete_tag)
7300 << Base->getSourceRange()))
7301 return ExprError();
7302
John McCall27b18f82009-11-17 02:14:36 +00007303 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7304 LookupQualifiedName(R, BaseRecord->getDecl());
7305 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007306
7307 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007308 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007309 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007310 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007311 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007312
7313 // Perform overload resolution.
7314 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007315 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007316 case OR_Success:
7317 // Overload resolution succeeded; we'll build the call below.
7318 break;
7319
7320 case OR_No_Viable_Function:
7321 if (CandidateSet.empty())
7322 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007323 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007324 else
7325 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007326 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007327 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007328 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007329
7330 case OR_Ambiguous:
7331 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007332 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007333 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007334 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007335
7336 case OR_Deleted:
7337 Diag(OpLoc, diag::err_ovl_deleted_oper)
7338 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007339 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007340 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007341 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007342 }
7343
John McCalla0296f72010-03-19 07:35:19 +00007344 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007345 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007346
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007347 // Convert the object parameter.
7348 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007349 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7350 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007351 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007352
7353 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007354 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007355
7356 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007357 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7358 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007359 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007360
7361 QualType ResultTy = Method->getResultType().getNonReferenceType();
7362 ExprOwningPtr<CXXOperatorCallExpr>
7363 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7364 &Base, 1, ResultTy, OpLoc));
7365
7366 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7367 Method))
7368 return ExprError();
7369 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007370}
7371
Douglas Gregorcd695e52008-11-10 20:40:00 +00007372/// FixOverloadedFunctionReference - E is an expression that refers to
7373/// a C++ overloaded function (possibly with some parentheses and
7374/// perhaps a '&' around it). We have resolved the overloaded function
7375/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007376/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007377Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007378 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007379 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007380 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7381 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007382 if (SubExpr == PE->getSubExpr())
7383 return PE->Retain();
7384
7385 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7386 }
7387
7388 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007389 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7390 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007391 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007392 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007393 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007394 if (SubExpr == ICE->getSubExpr())
7395 return ICE->Retain();
7396
7397 return new (Context) ImplicitCastExpr(ICE->getType(),
7398 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007399 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007400 ICE->isLvalueCast());
7401 }
7402
7403 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007404 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007405 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007406 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7407 if (Method->isStatic()) {
7408 // Do nothing: static member functions aren't any different
7409 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007410 } else {
John McCalle66edc12009-11-24 19:00:30 +00007411 // Fix the sub expression, which really has to be an
7412 // UnresolvedLookupExpr holding an overloaded member function
7413 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007414 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7415 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007416 if (SubExpr == UnOp->getSubExpr())
7417 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007418
John McCalld14a8642009-11-21 08:51:07 +00007419 assert(isa<DeclRefExpr>(SubExpr)
7420 && "fixed to something other than a decl ref");
7421 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7422 && "fixed to a member ref with no nested name qualifier");
7423
7424 // We have taken the address of a pointer to member
7425 // function. Perform the computation here so that we get the
7426 // appropriate pointer to member type.
7427 QualType ClassType
7428 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7429 QualType MemPtrType
7430 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7431
7432 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7433 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007434 }
7435 }
John McCall16df1e52010-03-30 21:47:33 +00007436 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7437 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007438 if (SubExpr == UnOp->getSubExpr())
7439 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007440
Douglas Gregor51c538b2009-11-20 19:42:02 +00007441 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7442 Context.getPointerType(SubExpr->getType()),
7443 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007444 }
John McCalld14a8642009-11-21 08:51:07 +00007445
7446 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007447 // FIXME: avoid copy.
7448 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007449 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007450 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7451 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007452 }
7453
John McCalld14a8642009-11-21 08:51:07 +00007454 return DeclRefExpr::Create(Context,
7455 ULE->getQualifier(),
7456 ULE->getQualifierRange(),
7457 Fn,
7458 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007459 Fn->getType(),
7460 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007461 }
7462
John McCall10eae182009-11-30 22:42:35 +00007463 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007464 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007465 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7466 if (MemExpr->hasExplicitTemplateArgs()) {
7467 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7468 TemplateArgs = &TemplateArgsBuffer;
7469 }
John McCall6b51f282009-11-23 01:53:49 +00007470
John McCall2d74de92009-12-01 22:10:20 +00007471 Expr *Base;
7472
7473 // If we're filling in
7474 if (MemExpr->isImplicitAccess()) {
7475 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7476 return DeclRefExpr::Create(Context,
7477 MemExpr->getQualifier(),
7478 MemExpr->getQualifierRange(),
7479 Fn,
7480 MemExpr->getMemberLoc(),
7481 Fn->getType(),
7482 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007483 } else {
7484 SourceLocation Loc = MemExpr->getMemberLoc();
7485 if (MemExpr->getQualifier())
7486 Loc = MemExpr->getQualifierRange().getBegin();
7487 Base = new (Context) CXXThisExpr(Loc,
7488 MemExpr->getBaseType(),
7489 /*isImplicit=*/true);
7490 }
John McCall2d74de92009-12-01 22:10:20 +00007491 } else
7492 Base = MemExpr->getBase()->Retain();
7493
7494 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007495 MemExpr->isArrow(),
7496 MemExpr->getQualifier(),
7497 MemExpr->getQualifierRange(),
7498 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007499 Found,
John McCall6b51f282009-11-23 01:53:49 +00007500 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007501 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007502 Fn->getType());
7503 }
7504
Douglas Gregor51c538b2009-11-20 19:42:02 +00007505 assert(false && "Invalid reference to overloaded function");
7506 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007507}
7508
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007509Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007510 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007511 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007512 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007513}
7514
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007515} // end namespace clang