blob: 3de8e730c60ee7fec77f3b11896051e7e3067a41 [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 McCalldaa3d6b2009-12-09 03:35:25 +0000503Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000504Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
505 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000506 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000507 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000508 NamedDecl *OldD = (*I)->getUnderlyingDecl();
509 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000510 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000511 Match = *I;
512 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 }
John McCall3d988d92009-12-02 08:47:38 +0000514 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000515 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000516 Match = *I;
517 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000518 }
John McCall84d87672009-12-10 09:41:52 +0000519 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
520 // We can overload with these, which can show up when doing
521 // redeclaration checks for UsingDecls.
522 assert(Old.getLookupKind() == LookupUsingDeclName);
523 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
524 // Optimistically assume that an unresolved using decl will
525 // overload; if it doesn't, we'll have to diagnose during
526 // template instantiation.
527 } else {
John McCall1f82f242009-11-18 22:49:29 +0000528 // (C++ 13p1):
529 // Only function declarations can be overloaded; object and type
530 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000531 Match = *I;
532 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000533 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534 }
John McCall1f82f242009-11-18 22:49:29 +0000535
John McCalldaa3d6b2009-12-09 03:35:25 +0000536 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000537}
538
539bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
540 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
541 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
542
543 // C++ [temp.fct]p2:
544 // A function template can be overloaded with other function templates
545 // and with normal (non-template) functions.
546 if ((OldTemplate == 0) != (NewTemplate == 0))
547 return true;
548
549 // Is the function New an overload of the function Old?
550 QualType OldQType = Context.getCanonicalType(Old->getType());
551 QualType NewQType = Context.getCanonicalType(New->getType());
552
553 // Compare the signatures (C++ 1.3.10) of the two functions to
554 // determine whether they are overloads. If we find any mismatch
555 // in the signature, they are overloads.
556
557 // If either of these functions is a K&R-style function (no
558 // prototype), then we consider them to have matching signatures.
559 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
560 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
561 return false;
562
563 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
564 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
565
566 // The signature of a function includes the types of its
567 // parameters (C++ 1.3.10), which includes the presence or absence
568 // of the ellipsis; see C++ DR 357).
569 if (OldQType != NewQType &&
570 (OldType->getNumArgs() != NewType->getNumArgs() ||
571 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000572 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000573 return true;
574
575 // C++ [temp.over.link]p4:
576 // The signature of a function template consists of its function
577 // signature, its return type and its template parameter list. The names
578 // of the template parameters are significant only for establishing the
579 // relationship between the template parameters and the rest of the
580 // signature.
581 //
582 // We check the return type and template parameter lists for function
583 // templates first; the remaining checks follow.
584 if (NewTemplate &&
585 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
586 OldTemplate->getTemplateParameters(),
587 false, TPL_TemplateMatch) ||
588 OldType->getResultType() != NewType->getResultType()))
589 return true;
590
591 // If the function is a class member, its signature includes the
592 // cv-qualifiers (if any) on the function itself.
593 //
594 // As part of this, also check whether one of the member functions
595 // is static, in which case they are not overloads (C++
596 // 13.1p2). While not part of the definition of the signature,
597 // this check is important to determine whether these functions
598 // can be overloaded.
599 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
600 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
601 if (OldMethod && NewMethod &&
602 !OldMethod->isStatic() && !NewMethod->isStatic() &&
603 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
604 return true;
605
606 // The signatures match; this is not an overload.
607 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000608}
609
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000610/// TryImplicitConversion - Attempt to perform an implicit conversion
611/// from the given expression (Expr) to the given type (ToType). This
612/// function returns an implicit conversion sequence that can be used
613/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000614///
615/// void f(float f);
616/// void g(int i) { f(i); }
617///
618/// this routine would produce an implicit conversion sequence to
619/// describe the initialization of f from i, which will be a standard
620/// conversion sequence containing an lvalue-to-rvalue conversion (C++
621/// 4.1) followed by a floating-integral conversion (C++ 4.9).
622//
623/// Note that this routine only determines how the conversion can be
624/// performed; it does not actually perform the conversion. As such,
625/// it will not produce any diagnostics if no conversion is available,
626/// but will instead return an implicit conversion sequence of kind
627/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000628///
629/// If @p SuppressUserConversions, then user-defined conversions are
630/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000631/// If @p AllowExplicit, then explicit user-defined conversions are
632/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000633ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000634Sema::TryImplicitConversion(Expr* From, QualType ToType,
635 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000636 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000637 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000638 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000639 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000640 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000641 return ICS;
642 }
643
644 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000645 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000646 return ICS;
647 }
648
Douglas Gregor5ab11652010-04-17 22:01:05 +0000649 if (SuppressUserConversions) {
650 // C++ [over.ics.user]p4:
651 // A conversion of an expression of class type to the same class
652 // type is given Exact Match rank, and a conversion of an
653 // expression of class type to a base class of that type is
654 // given Conversion rank, in spite of the fact that a copy/move
655 // constructor (i.e., a user-defined conversion function) is
656 // called for those cases.
657 QualType FromType = From->getType();
658 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
659 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
660 IsDerivedFrom(FromType, ToType))) {
661 // We're not in the case above, so there is no conversion that
662 // we can perform.
663 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
664 return ICS;
665 }
666
667 ICS.setStandard();
668 ICS.Standard.setAsIdentityConversion();
669 ICS.Standard.setFromType(FromType);
670 ICS.Standard.setAllToTypes(ToType);
671
672 // We don't actually check at this point whether there is a valid
673 // copy/move constructor, since overloading just assumes that it
674 // exists. When we actually perform initialization, we'll find the
675 // appropriate constructor to copy the returned object, if needed.
676 ICS.Standard.CopyConstructor = 0;
677
678 // Determine whether this is considered a derived-to-base conversion.
679 if (!Context.hasSameUnqualifiedType(FromType, ToType))
680 ICS.Standard.Second = ICK_Derived_To_Base;
681
682 return ICS;
683 }
684
685 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000686 OverloadCandidateSet Conversions(From->getExprLoc());
687 OverloadingResult UserDefResult
688 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000689 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000690
691 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000692 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000693 // C++ [over.ics.user]p4:
694 // A conversion of an expression of class type to the same class
695 // type is given Exact Match rank, and a conversion of an
696 // expression of class type to a base class of that type is
697 // given Conversion rank, in spite of the fact that a copy
698 // constructor (i.e., a user-defined conversion function) is
699 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000700 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000701 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000702 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000703 = Context.getCanonicalType(From->getType().getUnqualifiedType());
704 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000705 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000706 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000707 // Turn this into a "standard" conversion sequence, so that it
708 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000709 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000710 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000711 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000712 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000713 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000714 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000715 ICS.Standard.Second = ICK_Derived_To_Base;
716 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000717 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000718
719 // C++ [over.best.ics]p4:
720 // However, when considering the argument of a user-defined
721 // conversion function that is a candidate by 13.3.1.3 when
722 // invoked for the copying of the temporary in the second step
723 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
724 // 13.3.1.6 in all cases, only standard conversion sequences and
725 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000726 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000727 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000728 }
John McCalle8c8cd22010-01-13 22:30:33 +0000729 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000730 ICS.setAmbiguous();
731 ICS.Ambiguous.setFromType(From->getType());
732 ICS.Ambiguous.setToType(ToType);
733 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
734 Cand != Conversions.end(); ++Cand)
735 if (Cand->Viable)
736 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000737 } else {
John McCall65eb8792010-02-25 01:37:24 +0000738 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000739 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000740
741 return ICS;
742}
743
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000744/// PerformImplicitConversion - Perform an implicit conversion of the
745/// expression From to the type ToType. Returns true if there was an
746/// error, false otherwise. The expression From is replaced with the
747/// converted expression. Flavor is the kind of conversion we're
748/// performing, used in the error message. If @p AllowExplicit,
749/// explicit user-defined conversions are permitted.
750bool
751Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
752 AssignmentAction Action, bool AllowExplicit) {
753 ImplicitConversionSequence ICS;
754 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
755}
756
757bool
758Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
759 AssignmentAction Action, bool AllowExplicit,
760 ImplicitConversionSequence& ICS) {
761 ICS = TryImplicitConversion(From, ToType,
762 /*SuppressUserConversions=*/false,
763 AllowExplicit,
764 /*InOverloadResolution=*/false);
765 return PerformImplicitConversion(From, ToType, ICS, Action);
766}
767
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000768/// \brief Determine whether the conversion from FromType to ToType is a valid
769/// conversion that strips "noreturn" off the nested function type.
770static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
771 QualType ToType, QualType &ResultTy) {
772 if (Context.hasSameUnqualifiedType(FromType, ToType))
773 return false;
774
775 // Strip the noreturn off the type we're converting from; noreturn can
776 // safely be removed.
777 FromType = Context.getNoReturnType(FromType, false);
778 if (!Context.hasSameUnqualifiedType(FromType, ToType))
779 return false;
780
781 ResultTy = FromType;
782 return true;
783}
Douglas Gregor46188682010-05-18 22:42:18 +0000784
785/// \brief Determine whether the conversion from FromType to ToType is a valid
786/// vector conversion.
787///
788/// \param ICK Will be set to the vector conversion kind, if this is a vector
789/// conversion.
790static bool IsVectorConversion(ASTContext &Context, QualType FromType,
791 QualType ToType, ImplicitConversionKind &ICK) {
792 // We need at least one of these types to be a vector type to have a vector
793 // conversion.
794 if (!ToType->isVectorType() && !FromType->isVectorType())
795 return false;
796
797 // Identical types require no conversions.
798 if (Context.hasSameUnqualifiedType(FromType, ToType))
799 return false;
800
801 // There are no conversions between extended vector types, only identity.
802 if (ToType->isExtVectorType()) {
803 // There are no conversions between extended vector types other than the
804 // identity conversion.
805 if (FromType->isExtVectorType())
806 return false;
807
808 // Vector splat from any arithmetic type to a vector.
809 if (!FromType->isVectorType() && FromType->isArithmeticType()) {
810 ICK = ICK_Vector_Splat;
811 return true;
812 }
813 }
814
815 // If lax vector conversions are permitted and the vector types are of the
816 // same size, we can perform the conversion.
817 if (Context.getLangOptions().LaxVectorConversions &&
818 FromType->isVectorType() && ToType->isVectorType() &&
819 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
820 ICK = ICK_Vector_Conversion;
821 return true;
822 }
823
824 return false;
825}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000826
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000827/// IsStandardConversion - Determines whether there is a standard
828/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
829/// expression From to the type ToType. Standard conversion sequences
830/// only consider non-class types; for conversions that involve class
831/// types, use TryImplicitConversion. If a conversion exists, SCS will
832/// contain the standard conversion sequence required to perform this
833/// conversion and this routine will return true. Otherwise, this
834/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000835bool
836Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000837 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000838 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839 QualType FromType = From->getType();
840
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000841 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000842 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000843 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000844 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000845 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000846 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000848 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000849 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000850 if (FromType->isRecordType() || ToType->isRecordType()) {
851 if (getLangOptions().CPlusPlus)
852 return false;
853
Mike Stump11289f42009-09-09 15:08:12 +0000854 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000855 }
856
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000857 // The first conversion can be an lvalue-to-rvalue conversion,
858 // array-to-pointer conversion, or function-to-pointer conversion
859 // (C++ 4p1).
860
Douglas Gregor980fb162010-04-29 18:24:40 +0000861 if (FromType == Context.OverloadTy) {
862 DeclAccessPair AccessPair;
863 if (FunctionDecl *Fn
864 = ResolveAddressOfOverloadedFunction(From, ToType, false,
865 AccessPair)) {
866 // We were able to resolve the address of the overloaded function,
867 // so we can convert to the type of that function.
868 FromType = Fn->getType();
869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
870 if (!Method->isStatic()) {
871 Type *ClassType
872 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
873 FromType = Context.getMemberPointerType(FromType, ClassType);
874 }
875 }
876
877 // If the "from" expression takes the address of the overloaded
878 // function, update the type of the resulting expression accordingly.
879 if (FromType->getAs<FunctionType>())
880 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
881 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
882 FromType = Context.getPointerType(FromType);
883
884 // Check that we've computed the proper type after overload resolution.
885 assert(Context.hasSameType(FromType,
886 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
887 } else {
888 return false;
889 }
890 }
Mike Stump11289f42009-09-09 15:08:12 +0000891 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000892 // An lvalue (3.10) of a non-function, non-array type T can be
893 // converted to an rvalue.
894 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000895 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000896 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000897 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000898 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000899
900 // If T is a non-class type, the type of the rvalue is the
901 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000902 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
903 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000904 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000905 } else if (FromType->isArrayType()) {
906 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000907 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000908
909 // An lvalue or rvalue of type "array of N T" or "array of unknown
910 // bound of T" can be converted to an rvalue of type "pointer to
911 // T" (C++ 4.2p1).
912 FromType = Context.getArrayDecayedType(FromType);
913
914 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
915 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000916 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000917
918 // For the purpose of ranking in overload resolution
919 // (13.3.3.1.1), this conversion is considered an
920 // array-to-pointer conversion followed by a qualification
921 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000922 SCS.Second = ICK_Identity;
923 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000924 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000925 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000926 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000927 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
928 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000929 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000930
931 // An lvalue of function type T can be converted to an rvalue of
932 // type "pointer to T." The result is a pointer to the
933 // function. (C++ 4.3p1).
934 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000935 } else {
936 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000937 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000939 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000940
941 // The second conversion can be an integral promotion, floating
942 // point promotion, integral conversion, floating point conversion,
943 // floating-integral conversion, pointer conversion,
944 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000945 // For overloading in C, this can also be a "compatible-type"
946 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000947 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000948 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000949 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000950 // The unqualified versions of the types are the same: there's no
951 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000952 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000953 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000954 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000955 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000957 } else if (IsFloatingPointPromotion(FromType, ToType)) {
958 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000959 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000960 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000961 } else if (IsComplexPromotion(FromType, ToType)) {
962 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000963 SCS.Second = ICK_Complex_Promotion;
964 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000965 } else if (FromType->isIntegralOrEnumerationType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000966 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000967 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000968 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000970 } else if (FromType->isComplexType() && ToType->isComplexType()) {
971 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000972 SCS.Second = ICK_Complex_Conversion;
973 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000974 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
975 (ToType->isComplexType() && FromType->isArithmeticType())) {
976 // Complex-real conversions (C99 6.3.1.7)
977 SCS.Second = ICK_Complex_Real;
978 FromType = ToType.getUnqualifiedType();
979 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
980 // Floating point conversions (C++ 4.8).
981 SCS.Second = ICK_Floating_Conversion;
982 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000983 } else if ((FromType->isFloatingType() &&
984 ToType->isIntegralType() && (!ToType->isBooleanType() &&
985 !ToType->isEnumeralType())) ||
Douglas Gregorb90df602010-06-16 00:17:44 +0000986 (FromType->isIntegralOrEnumerationType() &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000987 ToType->isFloatingType())) {
988 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000989 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000990 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000991 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
992 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000993 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000994 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000995 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000996 } else if (IsMemberPointerConversion(From, FromType, ToType,
997 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000998 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000999 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001000 } else if (ToType->isBooleanType() &&
1001 (FromType->isArithmeticType() ||
1002 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001003 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001004 FromType->isBlockPointerType() ||
1005 FromType->isMemberPointerType() ||
1006 FromType->isNullPtrType())) {
1007 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001008 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001009 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001010 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1011 SCS.Second = SecondICK;
1012 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001013 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001014 Context.typesAreCompatible(ToType, FromType)) {
1015 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001016 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001017 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001018 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1019 // Treat a conversion that strips "noreturn" as an identity conversion.
1020 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001021 } else {
1022 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001023 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001024 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001025 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001026
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001027 QualType CanonFrom;
1028 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001029 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001030 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001031 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001032 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001033 CanonFrom = Context.getCanonicalType(FromType);
1034 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001035 } else {
1036 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001037 SCS.Third = ICK_Identity;
1038
Mike Stump11289f42009-09-09 15:08:12 +00001039 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001040 // [...] Any difference in top-level cv-qualification is
1041 // subsumed by the initialization itself and does not constitute
1042 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001043 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001044 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001045 if (CanonFrom.getLocalUnqualifiedType()
1046 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001047 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1048 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001049 FromType = ToType;
1050 CanonFrom = CanonTo;
1051 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001052 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001053 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001054
1055 // If we have not converted the argument type to the parameter type,
1056 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001057 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001058 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001060 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061}
1062
1063/// IsIntegralPromotion - Determines whether the conversion from the
1064/// expression From (whose potentially-adjusted type is FromType) to
1065/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1066/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001067bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001068 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001069 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001070 if (!To) {
1071 return false;
1072 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073
1074 // An rvalue of type char, signed char, unsigned char, short int, or
1075 // unsigned short int can be converted to an rvalue of type int if
1076 // int can represent all the values of the source type; otherwise,
1077 // the source rvalue can be converted to an rvalue of type unsigned
1078 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001079 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1080 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001081 if (// We can promote any signed, promotable integer type to an int
1082 (FromType->isSignedIntegerType() ||
1083 // We can promote any unsigned integer type whose size is
1084 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001085 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001086 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001088 }
1089
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001090 return To->getKind() == BuiltinType::UInt;
1091 }
1092
1093 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1094 // can be converted to an rvalue of the first of the following types
1095 // that can represent all the values of its underlying type: int,
1096 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001097
1098 // We pre-calculate the promotion type for enum types.
1099 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1100 if (ToType->isIntegerType())
1101 return Context.hasSameUnqualifiedType(ToType,
1102 FromEnumType->getDecl()->getPromotionType());
1103
1104 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001105 // Determine whether the type we're converting from is signed or
1106 // unsigned.
1107 bool FromIsSigned;
1108 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001109
1110 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1111 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001112
1113 // The types we'll try to promote to, in the appropriate
1114 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001115 QualType PromoteTypes[6] = {
1116 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001117 Context.LongTy, Context.UnsignedLongTy ,
1118 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001120 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001121 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1122 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001123 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1125 // We found the type that we can promote to. If this is the
1126 // type we wanted, we have a promotion. Otherwise, no
1127 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001128 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 }
1130 }
1131 }
1132
1133 // An rvalue for an integral bit-field (9.6) can be converted to an
1134 // rvalue of type int if int can represent all the values of the
1135 // bit-field; otherwise, it can be converted to unsigned int if
1136 // unsigned int can represent all the values of the bit-field. If
1137 // the bit-field is larger yet, no integral promotion applies to
1138 // it. If the bit-field has an enumerated type, it is treated as any
1139 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001140 // FIXME: We should delay checking of bit-fields until we actually perform the
1141 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001142 using llvm::APSInt;
1143 if (From)
1144 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001145 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +00001146 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1147 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1148 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1149 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001150
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001151 // Are we promoting to an int from a bitfield that fits in an int?
1152 if (BitWidth < ToSize ||
1153 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1154 return To->getKind() == BuiltinType::Int;
1155 }
Mike Stump11289f42009-09-09 15:08:12 +00001156
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001157 // Are we promoting to an unsigned int from an unsigned bitfield
1158 // that fits into an unsigned int?
1159 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1160 return To->getKind() == BuiltinType::UInt;
1161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001163 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001164 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001165 }
Mike Stump11289f42009-09-09 15:08:12 +00001166
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001167 // An rvalue of type bool can be converted to an rvalue of type int,
1168 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001169 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001171 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001172
1173 return false;
1174}
1175
1176/// IsFloatingPointPromotion - Determines whether the conversion from
1177/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1178/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001179bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 /// An rvalue of type float can be converted to an rvalue of type
1181 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001182 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1183 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184 if (FromBuiltin->getKind() == BuiltinType::Float &&
1185 ToBuiltin->getKind() == BuiltinType::Double)
1186 return true;
1187
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001188 // C99 6.3.1.5p1:
1189 // When a float is promoted to double or long double, or a
1190 // double is promoted to long double [...].
1191 if (!getLangOptions().CPlusPlus &&
1192 (FromBuiltin->getKind() == BuiltinType::Float ||
1193 FromBuiltin->getKind() == BuiltinType::Double) &&
1194 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1195 return true;
1196 }
1197
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001198 return false;
1199}
1200
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001201/// \brief Determine if a conversion is a complex promotion.
1202///
1203/// A complex promotion is defined as a complex -> complex conversion
1204/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001205/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001206bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001207 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001208 if (!FromComplex)
1209 return false;
1210
John McCall9dd450b2009-09-21 23:43:11 +00001211 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001212 if (!ToComplex)
1213 return false;
1214
1215 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001216 ToComplex->getElementType()) ||
1217 IsIntegralPromotion(0, FromComplex->getElementType(),
1218 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001219}
1220
Douglas Gregor237f96c2008-11-26 23:31:11 +00001221/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1222/// the pointer type FromPtr to a pointer to type ToPointee, with the
1223/// same type qualifiers as FromPtr has on its pointee type. ToType,
1224/// if non-empty, will be a pointer to ToType that may or may not have
1225/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001226static QualType
1227BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001228 QualType ToPointee, QualType ToType,
1229 ASTContext &Context) {
1230 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1231 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001232 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001233
1234 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001235 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001236 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001237 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001238 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001239
1240 // Build a pointer to ToPointee. It has the right qualifiers
1241 // already.
1242 return Context.getPointerType(ToPointee);
1243 }
1244
1245 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001246 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001247 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1248 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001249}
1250
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001251/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1252/// the FromType, which is an objective-c pointer, to ToType, which may or may
1253/// not have the right set of qualifiers.
1254static QualType
1255BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1256 QualType ToType,
1257 ASTContext &Context) {
1258 QualType CanonFromType = Context.getCanonicalType(FromType);
1259 QualType CanonToType = Context.getCanonicalType(ToType);
1260 Qualifiers Quals = CanonFromType.getQualifiers();
1261
1262 // Exact qualifier match -> return the pointer type we're converting to.
1263 if (CanonToType.getLocalQualifiers() == Quals)
1264 return ToType;
1265
1266 // Just build a canonical type that has the right qualifiers.
1267 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1268}
1269
Mike Stump11289f42009-09-09 15:08:12 +00001270static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001271 bool InOverloadResolution,
1272 ASTContext &Context) {
1273 // Handle value-dependent integral null pointer constants correctly.
1274 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1275 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001276 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001277 return !InOverloadResolution;
1278
Douglas Gregor56751b52009-09-25 04:25:58 +00001279 return Expr->isNullPointerConstant(Context,
1280 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1281 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001282}
Mike Stump11289f42009-09-09 15:08:12 +00001283
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001284/// IsPointerConversion - Determines whether the conversion of the
1285/// expression From, which has the (possibly adjusted) type FromType,
1286/// can be converted to the type ToType via a pointer conversion (C++
1287/// 4.10). If so, returns true and places the converted type (that
1288/// might differ from ToType in its cv-qualifiers at some level) into
1289/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001290///
Douglas Gregora29dc052008-11-27 01:19:21 +00001291/// This routine also supports conversions to and from block pointers
1292/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1293/// pointers to interfaces. FIXME: Once we've determined the
1294/// appropriate overloading rules for Objective-C, we may want to
1295/// split the Objective-C checks into a different routine; however,
1296/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001297/// conversions, so for now they live here. IncompatibleObjC will be
1298/// set if the conversion is an allowed Objective-C conversion that
1299/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001300bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001301 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001302 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001303 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001304 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001305 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1306 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001307
Mike Stump11289f42009-09-09 15:08:12 +00001308 // Conversion from a null pointer constant to any Objective-C pointer type.
1309 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001310 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001311 ConvertedType = ToType;
1312 return true;
1313 }
1314
Douglas Gregor231d1c62008-11-27 00:15:41 +00001315 // Blocks: Block pointers can be converted to void*.
1316 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001317 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001318 ConvertedType = ToType;
1319 return true;
1320 }
1321 // Blocks: A null pointer constant can be converted to a block
1322 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001323 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001324 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001325 ConvertedType = ToType;
1326 return true;
1327 }
1328
Sebastian Redl576fd422009-05-10 18:38:11 +00001329 // If the left-hand-side is nullptr_t, the right side can be a null
1330 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001331 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001332 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001333 ConvertedType = ToType;
1334 return true;
1335 }
1336
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001337 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338 if (!ToTypePtr)
1339 return false;
1340
1341 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001342 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001343 ConvertedType = ToType;
1344 return true;
1345 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001346
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001347 // Beyond this point, both types need to be pointers
1348 // , including objective-c pointers.
1349 QualType ToPointeeType = ToTypePtr->getPointeeType();
1350 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1351 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1352 ToType, Context);
1353 return true;
1354
1355 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001356 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001357 if (!FromTypePtr)
1358 return false;
1359
1360 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001361
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001362 // An rvalue of type "pointer to cv T," where T is an object type,
1363 // can be converted to an rvalue of type "pointer to cv void" (C++
1364 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001365 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001366 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001367 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001368 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001369 return true;
1370 }
1371
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001372 // When we're overloading in C, we allow a special kind of pointer
1373 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001374 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001375 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001376 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001377 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001378 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001379 return true;
1380 }
1381
Douglas Gregor5c407d92008-10-23 00:40:37 +00001382 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001383 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001384 // An rvalue of type "pointer to cv D," where D is a class type,
1385 // can be converted to an rvalue of type "pointer to cv B," where
1386 // B is a base class (clause 10) of D. If B is an inaccessible
1387 // (clause 11) or ambiguous (10.2) base class of D, a program that
1388 // necessitates this conversion is ill-formed. The result of the
1389 // conversion is a pointer to the base class sub-object of the
1390 // derived class object. The null pointer value is converted to
1391 // the null pointer value of the destination type.
1392 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001393 // Note that we do not check for ambiguity or inaccessibility
1394 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001395 if (getLangOptions().CPlusPlus &&
1396 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001397 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001398 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001399 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001400 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001401 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001402 ToType, Context);
1403 return true;
1404 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001405
Douglas Gregora119f102008-12-19 19:13:09 +00001406 return false;
1407}
1408
1409/// isObjCPointerConversion - Determines whether this is an
1410/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1411/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001412bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001413 QualType& ConvertedType,
1414 bool &IncompatibleObjC) {
1415 if (!getLangOptions().ObjC1)
1416 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001417
Steve Naroff7cae42b2009-07-10 23:34:53 +00001418 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001419 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001420 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001421 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001422
Steve Naroff7cae42b2009-07-10 23:34:53 +00001423 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001424 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001425 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001426 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001427 ConvertedType = ToType;
1428 return true;
1429 }
1430 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001431 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001432 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001433 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001434 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001435 ConvertedType = ToType;
1436 return true;
1437 }
1438 // Objective C++: We're able to convert from a pointer to an
1439 // interface to a pointer to a different interface.
1440 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001441 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1442 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1443 if (getLangOptions().CPlusPlus && LHS && RHS &&
1444 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1445 FromObjCPtr->getPointeeType()))
1446 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001447 ConvertedType = ToType;
1448 return true;
1449 }
1450
1451 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1452 // Okay: this is some kind of implicit downcast of Objective-C
1453 // interfaces, which is permitted. However, we're going to
1454 // complain about it.
1455 IncompatibleObjC = true;
1456 ConvertedType = FromType;
1457 return true;
1458 }
Mike Stump11289f42009-09-09 15:08:12 +00001459 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001460 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001461 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001462 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001463 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001464 else if (const BlockPointerType *ToBlockPtr =
1465 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001466 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001467 // to a block pointer type.
1468 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1469 ConvertedType = ToType;
1470 return true;
1471 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001472 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001473 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001474 else if (FromType->getAs<BlockPointerType>() &&
1475 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1476 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001477 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001478 ConvertedType = ToType;
1479 return true;
1480 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001481 else
Douglas Gregora119f102008-12-19 19:13:09 +00001482 return false;
1483
Douglas Gregor033f56d2008-12-23 00:53:59 +00001484 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001485 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001486 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001487 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001488 FromPointeeType = FromBlockPtr->getPointeeType();
1489 else
Douglas Gregora119f102008-12-19 19:13:09 +00001490 return false;
1491
Douglas Gregora119f102008-12-19 19:13:09 +00001492 // If we have pointers to pointers, recursively check whether this
1493 // is an Objective-C conversion.
1494 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1495 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1496 IncompatibleObjC)) {
1497 // We always complain about this conversion.
1498 IncompatibleObjC = true;
1499 ConvertedType = ToType;
1500 return true;
1501 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001502 // Allow conversion of pointee being objective-c pointer to another one;
1503 // as in I* to id.
1504 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1505 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1506 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1507 IncompatibleObjC)) {
1508 ConvertedType = ToType;
1509 return true;
1510 }
1511
Douglas Gregor033f56d2008-12-23 00:53:59 +00001512 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001513 // differences in the argument and result types are in Objective-C
1514 // pointer conversions. If so, we permit the conversion (but
1515 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001516 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001517 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001518 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001519 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001520 if (FromFunctionType && ToFunctionType) {
1521 // If the function types are exactly the same, this isn't an
1522 // Objective-C pointer conversion.
1523 if (Context.getCanonicalType(FromPointeeType)
1524 == Context.getCanonicalType(ToPointeeType))
1525 return false;
1526
1527 // Perform the quick checks that will tell us whether these
1528 // function types are obviously different.
1529 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1530 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1531 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1532 return false;
1533
1534 bool HasObjCConversion = false;
1535 if (Context.getCanonicalType(FromFunctionType->getResultType())
1536 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1537 // Okay, the types match exactly. Nothing to do.
1538 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1539 ToFunctionType->getResultType(),
1540 ConvertedType, IncompatibleObjC)) {
1541 // Okay, we have an Objective-C pointer conversion.
1542 HasObjCConversion = true;
1543 } else {
1544 // Function types are too different. Abort.
1545 return false;
1546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Douglas Gregora119f102008-12-19 19:13:09 +00001548 // Check argument types.
1549 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1550 ArgIdx != NumArgs; ++ArgIdx) {
1551 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1552 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1553 if (Context.getCanonicalType(FromArgType)
1554 == Context.getCanonicalType(ToArgType)) {
1555 // Okay, the types match exactly. Nothing to do.
1556 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1557 ConvertedType, IncompatibleObjC)) {
1558 // Okay, we have an Objective-C pointer conversion.
1559 HasObjCConversion = true;
1560 } else {
1561 // Argument types are too different. Abort.
1562 return false;
1563 }
1564 }
1565
1566 if (HasObjCConversion) {
1567 // We had an Objective-C conversion. Allow this pointer
1568 // conversion, but complain about it.
1569 ConvertedType = ToType;
1570 IncompatibleObjC = true;
1571 return true;
1572 }
1573 }
1574
Sebastian Redl72b597d2009-01-25 19:43:20 +00001575 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001577
1578/// FunctionArgTypesAreEqual - This routine checks two function proto types
1579/// for equlity of their argument types. Caller has already checked that
1580/// they have same number of arguments. This routine assumes that Objective-C
1581/// pointer types which only differ in their protocol qualifiers are equal.
1582bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1583 FunctionProtoType* NewType){
1584 if (!getLangOptions().ObjC1)
1585 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1586 NewType->arg_type_begin());
1587
1588 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1589 N = NewType->arg_type_begin(),
1590 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1591 QualType ToType = (*O);
1592 QualType FromType = (*N);
1593 if (ToType != FromType) {
1594 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1595 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001596 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1597 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1598 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1599 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001600 continue;
1601 }
John McCall8b07ec22010-05-15 11:32:37 +00001602 else if (const ObjCObjectPointerType *PTTo =
1603 ToType->getAs<ObjCObjectPointerType>()) {
1604 if (const ObjCObjectPointerType *PTFr =
1605 FromType->getAs<ObjCObjectPointerType>())
1606 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1607 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001608 }
1609 return false;
1610 }
1611 }
1612 return true;
1613}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001614
Douglas Gregor39c16d42008-10-24 04:54:22 +00001615/// CheckPointerConversion - Check the pointer conversion from the
1616/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001617/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001618/// conversions for which IsPointerConversion has already returned
1619/// true. It returns true and produces a diagnostic if there was an
1620/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001621bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001622 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001623 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001624 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001625 QualType FromType = From->getType();
1626
Douglas Gregor4038cf42010-06-08 17:35:15 +00001627 if (CXXBoolLiteralExpr* LitBool
1628 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1629 if (LitBool->getValue() == false)
1630 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1631 << ToType;
1632
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001633 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1634 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001635 QualType FromPointeeType = FromPtrType->getPointeeType(),
1636 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001637
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001638 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1639 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001640 // We must have a derived-to-base conversion. Check an
1641 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001642 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1643 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001644 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001645 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001646 return true;
1647
1648 // The conversion was successful.
1649 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001650 }
1651 }
Mike Stump11289f42009-09-09 15:08:12 +00001652 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001653 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001654 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001655 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001656 // Objective-C++ conversions are always okay.
1657 // FIXME: We should have a different class of conversions for the
1658 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001659 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001660 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001661
Steve Naroff7cae42b2009-07-10 23:34:53 +00001662 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001663 return false;
1664}
1665
Sebastian Redl72b597d2009-01-25 19:43:20 +00001666/// IsMemberPointerConversion - Determines whether the conversion of the
1667/// expression From, which has the (possibly adjusted) type FromType, can be
1668/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1669/// If so, returns true and places the converted type (that might differ from
1670/// ToType in its cv-qualifiers at some level) into ConvertedType.
1671bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001672 QualType ToType,
1673 bool InOverloadResolution,
1674 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001675 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001676 if (!ToTypePtr)
1677 return false;
1678
1679 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001680 if (From->isNullPointerConstant(Context,
1681 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1682 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001683 ConvertedType = ToType;
1684 return true;
1685 }
1686
1687 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001688 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001689 if (!FromTypePtr)
1690 return false;
1691
1692 // A pointer to member of B can be converted to a pointer to member of D,
1693 // where D is derived from B (C++ 4.11p2).
1694 QualType FromClass(FromTypePtr->getClass(), 0);
1695 QualType ToClass(ToTypePtr->getClass(), 0);
1696 // FIXME: What happens when these are dependent? Is this function even called?
1697
1698 if (IsDerivedFrom(ToClass, FromClass)) {
1699 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1700 ToClass.getTypePtr());
1701 return true;
1702 }
1703
1704 return false;
1705}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001706
Sebastian Redl72b597d2009-01-25 19:43:20 +00001707/// CheckMemberPointerConversion - Check the member pointer conversion from the
1708/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001709/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001710/// for which IsMemberPointerConversion has already returned true. It returns
1711/// true and produces a diagnostic if there was an error, or returns false
1712/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001713bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001714 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001715 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001716 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001717 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001718 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001719 if (!FromPtrType) {
1720 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001721 assert(From->isNullPointerConstant(Context,
1722 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001723 "Expr must be null pointer constant!");
1724 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001725 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001726 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001727
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001728 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001729 assert(ToPtrType && "No member pointer cast has a target type "
1730 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001731
Sebastian Redled8f2002009-01-28 18:33:18 +00001732 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1733 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001734
Sebastian Redled8f2002009-01-28 18:33:18 +00001735 // FIXME: What about dependent types?
1736 assert(FromClass->isRecordType() && "Pointer into non-class.");
1737 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001738
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001739 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001740 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001741 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1742 assert(DerivationOkay &&
1743 "Should not have been called if derivation isn't OK.");
1744 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001745
Sebastian Redled8f2002009-01-28 18:33:18 +00001746 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1747 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001748 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1749 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1750 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1751 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001752 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001753
Douglas Gregor89ee6822009-02-28 01:32:25 +00001754 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001755 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1756 << FromClass << ToClass << QualType(VBase, 0)
1757 << From->getSourceRange();
1758 return true;
1759 }
1760
John McCall5b0829a2010-02-10 09:31:12 +00001761 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001762 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1763 Paths.front(),
1764 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001765
Anders Carlssond7923c62009-08-22 23:33:40 +00001766 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001767 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001768 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001769 return false;
1770}
1771
Douglas Gregor9a657932008-10-21 23:43:52 +00001772/// IsQualificationConversion - Determines whether the conversion from
1773/// an rvalue of type FromType to ToType is a qualification conversion
1774/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001775bool
1776Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001777 FromType = Context.getCanonicalType(FromType);
1778 ToType = Context.getCanonicalType(ToType);
1779
1780 // If FromType and ToType are the same type, this is not a
1781 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001782 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001783 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001784
Douglas Gregor9a657932008-10-21 23:43:52 +00001785 // (C++ 4.4p4):
1786 // A conversion can add cv-qualifiers at levels other than the first
1787 // in multi-level pointers, subject to the following rules: [...]
1788 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001789 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001790 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001791 // Within each iteration of the loop, we check the qualifiers to
1792 // determine if this still looks like a qualification
1793 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001794 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001795 // until there are no more pointers or pointers-to-members left to
1796 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001797 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001798
1799 // -- for every j > 0, if const is in cv 1,j then const is in cv
1800 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001801 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001802 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001803
Douglas Gregor9a657932008-10-21 23:43:52 +00001804 // -- if the cv 1,j and cv 2,j are different, then const is in
1805 // every cv for 0 < k < j.
1806 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001807 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001808 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001809
Douglas Gregor9a657932008-10-21 23:43:52 +00001810 // Keep track of whether all prior cv-qualifiers in the "to" type
1811 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001812 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001813 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001814 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001815
1816 // We are left with FromType and ToType being the pointee types
1817 // after unwrapping the original FromType and ToType the same number
1818 // of types. If we unwrapped any pointers, and if FromType and
1819 // ToType have the same unqualified type (since we checked
1820 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001821 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001822}
1823
Douglas Gregor576e98c2009-01-30 23:27:23 +00001824/// Determines whether there is a user-defined conversion sequence
1825/// (C++ [over.ics.user]) that converts expression From to the type
1826/// ToType. If such a conversion exists, User will contain the
1827/// user-defined conversion sequence that performs such a conversion
1828/// and this routine will return true. Otherwise, this routine returns
1829/// false and User is unspecified.
1830///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001831/// \param AllowExplicit true if the conversion should consider C++0x
1832/// "explicit" conversion functions as well as non-explicit conversion
1833/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001834OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1835 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001836 OverloadCandidateSet& CandidateSet,
1837 bool AllowExplicit) {
1838 // Whether we will only visit constructors.
1839 bool ConstructorsOnly = false;
1840
1841 // If the type we are conversion to is a class type, enumerate its
1842 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001843 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001844 // C++ [over.match.ctor]p1:
1845 // When objects of class type are direct-initialized (8.5), or
1846 // copy-initialized from an expression of the same or a
1847 // derived class type (8.5), overload resolution selects the
1848 // constructor. [...] For copy-initialization, the candidate
1849 // functions are all the converting constructors (12.3.1) of
1850 // that class. The argument list is the expression-list within
1851 // the parentheses of the initializer.
1852 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1853 (From->getType()->getAs<RecordType>() &&
1854 IsDerivedFrom(From->getType(), ToType)))
1855 ConstructorsOnly = true;
1856
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001857 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1858 // We're not going to find any constructors.
1859 } else if (CXXRecordDecl *ToRecordDecl
1860 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001861 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001862 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001863 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001864 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001865 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001866 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001867 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001868 NamedDecl *D = *Con;
1869 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1870
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001871 // Find the constructor (which may be a template).
1872 CXXConstructorDecl *Constructor = 0;
1873 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001874 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001875 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001876 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001877 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1878 else
John McCalla0296f72010-03-19 07:35:19 +00001879 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001880
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001881 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001882 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001883 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001884 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001885 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001886 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001887 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001888 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001889 // Allow one user-defined conversion when user specifies a
1890 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001891 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001892 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001893 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001894 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001895 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001896 }
1897 }
1898
Douglas Gregor5ab11652010-04-17 22:01:05 +00001899 // Enumerate conversion functions, if we're allowed to.
1900 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001901 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001902 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001903 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001904 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001905 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001906 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001907 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1908 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001909 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001910 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001911 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001912 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001913 DeclAccessPair FoundDecl = I.getPair();
1914 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001915 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1916 if (isa<UsingShadowDecl>(D))
1917 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1918
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001919 CXXConversionDecl *Conv;
1920 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001921 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1922 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001923 else
John McCallda4458e2010-03-31 01:36:47 +00001924 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001925
1926 if (AllowExplicit || !Conv->isExplicit()) {
1927 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001928 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001929 ActingContext, From, ToType,
1930 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001931 else
John McCalla0296f72010-03-19 07:35:19 +00001932 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001933 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001934 }
1935 }
1936 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001937 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001938
1939 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001940 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001941 case OR_Success:
1942 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001943 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001944 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1945 // C++ [over.ics.user]p1:
1946 // If the user-defined conversion is specified by a
1947 // constructor (12.3.1), the initial standard conversion
1948 // sequence converts the source type to the type required by
1949 // the argument of the constructor.
1950 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001951 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001952 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001953 User.EllipsisConversion = true;
1954 else {
1955 User.Before = Best->Conversions[0].Standard;
1956 User.EllipsisConversion = false;
1957 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001958 User.ConversionFunction = Constructor;
1959 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001960 User.After.setFromType(
1961 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001962 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001963 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001964 } else if (CXXConversionDecl *Conversion
1965 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1966 // C++ [over.ics.user]p1:
1967 //
1968 // [...] If the user-defined conversion is specified by a
1969 // conversion function (12.3.2), the initial standard
1970 // conversion sequence converts the source type to the
1971 // implicit object parameter of the conversion function.
1972 User.Before = Best->Conversions[0].Standard;
1973 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001974 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001975
1976 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001977 // The second standard conversion sequence converts the
1978 // result of the user-defined conversion to the target type
1979 // for the sequence. Since an implicit conversion sequence
1980 // is an initialization, the special rules for
1981 // initialization by user-defined conversion apply when
1982 // selecting the best user-defined conversion for a
1983 // user-defined conversion sequence (see 13.3.3 and
1984 // 13.3.3.1).
1985 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001986 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001987 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001988 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001989 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001990 }
Mike Stump11289f42009-09-09 15:08:12 +00001991
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001992 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001993 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001994 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001995 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001996 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001997
1998 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001999 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002000 }
2001
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002002 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002003}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002004
2005bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002006Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002007 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002008 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002009 OverloadingResult OvResult =
2010 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002011 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002012 if (OvResult == OR_Ambiguous)
2013 Diag(From->getSourceRange().getBegin(),
2014 diag::err_typecheck_ambiguous_condition)
2015 << From->getType() << ToType << From->getSourceRange();
2016 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2017 Diag(From->getSourceRange().getBegin(),
2018 diag::err_typecheck_nonviable_condition)
2019 << From->getType() << ToType << From->getSourceRange();
2020 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002021 return false;
John McCallad907772010-01-12 07:18:19 +00002022 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002023 return true;
2024}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002025
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002026/// CompareImplicitConversionSequences - Compare two implicit
2027/// conversion sequences to determine whether one is better than the
2028/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002029ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002030Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2031 const ImplicitConversionSequence& ICS2)
2032{
2033 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2034 // conversion sequences (as defined in 13.3.3.1)
2035 // -- a standard conversion sequence (13.3.3.1.1) is a better
2036 // conversion sequence than a user-defined conversion sequence or
2037 // an ellipsis conversion sequence, and
2038 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2039 // conversion sequence than an ellipsis conversion sequence
2040 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002041 //
John McCall0d1da222010-01-12 00:44:57 +00002042 // C++0x [over.best.ics]p10:
2043 // For the purpose of ranking implicit conversion sequences as
2044 // described in 13.3.3.2, the ambiguous conversion sequence is
2045 // treated as a user-defined sequence that is indistinguishable
2046 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002047 if (ICS1.getKindRank() < ICS2.getKindRank())
2048 return ImplicitConversionSequence::Better;
2049 else if (ICS2.getKindRank() < ICS1.getKindRank())
2050 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002051
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002052 // The following checks require both conversion sequences to be of
2053 // the same kind.
2054 if (ICS1.getKind() != ICS2.getKind())
2055 return ImplicitConversionSequence::Indistinguishable;
2056
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002057 // Two implicit conversion sequences of the same form are
2058 // indistinguishable conversion sequences unless one of the
2059 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002060 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002061 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002062 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002063 // User-defined conversion sequence U1 is a better conversion
2064 // sequence than another user-defined conversion sequence U2 if
2065 // they contain the same user-defined conversion function or
2066 // constructor and if the second standard conversion sequence of
2067 // U1 is better than the second standard conversion sequence of
2068 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002069 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002070 ICS2.UserDefined.ConversionFunction)
2071 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2072 ICS2.UserDefined.After);
2073 }
2074
2075 return ImplicitConversionSequence::Indistinguishable;
2076}
2077
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002078static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2079 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2080 Qualifiers Quals;
2081 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2082 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2083 }
2084
2085 return Context.hasSameUnqualifiedType(T1, T2);
2086}
2087
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002088// Per 13.3.3.2p3, compare the given standard conversion sequences to
2089// determine if one is a proper subset of the other.
2090static ImplicitConversionSequence::CompareKind
2091compareStandardConversionSubsets(ASTContext &Context,
2092 const StandardConversionSequence& SCS1,
2093 const StandardConversionSequence& SCS2) {
2094 ImplicitConversionSequence::CompareKind Result
2095 = ImplicitConversionSequence::Indistinguishable;
2096
Douglas Gregore87561a2010-05-23 22:10:15 +00002097 // the identity conversion sequence is considered to be a subsequence of
2098 // any non-identity conversion sequence
2099 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2100 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2101 return ImplicitConversionSequence::Better;
2102 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2103 return ImplicitConversionSequence::Worse;
2104 }
2105
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002106 if (SCS1.Second != SCS2.Second) {
2107 if (SCS1.Second == ICK_Identity)
2108 Result = ImplicitConversionSequence::Better;
2109 else if (SCS2.Second == ICK_Identity)
2110 Result = ImplicitConversionSequence::Worse;
2111 else
2112 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002113 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002114 return ImplicitConversionSequence::Indistinguishable;
2115
2116 if (SCS1.Third == SCS2.Third) {
2117 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2118 : ImplicitConversionSequence::Indistinguishable;
2119 }
2120
2121 if (SCS1.Third == ICK_Identity)
2122 return Result == ImplicitConversionSequence::Worse
2123 ? ImplicitConversionSequence::Indistinguishable
2124 : ImplicitConversionSequence::Better;
2125
2126 if (SCS2.Third == ICK_Identity)
2127 return Result == ImplicitConversionSequence::Better
2128 ? ImplicitConversionSequence::Indistinguishable
2129 : ImplicitConversionSequence::Worse;
2130
2131 return ImplicitConversionSequence::Indistinguishable;
2132}
2133
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002134/// CompareStandardConversionSequences - Compare two standard
2135/// conversion sequences to determine whether one is better than the
2136/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002137ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002138Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2139 const StandardConversionSequence& SCS2)
2140{
2141 // Standard conversion sequence S1 is a better conversion sequence
2142 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2143
2144 // -- S1 is a proper subsequence of S2 (comparing the conversion
2145 // sequences in the canonical form defined by 13.3.3.1.1,
2146 // excluding any Lvalue Transformation; the identity conversion
2147 // sequence is considered to be a subsequence of any
2148 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002149 if (ImplicitConversionSequence::CompareKind CK
2150 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2151 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002152
2153 // -- the rank of S1 is better than the rank of S2 (by the rules
2154 // defined below), or, if not that,
2155 ImplicitConversionRank Rank1 = SCS1.getRank();
2156 ImplicitConversionRank Rank2 = SCS2.getRank();
2157 if (Rank1 < Rank2)
2158 return ImplicitConversionSequence::Better;
2159 else if (Rank2 < Rank1)
2160 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002161
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002162 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2163 // are indistinguishable unless one of the following rules
2164 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002165
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002166 // A conversion that is not a conversion of a pointer, or
2167 // pointer to member, to bool is better than another conversion
2168 // that is such a conversion.
2169 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2170 return SCS2.isPointerConversionToBool()
2171 ? ImplicitConversionSequence::Better
2172 : ImplicitConversionSequence::Worse;
2173
Douglas Gregor5c407d92008-10-23 00:40:37 +00002174 // C++ [over.ics.rank]p4b2:
2175 //
2176 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002177 // conversion of B* to A* is better than conversion of B* to
2178 // void*, and conversion of A* to void* is better than conversion
2179 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002180 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002181 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002182 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002183 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002184 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2185 // Exactly one of the conversion sequences is a conversion to
2186 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002187 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2188 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002189 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2190 // Neither conversion sequence converts to a void pointer; compare
2191 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002192 if (ImplicitConversionSequence::CompareKind DerivedCK
2193 = CompareDerivedToBaseConversions(SCS1, SCS2))
2194 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002195 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2196 // Both conversion sequences are conversions to void
2197 // pointers. Compare the source types to determine if there's an
2198 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002199 QualType FromType1 = SCS1.getFromType();
2200 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002201
2202 // Adjust the types we're converting from via the array-to-pointer
2203 // conversion, if we need to.
2204 if (SCS1.First == ICK_Array_To_Pointer)
2205 FromType1 = Context.getArrayDecayedType(FromType1);
2206 if (SCS2.First == ICK_Array_To_Pointer)
2207 FromType2 = Context.getArrayDecayedType(FromType2);
2208
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002209 QualType FromPointee1
2210 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2211 QualType FromPointee2
2212 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002213
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002214 if (IsDerivedFrom(FromPointee2, FromPointee1))
2215 return ImplicitConversionSequence::Better;
2216 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2217 return ImplicitConversionSequence::Worse;
2218
2219 // Objective-C++: If one interface is more specific than the
2220 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002221 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2222 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002223 if (FromIface1 && FromIface1) {
2224 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2225 return ImplicitConversionSequence::Better;
2226 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2227 return ImplicitConversionSequence::Worse;
2228 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002229 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002230
2231 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2232 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002233 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002234 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002235 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002236
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002237 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002238 // C++0x [over.ics.rank]p3b4:
2239 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2240 // implicit object parameter of a non-static member function declared
2241 // without a ref-qualifier, and S1 binds an rvalue reference to an
2242 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002243 // FIXME: We don't know if we're dealing with the implicit object parameter,
2244 // or if the member function in this case has a ref qualifier.
2245 // (Of course, we don't have ref qualifiers yet.)
2246 if (SCS1.RRefBinding != SCS2.RRefBinding)
2247 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2248 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002249
2250 // C++ [over.ics.rank]p3b4:
2251 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2252 // which the references refer are the same type except for
2253 // top-level cv-qualifiers, and the type to which the reference
2254 // initialized by S2 refers is more cv-qualified than the type
2255 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002256 QualType T1 = SCS1.getToType(2);
2257 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002258 T1 = Context.getCanonicalType(T1);
2259 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002260 Qualifiers T1Quals, T2Quals;
2261 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2262 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2263 if (UnqualT1 == UnqualT2) {
2264 // If the type is an array type, promote the element qualifiers to the type
2265 // for comparison.
2266 if (isa<ArrayType>(T1) && T1Quals)
2267 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2268 if (isa<ArrayType>(T2) && T2Quals)
2269 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002270 if (T2.isMoreQualifiedThan(T1))
2271 return ImplicitConversionSequence::Better;
2272 else if (T1.isMoreQualifiedThan(T2))
2273 return ImplicitConversionSequence::Worse;
2274 }
2275 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002276
2277 return ImplicitConversionSequence::Indistinguishable;
2278}
2279
2280/// CompareQualificationConversions - Compares two standard conversion
2281/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002282/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2283ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002284Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002285 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002286 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002287 // -- S1 and S2 differ only in their qualification conversion and
2288 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2289 // cv-qualification signature of type T1 is a proper subset of
2290 // the cv-qualification signature of type T2, and S1 is not the
2291 // deprecated string literal array-to-pointer conversion (4.2).
2292 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2293 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2294 return ImplicitConversionSequence::Indistinguishable;
2295
2296 // FIXME: the example in the standard doesn't use a qualification
2297 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002298 QualType T1 = SCS1.getToType(2);
2299 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002300 T1 = Context.getCanonicalType(T1);
2301 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002302 Qualifiers T1Quals, T2Quals;
2303 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2304 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002305
2306 // If the types are the same, we won't learn anything by unwrapped
2307 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002308 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002309 return ImplicitConversionSequence::Indistinguishable;
2310
Chandler Carruth607f38e2009-12-29 07:16:59 +00002311 // If the type is an array type, promote the element qualifiers to the type
2312 // for comparison.
2313 if (isa<ArrayType>(T1) && T1Quals)
2314 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2315 if (isa<ArrayType>(T2) && T2Quals)
2316 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2317
Mike Stump11289f42009-09-09 15:08:12 +00002318 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002319 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002320 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002321 // Within each iteration of the loop, we check the qualifiers to
2322 // determine if this still looks like a qualification
2323 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002324 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002325 // until there are no more pointers or pointers-to-members left
2326 // to unwrap. This essentially mimics what
2327 // IsQualificationConversion does, but here we're checking for a
2328 // strict subset of qualifiers.
2329 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2330 // The qualifiers are the same, so this doesn't tell us anything
2331 // about how the sequences rank.
2332 ;
2333 else if (T2.isMoreQualifiedThan(T1)) {
2334 // T1 has fewer qualifiers, so it could be the better sequence.
2335 if (Result == ImplicitConversionSequence::Worse)
2336 // Neither has qualifiers that are a subset of the other's
2337 // qualifiers.
2338 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002339
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002340 Result = ImplicitConversionSequence::Better;
2341 } else if (T1.isMoreQualifiedThan(T2)) {
2342 // T2 has fewer qualifiers, so it could be the better sequence.
2343 if (Result == ImplicitConversionSequence::Better)
2344 // Neither has qualifiers that are a subset of the other's
2345 // qualifiers.
2346 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002347
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002348 Result = ImplicitConversionSequence::Worse;
2349 } else {
2350 // Qualifiers are disjoint.
2351 return ImplicitConversionSequence::Indistinguishable;
2352 }
2353
2354 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002355 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002356 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002357 }
2358
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002359 // Check that the winning standard conversion sequence isn't using
2360 // the deprecated string literal array to pointer conversion.
2361 switch (Result) {
2362 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002363 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002364 Result = ImplicitConversionSequence::Indistinguishable;
2365 break;
2366
2367 case ImplicitConversionSequence::Indistinguishable:
2368 break;
2369
2370 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002371 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002372 Result = ImplicitConversionSequence::Indistinguishable;
2373 break;
2374 }
2375
2376 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002377}
2378
Douglas Gregor5c407d92008-10-23 00:40:37 +00002379/// CompareDerivedToBaseConversions - Compares two standard conversion
2380/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002381/// various kinds of derived-to-base conversions (C++
2382/// [over.ics.rank]p4b3). As part of these checks, we also look at
2383/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002384ImplicitConversionSequence::CompareKind
2385Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2386 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002387 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002388 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002389 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002390 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002391
2392 // Adjust the types we're converting from via the array-to-pointer
2393 // conversion, if we need to.
2394 if (SCS1.First == ICK_Array_To_Pointer)
2395 FromType1 = Context.getArrayDecayedType(FromType1);
2396 if (SCS2.First == ICK_Array_To_Pointer)
2397 FromType2 = Context.getArrayDecayedType(FromType2);
2398
2399 // Canonicalize all of the types.
2400 FromType1 = Context.getCanonicalType(FromType1);
2401 ToType1 = Context.getCanonicalType(ToType1);
2402 FromType2 = Context.getCanonicalType(FromType2);
2403 ToType2 = Context.getCanonicalType(ToType2);
2404
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002405 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002406 //
2407 // If class B is derived directly or indirectly from class A and
2408 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002409 //
2410 // For Objective-C, we let A, B, and C also be Objective-C
2411 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002412
2413 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002414 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002415 SCS2.Second == ICK_Pointer_Conversion &&
2416 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2417 FromType1->isPointerType() && FromType2->isPointerType() &&
2418 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002419 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002420 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002421 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002422 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002423 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002424 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002425 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002426 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002427
John McCall8b07ec22010-05-15 11:32:37 +00002428 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2429 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2430 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2431 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002432
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002433 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002434 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2435 if (IsDerivedFrom(ToPointee1, ToPointee2))
2436 return ImplicitConversionSequence::Better;
2437 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2438 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002439
2440 if (ToIface1 && ToIface2) {
2441 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2442 return ImplicitConversionSequence::Better;
2443 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2444 return ImplicitConversionSequence::Worse;
2445 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002446 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002447
2448 // -- conversion of B* to A* is better than conversion of C* to A*,
2449 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2450 if (IsDerivedFrom(FromPointee2, FromPointee1))
2451 return ImplicitConversionSequence::Better;
2452 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2453 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002454
Douglas Gregor237f96c2008-11-26 23:31:11 +00002455 if (FromIface1 && FromIface2) {
2456 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2457 return ImplicitConversionSequence::Better;
2458 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2459 return ImplicitConversionSequence::Worse;
2460 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002461 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002462 }
2463
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002464 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002465 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2466 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2467 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2468 const MemberPointerType * FromMemPointer1 =
2469 FromType1->getAs<MemberPointerType>();
2470 const MemberPointerType * ToMemPointer1 =
2471 ToType1->getAs<MemberPointerType>();
2472 const MemberPointerType * FromMemPointer2 =
2473 FromType2->getAs<MemberPointerType>();
2474 const MemberPointerType * ToMemPointer2 =
2475 ToType2->getAs<MemberPointerType>();
2476 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2477 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2478 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2479 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2480 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2481 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2482 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2483 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002484 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002485 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2486 if (IsDerivedFrom(ToPointee1, ToPointee2))
2487 return ImplicitConversionSequence::Worse;
2488 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2489 return ImplicitConversionSequence::Better;
2490 }
2491 // conversion of B::* to C::* is better than conversion of A::* to C::*
2492 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2493 if (IsDerivedFrom(FromPointee1, FromPointee2))
2494 return ImplicitConversionSequence::Better;
2495 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2496 return ImplicitConversionSequence::Worse;
2497 }
2498 }
2499
Douglas Gregor5ab11652010-04-17 22:01:05 +00002500 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002501 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002502 // -- binding of an expression of type C to a reference of type
2503 // B& is better than binding an expression of type C to a
2504 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002505 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2506 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002507 if (IsDerivedFrom(ToType1, ToType2))
2508 return ImplicitConversionSequence::Better;
2509 else if (IsDerivedFrom(ToType2, ToType1))
2510 return ImplicitConversionSequence::Worse;
2511 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002512
Douglas Gregor2fe98832008-11-03 19:09:14 +00002513 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002514 // -- binding of an expression of type B to a reference of type
2515 // A& is better than binding an expression of type C to a
2516 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002517 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2518 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002519 if (IsDerivedFrom(FromType2, FromType1))
2520 return ImplicitConversionSequence::Better;
2521 else if (IsDerivedFrom(FromType1, FromType2))
2522 return ImplicitConversionSequence::Worse;
2523 }
2524 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002525
Douglas Gregor5c407d92008-10-23 00:40:37 +00002526 return ImplicitConversionSequence::Indistinguishable;
2527}
2528
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002529/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2530/// determine whether they are reference-related,
2531/// reference-compatible, reference-compatible with added
2532/// qualification, or incompatible, for use in C++ initialization by
2533/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2534/// type, and the first type (T1) is the pointee type of the reference
2535/// type being initialized.
2536Sema::ReferenceCompareResult
2537Sema::CompareReferenceRelationship(SourceLocation Loc,
2538 QualType OrigT1, QualType OrigT2,
2539 bool& DerivedToBase) {
2540 assert(!OrigT1->isReferenceType() &&
2541 "T1 must be the pointee type of the reference type");
2542 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2543
2544 QualType T1 = Context.getCanonicalType(OrigT1);
2545 QualType T2 = Context.getCanonicalType(OrigT2);
2546 Qualifiers T1Quals, T2Quals;
2547 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2548 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2549
2550 // C++ [dcl.init.ref]p4:
2551 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2552 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2553 // T1 is a base class of T2.
2554 if (UnqualT1 == UnqualT2)
2555 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002556 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002557 IsDerivedFrom(UnqualT2, UnqualT1))
2558 DerivedToBase = true;
2559 else
2560 return Ref_Incompatible;
2561
2562 // At this point, we know that T1 and T2 are reference-related (at
2563 // least).
2564
2565 // If the type is an array type, promote the element qualifiers to the type
2566 // for comparison.
2567 if (isa<ArrayType>(T1) && T1Quals)
2568 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2569 if (isa<ArrayType>(T2) && T2Quals)
2570 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2571
2572 // C++ [dcl.init.ref]p4:
2573 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2574 // reference-related to T2 and cv1 is the same cv-qualification
2575 // as, or greater cv-qualification than, cv2. For purposes of
2576 // overload resolution, cases for which cv1 is greater
2577 // cv-qualification than cv2 are identified as
2578 // reference-compatible with added qualification (see 13.3.3.2).
2579 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2580 return Ref_Compatible;
2581 else if (T1.isMoreQualifiedThan(T2))
2582 return Ref_Compatible_With_Added_Qualification;
2583 else
2584 return Ref_Related;
2585}
2586
2587/// \brief Compute an implicit conversion sequence for reference
2588/// initialization.
2589static ImplicitConversionSequence
2590TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2591 SourceLocation DeclLoc,
2592 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002593 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002594 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2595
2596 // Most paths end in a failed conversion.
2597 ImplicitConversionSequence ICS;
2598 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2599
2600 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2601 QualType T2 = Init->getType();
2602
2603 // If the initializer is the address of an overloaded function, try
2604 // to resolve the overloaded function. If all goes well, T2 is the
2605 // type of the resulting function.
2606 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2607 DeclAccessPair Found;
2608 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2609 false, Found))
2610 T2 = Fn->getType();
2611 }
2612
2613 // Compute some basic properties of the types and the initializer.
2614 bool isRValRef = DeclType->isRValueReferenceType();
2615 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002616 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002617 Sema::ReferenceCompareResult RefRelationship
2618 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2619
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002620
2621 // C++ [over.ics.ref]p3:
2622 // Except for an implicit object parameter, for which see 13.3.1,
2623 // a standard conversion sequence cannot be formed if it requires
2624 // binding an lvalue reference to non-const to an rvalue or
2625 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002626 //
2627 // FIXME: DPG doesn't trust this code. It seems far too early to
2628 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002629 if (isRValRef && InitLvalue == Expr::LV_Valid)
2630 return ICS;
2631
Douglas Gregor870f3742010-04-18 09:22:00 +00002632 // C++0x [dcl.init.ref]p16:
2633 // A reference to type "cv1 T1" is initialized by an expression
2634 // of type "cv2 T2" as follows:
2635
2636 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002637 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2638 // reference-compatible with "cv2 T2," or
2639 //
2640 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2641 if (InitLvalue == Expr::LV_Valid &&
2642 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2643 // C++ [over.ics.ref]p1:
2644 // When a parameter of reference type binds directly (8.5.3)
2645 // to an argument expression, the implicit conversion sequence
2646 // is the identity conversion, unless the argument expression
2647 // has a type that is a derived class of the parameter type,
2648 // in which case the implicit conversion sequence is a
2649 // derived-to-base Conversion (13.3.3.1).
2650 ICS.setStandard();
2651 ICS.Standard.First = ICK_Identity;
2652 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2653 ICS.Standard.Third = ICK_Identity;
2654 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2655 ICS.Standard.setToType(0, T2);
2656 ICS.Standard.setToType(1, T1);
2657 ICS.Standard.setToType(2, T1);
2658 ICS.Standard.ReferenceBinding = true;
2659 ICS.Standard.DirectBinding = true;
2660 ICS.Standard.RRefBinding = false;
2661 ICS.Standard.CopyConstructor = 0;
2662
2663 // Nothing more to do: the inaccessibility/ambiguity check for
2664 // derived-to-base conversions is suppressed when we're
2665 // computing the implicit conversion sequence (C++
2666 // [over.best.ics]p2).
2667 return ICS;
2668 }
2669
2670 // -- has a class type (i.e., T2 is a class type), where T1 is
2671 // not reference-related to T2, and can be implicitly
2672 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2673 // is reference-compatible with "cv3 T3" 92) (this
2674 // conversion is selected by enumerating the applicable
2675 // conversion functions (13.3.1.6) and choosing the best
2676 // one through overload resolution (13.3)),
2677 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2678 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2679 RefRelationship == Sema::Ref_Incompatible) {
2680 CXXRecordDecl *T2RecordDecl
2681 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2682
2683 OverloadCandidateSet CandidateSet(DeclLoc);
2684 const UnresolvedSetImpl *Conversions
2685 = T2RecordDecl->getVisibleConversionFunctions();
2686 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2687 E = Conversions->end(); I != E; ++I) {
2688 NamedDecl *D = *I;
2689 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2690 if (isa<UsingShadowDecl>(D))
2691 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2692
2693 FunctionTemplateDecl *ConvTemplate
2694 = dyn_cast<FunctionTemplateDecl>(D);
2695 CXXConversionDecl *Conv;
2696 if (ConvTemplate)
2697 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2698 else
2699 Conv = cast<CXXConversionDecl>(D);
2700
2701 // If the conversion function doesn't return a reference type,
2702 // it can't be considered for this conversion.
2703 if (Conv->getConversionType()->isLValueReferenceType() &&
2704 (AllowExplicit || !Conv->isExplicit())) {
2705 if (ConvTemplate)
2706 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2707 Init, DeclType, CandidateSet);
2708 else
2709 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2710 DeclType, CandidateSet);
2711 }
2712 }
2713
2714 OverloadCandidateSet::iterator Best;
2715 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2716 case OR_Success:
2717 // C++ [over.ics.ref]p1:
2718 //
2719 // [...] If the parameter binds directly to the result of
2720 // applying a conversion function to the argument
2721 // expression, the implicit conversion sequence is a
2722 // user-defined conversion sequence (13.3.3.1.2), with the
2723 // second standard conversion sequence either an identity
2724 // conversion or, if the conversion function returns an
2725 // entity of a type that is a derived class of the parameter
2726 // type, a derived-to-base Conversion.
2727 if (!Best->FinalConversion.DirectBinding)
2728 break;
2729
2730 ICS.setUserDefined();
2731 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2732 ICS.UserDefined.After = Best->FinalConversion;
2733 ICS.UserDefined.ConversionFunction = Best->Function;
2734 ICS.UserDefined.EllipsisConversion = false;
2735 assert(ICS.UserDefined.After.ReferenceBinding &&
2736 ICS.UserDefined.After.DirectBinding &&
2737 "Expected a direct reference binding!");
2738 return ICS;
2739
2740 case OR_Ambiguous:
2741 ICS.setAmbiguous();
2742 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2743 Cand != CandidateSet.end(); ++Cand)
2744 if (Cand->Viable)
2745 ICS.Ambiguous.addConversion(Cand->Function);
2746 return ICS;
2747
2748 case OR_No_Viable_Function:
2749 case OR_Deleted:
2750 // There was no suitable conversion, or we found a deleted
2751 // conversion; continue with other checks.
2752 break;
2753 }
2754 }
2755
2756 // -- Otherwise, the reference shall be to a non-volatile const
2757 // type (i.e., cv1 shall be const), or the reference shall be an
2758 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002759 //
2760 // We actually handle one oddity of C++ [over.ics.ref] at this
2761 // point, which is that, due to p2 (which short-circuits reference
2762 // binding by only attempting a simple conversion for non-direct
2763 // bindings) and p3's strange wording, we allow a const volatile
2764 // reference to bind to an rvalue. Hence the check for the presence
2765 // of "const" rather than checking for "const" being the only
2766 // qualifier.
2767 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002768 return ICS;
2769
Douglas Gregorf93df192010-04-18 08:46:23 +00002770 // -- if T2 is a class type and
2771 // -- the initializer expression is an rvalue and "cv1 T1"
2772 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002773 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002774 // -- T1 is not reference-related to T2 and the initializer
2775 // expression can be implicitly converted to an rvalue
2776 // of type "cv3 T3" (this conversion is selected by
2777 // enumerating the applicable conversion functions
2778 // (13.3.1.6) and choosing the best one through overload
2779 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002780 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002781 // then the reference is bound to the initializer
2782 // expression rvalue in the first case and to the object
2783 // that is the result of the conversion in the second case
2784 // (or, in either case, to the appropriate base class
2785 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002786 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002787 // We're only checking the first case here, which is a direct
2788 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002789 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2790 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2791 ICS.setStandard();
2792 ICS.Standard.First = ICK_Identity;
2793 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2794 ICS.Standard.Third = ICK_Identity;
2795 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2796 ICS.Standard.setToType(0, T2);
2797 ICS.Standard.setToType(1, T1);
2798 ICS.Standard.setToType(2, T1);
2799 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002800 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002801 ICS.Standard.RRefBinding = isRValRef;
2802 ICS.Standard.CopyConstructor = 0;
2803 return ICS;
2804 }
2805
2806 // -- Otherwise, a temporary of type "cv1 T1" is created and
2807 // initialized from the initializer expression using the
2808 // rules for a non-reference copy initialization (8.5). The
2809 // reference is then bound to the temporary. If T1 is
2810 // reference-related to T2, cv1 must be the same
2811 // cv-qualification as, or greater cv-qualification than,
2812 // cv2; otherwise, the program is ill-formed.
2813 if (RefRelationship == Sema::Ref_Related) {
2814 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2815 // we would be reference-compatible or reference-compatible with
2816 // added qualification. But that wasn't the case, so the reference
2817 // initialization fails.
2818 return ICS;
2819 }
2820
2821 // If at least one of the types is a class type, the types are not
2822 // related, and we aren't allowed any user conversions, the
2823 // reference binding fails. This case is important for breaking
2824 // recursion, since TryImplicitConversion below will attempt to
2825 // create a temporary through the use of a copy constructor.
2826 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2827 (T1->isRecordType() || T2->isRecordType()))
2828 return ICS;
2829
2830 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002831 // When a parameter of reference type is not bound directly to
2832 // an argument expression, the conversion sequence is the one
2833 // required to convert the argument expression to the
2834 // underlying type of the reference according to
2835 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2836 // to copy-initializing a temporary of the underlying type with
2837 // the argument expression. Any difference in top-level
2838 // cv-qualification is subsumed by the initialization itself
2839 // and does not constitute a conversion.
2840 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2841 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002842 /*InOverloadResolution=*/false);
2843
2844 // Of course, that's still a reference binding.
2845 if (ICS.isStandard()) {
2846 ICS.Standard.ReferenceBinding = true;
2847 ICS.Standard.RRefBinding = isRValRef;
2848 } else if (ICS.isUserDefined()) {
2849 ICS.UserDefined.After.ReferenceBinding = true;
2850 ICS.UserDefined.After.RRefBinding = isRValRef;
2851 }
2852 return ICS;
2853}
2854
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002855/// TryCopyInitialization - Try to copy-initialize a value of type
2856/// ToType from the expression From. Return the implicit conversion
2857/// sequence required to pass this argument, which may be a bad
2858/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002859/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002860/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002861static ImplicitConversionSequence
2862TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002863 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002864 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002865 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002866 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002867 /*FIXME:*/From->getLocStart(),
2868 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002869 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002870
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002871 return S.TryImplicitConversion(From, ToType,
2872 SuppressUserConversions,
2873 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002874 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002875}
2876
Douglas Gregor436424c2008-11-18 23:14:02 +00002877/// TryObjectArgumentInitialization - Try to initialize the object
2878/// parameter of the given member function (@c Method) from the
2879/// expression @p From.
2880ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002881Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002882 CXXMethodDecl *Method,
2883 CXXRecordDecl *ActingContext) {
2884 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002885 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2886 // const volatile object.
2887 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2888 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2889 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002890
2891 // Set up the conversion sequence as a "bad" conversion, to allow us
2892 // to exit early.
2893 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002894
2895 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002896 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002897 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002898 FromType = PT->getPointeeType();
2899
2900 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002901
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002902 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002903 // where X is the class of which the function is a member
2904 // (C++ [over.match.funcs]p4). However, when finding an implicit
2905 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002906 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002907 // (C++ [over.match.funcs]p5). We perform a simplified version of
2908 // reference binding here, that allows class rvalues to bind to
2909 // non-constant references.
2910
2911 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2912 // with the implicit object parameter (C++ [over.match.funcs]p5).
2913 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002914 if (ImplicitParamType.getCVRQualifiers()
2915 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002916 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002917 ICS.setBad(BadConversionSequence::bad_qualifiers,
2918 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002919 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002920 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002921
2922 // Check that we have either the same type or a derived type. It
2923 // affects the conversion rank.
2924 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002925 ImplicitConversionKind SecondKind;
2926 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2927 SecondKind = ICK_Identity;
2928 } else if (IsDerivedFrom(FromType, ClassType))
2929 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002930 else {
John McCall65eb8792010-02-25 01:37:24 +00002931 ICS.setBad(BadConversionSequence::unrelated_class,
2932 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002933 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002934 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002935
2936 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002937 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002938 ICS.Standard.setAsIdentityConversion();
2939 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002940 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002941 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002942 ICS.Standard.ReferenceBinding = true;
2943 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002944 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002945 return ICS;
2946}
2947
2948/// PerformObjectArgumentInitialization - Perform initialization of
2949/// the implicit object parameter for the given Method with the given
2950/// expression.
2951bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002952Sema::PerformObjectArgumentInitialization(Expr *&From,
2953 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002954 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002955 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002956 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002957 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002958 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002959
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002960 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002961 FromRecordType = PT->getPointeeType();
2962 DestType = Method->getThisType(Context);
2963 } else {
2964 FromRecordType = From->getType();
2965 DestType = ImplicitParamRecordType;
2966 }
2967
John McCall6e9f8f62009-12-03 04:06:58 +00002968 // Note that we always use the true parent context when performing
2969 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002970 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002971 = TryObjectArgumentInitialization(From->getType(), Method,
2972 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002973 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002974 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002975 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002976 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002977
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002978 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002979 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002980
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002981 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002982 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2983 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002984 return false;
2985}
2986
Douglas Gregor5fb53972009-01-14 15:45:31 +00002987/// TryContextuallyConvertToBool - Attempt to contextually convert the
2988/// expression From to bool (C++0x [conv]p3).
2989ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002990 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00002991 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002992 // FIXME: Are these flags correct?
2993 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002994 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002995 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002996}
2997
2998/// PerformContextuallyConvertToBool - Perform a contextual conversion
2999/// of the expression From to bool (C++0x [conv]p3).
3000bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3001 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003002 if (!ICS.isBad())
3003 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003004
Fariborz Jahanian76197412009-11-18 18:26:29 +00003005 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003006 return Diag(From->getSourceRange().getBegin(),
3007 diag::err_typecheck_bool_condition)
3008 << From->getType() << From->getSourceRange();
3009 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003010}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003011
3012/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3013/// expression From to 'id'.
3014ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003015 QualType Ty = Context.getObjCIdType();
3016 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003017 // FIXME: Are these flags correct?
3018 /*SuppressUserConversions=*/false,
3019 /*AllowExplicit=*/true,
3020 /*InOverloadResolution=*/false);
3021}
3022
3023/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3024/// of the expression From to 'id'.
3025bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003026 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003027 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3028 if (!ICS.isBad())
3029 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3030 return true;
3031}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003032
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003033/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003034/// candidate functions, using the given function call arguments. If
3035/// @p SuppressUserConversions, then don't allow user-defined
3036/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003037///
3038/// \para PartialOverloading true if we are performing "partial" overloading
3039/// based on an incomplete set of function arguments. This feature is used by
3040/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003041void
3042Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003043 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003044 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003045 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003046 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003047 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003048 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003049 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003050 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003051 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003052 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003053
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003054 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003055 if (!isa<CXXConstructorDecl>(Method)) {
3056 // If we get here, it's because we're calling a member function
3057 // that is named without a member access expression (e.g.,
3058 // "this->f") that was either written explicitly or created
3059 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003060 // function, e.g., X::f(). We use an empty type for the implied
3061 // object argument (C++ [over.call.func]p3), and the acting context
3062 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003063 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003064 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003065 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003066 return;
3067 }
3068 // We treat a constructor like a non-member function, since its object
3069 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003070 }
3071
Douglas Gregorff7028a2009-11-13 23:59:09 +00003072 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003073 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003074
Douglas Gregor27381f32009-11-23 12:27:39 +00003075 // Overload resolution is always an unevaluated context.
3076 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3077
Douglas Gregorffe14e32009-11-14 01:20:54 +00003078 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3079 // C++ [class.copy]p3:
3080 // A member function template is never instantiated to perform the copy
3081 // of a class object to an object of its class type.
3082 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3083 if (NumArgs == 1 &&
3084 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003085 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3086 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003087 return;
3088 }
3089
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003090 // Add this candidate
3091 CandidateSet.push_back(OverloadCandidate());
3092 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003093 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003094 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003095 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003096 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003097 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003098
3099 unsigned NumArgsInProto = Proto->getNumArgs();
3100
3101 // (C++ 13.3.2p2): A candidate function having fewer than m
3102 // parameters is viable only if it has an ellipsis in its parameter
3103 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003104 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3105 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003106 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003107 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003108 return;
3109 }
3110
3111 // (C++ 13.3.2p2): A candidate function having more than m parameters
3112 // is viable only if the (m+1)st parameter has a default argument
3113 // (8.3.6). For the purposes of overload resolution, the
3114 // parameter list is truncated on the right, so that there are
3115 // exactly m parameters.
3116 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003117 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003118 // Not enough arguments.
3119 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003120 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003121 return;
3122 }
3123
3124 // Determine the implicit conversion sequences for each of the
3125 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003126 Candidate.Conversions.resize(NumArgs);
3127 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3128 if (ArgIdx < NumArgsInProto) {
3129 // (C++ 13.3.2p3): for F to be a viable function, there shall
3130 // exist for each argument an implicit conversion sequence
3131 // (13.3.3.1) that converts that argument to the corresponding
3132 // parameter of F.
3133 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003134 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003135 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003136 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003137 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003138 if (Candidate.Conversions[ArgIdx].isBad()) {
3139 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003140 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003141 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003142 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003143 } else {
3144 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3145 // argument for which there is no corresponding parameter is
3146 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003147 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003148 }
3149 }
3150}
3151
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003152/// \brief Add all of the function declarations in the given function set to
3153/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003154void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003155 Expr **Args, unsigned NumArgs,
3156 OverloadCandidateSet& CandidateSet,
3157 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003158 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003159 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3160 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003161 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003162 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003163 cast<CXXMethodDecl>(FD)->getParent(),
3164 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003165 CandidateSet, SuppressUserConversions);
3166 else
John McCalla0296f72010-03-19 07:35:19 +00003167 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003168 SuppressUserConversions);
3169 } else {
John McCalla0296f72010-03-19 07:35:19 +00003170 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003171 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3172 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003173 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003174 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003175 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003176 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003177 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003178 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003179 else
John McCalla0296f72010-03-19 07:35:19 +00003180 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003181 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003182 Args, NumArgs, CandidateSet,
3183 SuppressUserConversions);
3184 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003185 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003186}
3187
John McCallf0f1cf02009-11-17 07:50:12 +00003188/// AddMethodCandidate - Adds a named decl (which is some kind of
3189/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003190void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003191 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003192 Expr **Args, unsigned NumArgs,
3193 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003194 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003195 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003196 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003197
3198 if (isa<UsingShadowDecl>(Decl))
3199 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3200
3201 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3202 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3203 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003204 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3205 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003206 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003207 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003208 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003209 } else {
John McCalla0296f72010-03-19 07:35:19 +00003210 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003211 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003212 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003213 }
3214}
3215
Douglas Gregor436424c2008-11-18 23:14:02 +00003216/// AddMethodCandidate - Adds the given C++ member function to the set
3217/// of candidate functions, using the given function call arguments
3218/// and the object argument (@c Object). For example, in a call
3219/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3220/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3221/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003222/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003223void
John McCalla0296f72010-03-19 07:35:19 +00003224Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003225 CXXRecordDecl *ActingContext, QualType ObjectType,
3226 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003227 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003228 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003229 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003230 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003231 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003232 assert(!isa<CXXConstructorDecl>(Method) &&
3233 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003234
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003235 if (!CandidateSet.isNewCandidate(Method))
3236 return;
3237
Douglas Gregor27381f32009-11-23 12:27:39 +00003238 // Overload resolution is always an unevaluated context.
3239 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3240
Douglas Gregor436424c2008-11-18 23:14:02 +00003241 // Add this candidate
3242 CandidateSet.push_back(OverloadCandidate());
3243 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003244 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003245 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003246 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003247 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003248
3249 unsigned NumArgsInProto = Proto->getNumArgs();
3250
3251 // (C++ 13.3.2p2): A candidate function having fewer than m
3252 // parameters is viable only if it has an ellipsis in its parameter
3253 // list (8.3.5).
3254 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3255 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003256 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003257 return;
3258 }
3259
3260 // (C++ 13.3.2p2): A candidate function having more than m parameters
3261 // is viable only if the (m+1)st parameter has a default argument
3262 // (8.3.6). For the purposes of overload resolution, the
3263 // parameter list is truncated on the right, so that there are
3264 // exactly m parameters.
3265 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3266 if (NumArgs < MinRequiredArgs) {
3267 // Not enough arguments.
3268 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003269 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003270 return;
3271 }
3272
3273 Candidate.Viable = true;
3274 Candidate.Conversions.resize(NumArgs + 1);
3275
John McCall6e9f8f62009-12-03 04:06:58 +00003276 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003277 // The implicit object argument is ignored.
3278 Candidate.IgnoreObjectArgument = true;
3279 else {
3280 // Determine the implicit conversion sequence for the object
3281 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003282 Candidate.Conversions[0]
3283 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003284 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003285 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003286 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003287 return;
3288 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003289 }
3290
3291 // Determine the implicit conversion sequences for each of the
3292 // arguments.
3293 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3294 if (ArgIdx < NumArgsInProto) {
3295 // (C++ 13.3.2p3): for F to be a viable function, there shall
3296 // exist for each argument an implicit conversion sequence
3297 // (13.3.3.1) that converts that argument to the corresponding
3298 // parameter of F.
3299 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003300 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003301 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003302 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003303 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003304 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003305 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003306 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003307 break;
3308 }
3309 } else {
3310 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3311 // argument for which there is no corresponding parameter is
3312 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003313 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003314 }
3315 }
3316}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003317
Douglas Gregor97628d62009-08-21 00:16:32 +00003318/// \brief Add a C++ member function template as a candidate to the candidate
3319/// set, using template argument deduction to produce an appropriate member
3320/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003321void
Douglas Gregor97628d62009-08-21 00:16:32 +00003322Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003323 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003324 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003325 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003326 QualType ObjectType,
3327 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003328 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003329 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003330 if (!CandidateSet.isNewCandidate(MethodTmpl))
3331 return;
3332
Douglas Gregor97628d62009-08-21 00:16:32 +00003333 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003334 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003335 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003336 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003337 // candidate functions in the usual way.113) A given name can refer to one
3338 // or more function templates and also to a set of overloaded non-template
3339 // functions. In such a case, the candidate functions generated from each
3340 // function template are combined with the set of non-template candidate
3341 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003342 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003343 FunctionDecl *Specialization = 0;
3344 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003345 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003346 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003347 CandidateSet.push_back(OverloadCandidate());
3348 OverloadCandidate &Candidate = CandidateSet.back();
3349 Candidate.FoundDecl = FoundDecl;
3350 Candidate.Function = MethodTmpl->getTemplatedDecl();
3351 Candidate.Viable = false;
3352 Candidate.FailureKind = ovl_fail_bad_deduction;
3353 Candidate.IsSurrogate = false;
3354 Candidate.IgnoreObjectArgument = false;
3355 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3356 Info);
3357 return;
3358 }
Mike Stump11289f42009-09-09 15:08:12 +00003359
Douglas Gregor97628d62009-08-21 00:16:32 +00003360 // Add the function template specialization produced by template argument
3361 // deduction as a candidate.
3362 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003363 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003364 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003365 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003366 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003367 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003368}
3369
Douglas Gregor05155d82009-08-21 23:19:43 +00003370/// \brief Add a C++ function template specialization as a candidate
3371/// in the candidate set, using template argument deduction to produce
3372/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003373void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003374Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003375 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003376 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003377 Expr **Args, unsigned NumArgs,
3378 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003379 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003380 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3381 return;
3382
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003383 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003384 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003385 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003386 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003387 // candidate functions in the usual way.113) A given name can refer to one
3388 // or more function templates and also to a set of overloaded non-template
3389 // functions. In such a case, the candidate functions generated from each
3390 // function template are combined with the set of non-template candidate
3391 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003392 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003393 FunctionDecl *Specialization = 0;
3394 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003395 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003396 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003397 CandidateSet.push_back(OverloadCandidate());
3398 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003399 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003400 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3401 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003402 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003403 Candidate.IsSurrogate = false;
3404 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003405 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3406 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003407 return;
3408 }
Mike Stump11289f42009-09-09 15:08:12 +00003409
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003410 // Add the function template specialization produced by template argument
3411 // deduction as a candidate.
3412 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003413 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003414 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003415}
Mike Stump11289f42009-09-09 15:08:12 +00003416
Douglas Gregora1f013e2008-11-07 22:36:19 +00003417/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003418/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003419/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003420/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003421/// (which may or may not be the same type as the type that the
3422/// conversion function produces).
3423void
3424Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003425 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003426 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003427 Expr *From, QualType ToType,
3428 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003429 assert(!Conversion->getDescribedFunctionTemplate() &&
3430 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003431 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003432 if (!CandidateSet.isNewCandidate(Conversion))
3433 return;
3434
Douglas Gregor27381f32009-11-23 12:27:39 +00003435 // Overload resolution is always an unevaluated context.
3436 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3437
Douglas Gregora1f013e2008-11-07 22:36:19 +00003438 // Add this candidate
3439 CandidateSet.push_back(OverloadCandidate());
3440 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003441 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003442 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003443 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003444 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003445 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003446 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003447 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003448
Douglas Gregor436424c2008-11-18 23:14:02 +00003449 // Determine the implicit conversion sequence for the implicit
3450 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003451 Candidate.Viable = true;
3452 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003453 Candidate.Conversions[0]
3454 = TryObjectArgumentInitialization(From->getType(), Conversion,
3455 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003456 // Conversion functions to a different type in the base class is visible in
3457 // the derived class. So, a derived to base conversion should not participate
3458 // in overload resolution.
3459 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3460 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003461 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003462 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003463 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003464 return;
3465 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003466
3467 // We won't go through a user-define type conversion function to convert a
3468 // derived to base as such conversions are given Conversion Rank. They only
3469 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3470 QualType FromCanon
3471 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3472 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3473 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3474 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003475 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003476 return;
3477 }
3478
Douglas Gregora1f013e2008-11-07 22:36:19 +00003479 // To determine what the conversion from the result of calling the
3480 // conversion function to the type we're eventually trying to
3481 // convert to (ToType), we need to synthesize a call to the
3482 // conversion function and attempt copy initialization from it. This
3483 // makes sure that we get the right semantics with respect to
3484 // lvalues/rvalues and the type. Fortunately, we can allocate this
3485 // call on the stack and we don't need its arguments to be
3486 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003487 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003488 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003489 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003490 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003491 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003492
3493 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003494 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3495 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003496 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003497 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003498 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003499 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003500 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003501 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003502 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003503
John McCall0d1da222010-01-12 00:44:57 +00003504 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003505 case ImplicitConversionSequence::StandardConversion:
3506 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003507
3508 // C++ [over.ics.user]p3:
3509 // If the user-defined conversion is specified by a specialization of a
3510 // conversion function template, the second standard conversion sequence
3511 // shall have exact match rank.
3512 if (Conversion->getPrimaryTemplate() &&
3513 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3514 Candidate.Viable = false;
3515 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3516 }
3517
Douglas Gregora1f013e2008-11-07 22:36:19 +00003518 break;
3519
3520 case ImplicitConversionSequence::BadConversion:
3521 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003522 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003523 break;
3524
3525 default:
Mike Stump11289f42009-09-09 15:08:12 +00003526 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003527 "Can only end up with a standard conversion sequence or failure");
3528 }
3529}
3530
Douglas Gregor05155d82009-08-21 23:19:43 +00003531/// \brief Adds a conversion function template specialization
3532/// candidate to the overload set, using template argument deduction
3533/// to deduce the template arguments of the conversion function
3534/// template from the type that we are converting to (C++
3535/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003536void
Douglas Gregor05155d82009-08-21 23:19:43 +00003537Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003538 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003539 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003540 Expr *From, QualType ToType,
3541 OverloadCandidateSet &CandidateSet) {
3542 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3543 "Only conversion function templates permitted here");
3544
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003545 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3546 return;
3547
John McCallbc077cf2010-02-08 23:07:23 +00003548 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003549 CXXConversionDecl *Specialization = 0;
3550 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003551 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003552 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003553 CandidateSet.push_back(OverloadCandidate());
3554 OverloadCandidate &Candidate = CandidateSet.back();
3555 Candidate.FoundDecl = FoundDecl;
3556 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3557 Candidate.Viable = false;
3558 Candidate.FailureKind = ovl_fail_bad_deduction;
3559 Candidate.IsSurrogate = false;
3560 Candidate.IgnoreObjectArgument = false;
3561 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3562 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003563 return;
3564 }
Mike Stump11289f42009-09-09 15:08:12 +00003565
Douglas Gregor05155d82009-08-21 23:19:43 +00003566 // Add the conversion function template specialization produced by
3567 // template argument deduction as a candidate.
3568 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003569 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003570 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003571}
3572
Douglas Gregorab7897a2008-11-19 22:57:39 +00003573/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3574/// converts the given @c Object to a function pointer via the
3575/// conversion function @c Conversion, and then attempts to call it
3576/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3577/// the type of function that we'll eventually be calling.
3578void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003579 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003580 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003581 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003582 QualType ObjectType,
3583 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003584 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003585 if (!CandidateSet.isNewCandidate(Conversion))
3586 return;
3587
Douglas Gregor27381f32009-11-23 12:27:39 +00003588 // Overload resolution is always an unevaluated context.
3589 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3590
Douglas Gregorab7897a2008-11-19 22:57:39 +00003591 CandidateSet.push_back(OverloadCandidate());
3592 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003593 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003594 Candidate.Function = 0;
3595 Candidate.Surrogate = Conversion;
3596 Candidate.Viable = true;
3597 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003598 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003599 Candidate.Conversions.resize(NumArgs + 1);
3600
3601 // Determine the implicit conversion sequence for the implicit
3602 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003603 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003604 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003605 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003606 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003607 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003608 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003609 return;
3610 }
3611
3612 // The first conversion is actually a user-defined conversion whose
3613 // first conversion is ObjectInit's standard conversion (which is
3614 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003615 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003616 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003617 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003618 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003619 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003620 = Candidate.Conversions[0].UserDefined.Before;
3621 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3622
Mike Stump11289f42009-09-09 15:08:12 +00003623 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003624 unsigned NumArgsInProto = Proto->getNumArgs();
3625
3626 // (C++ 13.3.2p2): A candidate function having fewer than m
3627 // parameters is viable only if it has an ellipsis in its parameter
3628 // list (8.3.5).
3629 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3630 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003631 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003632 return;
3633 }
3634
3635 // Function types don't have any default arguments, so just check if
3636 // we have enough arguments.
3637 if (NumArgs < NumArgsInProto) {
3638 // Not enough arguments.
3639 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003640 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003641 return;
3642 }
3643
3644 // Determine the implicit conversion sequences for each of the
3645 // arguments.
3646 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3647 if (ArgIdx < NumArgsInProto) {
3648 // (C++ 13.3.2p3): for F to be a viable function, there shall
3649 // exist for each argument an implicit conversion sequence
3650 // (13.3.3.1) that converts that argument to the corresponding
3651 // parameter of F.
3652 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003653 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003654 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003655 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003656 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003657 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003658 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003659 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003660 break;
3661 }
3662 } else {
3663 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3664 // argument for which there is no corresponding parameter is
3665 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003666 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003667 }
3668 }
3669}
3670
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003671/// \brief Add overload candidates for overloaded operators that are
3672/// member functions.
3673///
3674/// Add the overloaded operator candidates that are member functions
3675/// for the operator Op that was used in an operator expression such
3676/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3677/// CandidateSet will store the added overload candidates. (C++
3678/// [over.match.oper]).
3679void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3680 SourceLocation OpLoc,
3681 Expr **Args, unsigned NumArgs,
3682 OverloadCandidateSet& CandidateSet,
3683 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003684 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3685
3686 // C++ [over.match.oper]p3:
3687 // For a unary operator @ with an operand of a type whose
3688 // cv-unqualified version is T1, and for a binary operator @ with
3689 // a left operand of a type whose cv-unqualified version is T1 and
3690 // a right operand of a type whose cv-unqualified version is T2,
3691 // three sets of candidate functions, designated member
3692 // candidates, non-member candidates and built-in candidates, are
3693 // constructed as follows:
3694 QualType T1 = Args[0]->getType();
3695 QualType T2;
3696 if (NumArgs > 1)
3697 T2 = Args[1]->getType();
3698
3699 // -- If T1 is a class type, the set of member candidates is the
3700 // result of the qualified lookup of T1::operator@
3701 // (13.3.1.1.1); otherwise, the set of member candidates is
3702 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003703 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003704 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003705 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003706 return;
Mike Stump11289f42009-09-09 15:08:12 +00003707
John McCall27b18f82009-11-17 02:14:36 +00003708 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3709 LookupQualifiedName(Operators, T1Rec->getDecl());
3710 Operators.suppressDiagnostics();
3711
Mike Stump11289f42009-09-09 15:08:12 +00003712 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003713 OperEnd = Operators.end();
3714 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003715 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003716 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003717 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003718 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003719 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003720}
3721
Douglas Gregora11693b2008-11-12 17:17:38 +00003722/// AddBuiltinCandidate - Add a candidate for a built-in
3723/// operator. ResultTy and ParamTys are the result and parameter types
3724/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003725/// arguments being passed to the candidate. IsAssignmentOperator
3726/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003727/// operator. NumContextualBoolArguments is the number of arguments
3728/// (at the beginning of the argument list) that will be contextually
3729/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003730void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003731 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003732 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003733 bool IsAssignmentOperator,
3734 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003735 // Overload resolution is always an unevaluated context.
3736 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3737
Douglas Gregora11693b2008-11-12 17:17:38 +00003738 // Add this candidate
3739 CandidateSet.push_back(OverloadCandidate());
3740 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003741 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003742 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003743 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003744 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003745 Candidate.BuiltinTypes.ResultTy = ResultTy;
3746 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3747 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3748
3749 // Determine the implicit conversion sequences for each of the
3750 // arguments.
3751 Candidate.Viable = true;
3752 Candidate.Conversions.resize(NumArgs);
3753 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003754 // C++ [over.match.oper]p4:
3755 // For the built-in assignment operators, conversions of the
3756 // left operand are restricted as follows:
3757 // -- no temporaries are introduced to hold the left operand, and
3758 // -- no user-defined conversions are applied to the left
3759 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003760 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003761 //
3762 // We block these conversions by turning off user-defined
3763 // conversions, since that is the only way that initialization of
3764 // a reference to a non-class type can occur from something that
3765 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003766 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003767 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003768 "Contextual conversion to bool requires bool type");
3769 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3770 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003771 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003772 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003773 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003774 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003775 }
John McCall0d1da222010-01-12 00:44:57 +00003776 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003777 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003778 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003779 break;
3780 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003781 }
3782}
3783
3784/// BuiltinCandidateTypeSet - A set of types that will be used for the
3785/// candidate operator functions for built-in operators (C++
3786/// [over.built]). The types are separated into pointer types and
3787/// enumeration types.
3788class BuiltinCandidateTypeSet {
3789 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003790 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003791
3792 /// PointerTypes - The set of pointer types that will be used in the
3793 /// built-in candidates.
3794 TypeSet PointerTypes;
3795
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003796 /// MemberPointerTypes - The set of member pointer types that will be
3797 /// used in the built-in candidates.
3798 TypeSet MemberPointerTypes;
3799
Douglas Gregora11693b2008-11-12 17:17:38 +00003800 /// EnumerationTypes - The set of enumeration types that will be
3801 /// used in the built-in candidates.
3802 TypeSet EnumerationTypes;
3803
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003804 /// \brief The set of vector types that will be used in the built-in
3805 /// candidates.
3806 TypeSet VectorTypes;
3807
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003808 /// Sema - The semantic analysis instance where we are building the
3809 /// candidate type set.
3810 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003811
Douglas Gregora11693b2008-11-12 17:17:38 +00003812 /// Context - The AST context in which we will build the type sets.
3813 ASTContext &Context;
3814
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003815 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3816 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003817 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003818
3819public:
3820 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003821 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003822
Mike Stump11289f42009-09-09 15:08:12 +00003823 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003824 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003825
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003826 void AddTypesConvertedFrom(QualType Ty,
3827 SourceLocation Loc,
3828 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003829 bool AllowExplicitConversions,
3830 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003831
3832 /// pointer_begin - First pointer type found;
3833 iterator pointer_begin() { return PointerTypes.begin(); }
3834
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003835 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003836 iterator pointer_end() { return PointerTypes.end(); }
3837
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003838 /// member_pointer_begin - First member pointer type found;
3839 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3840
3841 /// member_pointer_end - Past the last member pointer type found;
3842 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3843
Douglas Gregora11693b2008-11-12 17:17:38 +00003844 /// enumeration_begin - First enumeration type found;
3845 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3846
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003847 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003848 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003849
3850 iterator vector_begin() { return VectorTypes.begin(); }
3851 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00003852};
3853
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003854/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003855/// the set of pointer types along with any more-qualified variants of
3856/// that type. For example, if @p Ty is "int const *", this routine
3857/// will add "int const *", "int const volatile *", "int const
3858/// restrict *", and "int const volatile restrict *" to the set of
3859/// pointer types. Returns true if the add of @p Ty itself succeeded,
3860/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003861///
3862/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003863bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003864BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3865 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003866
Douglas Gregora11693b2008-11-12 17:17:38 +00003867 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003868 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003869 return false;
3870
John McCall8ccfcb52009-09-24 19:53:00 +00003871 const PointerType *PointerTy = Ty->getAs<PointerType>();
3872 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003873
John McCall8ccfcb52009-09-24 19:53:00 +00003874 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003875 // Don't add qualified variants of arrays. For one, they're not allowed
3876 // (the qualifier would sink to the element type), and for another, the
3877 // only overload situation where it matters is subscript or pointer +- int,
3878 // and those shouldn't have qualifier variants anyway.
3879 if (PointeeTy->isArrayType())
3880 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003881 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003882 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003883 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003884 bool hasVolatile = VisibleQuals.hasVolatile();
3885 bool hasRestrict = VisibleQuals.hasRestrict();
3886
John McCall8ccfcb52009-09-24 19:53:00 +00003887 // Iterate through all strict supersets of BaseCVR.
3888 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3889 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003890 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3891 // in the types.
3892 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3893 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003894 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3895 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003896 }
3897
3898 return true;
3899}
3900
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003901/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3902/// to the set of pointer types along with any more-qualified variants of
3903/// that type. For example, if @p Ty is "int const *", this routine
3904/// will add "int const *", "int const volatile *", "int const
3905/// restrict *", and "int const volatile restrict *" to the set of
3906/// pointer types. Returns true if the add of @p Ty itself succeeded,
3907/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003908///
3909/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003910bool
3911BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3912 QualType Ty) {
3913 // Insert this type.
3914 if (!MemberPointerTypes.insert(Ty))
3915 return false;
3916
John McCall8ccfcb52009-09-24 19:53:00 +00003917 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3918 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003919
John McCall8ccfcb52009-09-24 19:53:00 +00003920 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003921 // Don't add qualified variants of arrays. For one, they're not allowed
3922 // (the qualifier would sink to the element type), and for another, the
3923 // only overload situation where it matters is subscript or pointer +- int,
3924 // and those shouldn't have qualifier variants anyway.
3925 if (PointeeTy->isArrayType())
3926 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003927 const Type *ClassTy = PointerTy->getClass();
3928
3929 // Iterate through all strict supersets of the pointee type's CVR
3930 // qualifiers.
3931 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3932 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3933 if ((CVR | BaseCVR) != CVR) continue;
3934
3935 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3936 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003937 }
3938
3939 return true;
3940}
3941
Douglas Gregora11693b2008-11-12 17:17:38 +00003942/// AddTypesConvertedFrom - Add each of the types to which the type @p
3943/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003944/// primarily interested in pointer types and enumeration types. We also
3945/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003946/// AllowUserConversions is true if we should look at the conversion
3947/// functions of a class type, and AllowExplicitConversions if we
3948/// should also include the explicit conversion functions of a class
3949/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003950void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003951BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003952 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003953 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003954 bool AllowExplicitConversions,
3955 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003956 // Only deal with canonical types.
3957 Ty = Context.getCanonicalType(Ty);
3958
3959 // Look through reference types; they aren't part of the type of an
3960 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003961 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003962 Ty = RefTy->getPointeeType();
3963
3964 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003965 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003966
Sebastian Redl65ae2002009-11-05 16:36:20 +00003967 // If we're dealing with an array type, decay to the pointer.
3968 if (Ty->isArrayType())
3969 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3970
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003971 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003972 QualType PointeeTy = PointerTy->getPointeeType();
3973
3974 // Insert our type, and its more-qualified variants, into the set
3975 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003976 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003977 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003978 } else if (Ty->isMemberPointerType()) {
3979 // Member pointers are far easier, since the pointee can't be converted.
3980 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3981 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003982 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003983 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003984 } else if (Ty->isVectorType()) {
3985 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003986 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003987 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003988 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003989 // No conversion functions in incomplete types.
3990 return;
3991 }
Mike Stump11289f42009-09-09 15:08:12 +00003992
Douglas Gregora11693b2008-11-12 17:17:38 +00003993 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003994 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003995 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003996 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003997 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003998 NamedDecl *D = I.getDecl();
3999 if (isa<UsingShadowDecl>(D))
4000 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004001
Mike Stump11289f42009-09-09 15:08:12 +00004002 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004003 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004004 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004005 continue;
4006
John McCallda4458e2010-03-31 01:36:47 +00004007 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004008 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004009 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004010 VisibleQuals);
4011 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004012 }
4013 }
4014 }
4015}
4016
Douglas Gregor84605ae2009-08-24 13:43:27 +00004017/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4018/// the volatile- and non-volatile-qualified assignment operators for the
4019/// given type to the candidate set.
4020static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4021 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004022 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004023 unsigned NumArgs,
4024 OverloadCandidateSet &CandidateSet) {
4025 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004026
Douglas Gregor84605ae2009-08-24 13:43:27 +00004027 // T& operator=(T&, T)
4028 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4029 ParamTypes[1] = T;
4030 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4031 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004032
Douglas Gregor84605ae2009-08-24 13:43:27 +00004033 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4034 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004035 ParamTypes[0]
4036 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004037 ParamTypes[1] = T;
4038 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004039 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004040 }
4041}
Mike Stump11289f42009-09-09 15:08:12 +00004042
Sebastian Redl1054fae2009-10-25 17:03:50 +00004043/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4044/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004045static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4046 Qualifiers VRQuals;
4047 const RecordType *TyRec;
4048 if (const MemberPointerType *RHSMPType =
4049 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004050 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004051 else
4052 TyRec = ArgExpr->getType()->getAs<RecordType>();
4053 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004054 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004055 VRQuals.addVolatile();
4056 VRQuals.addRestrict();
4057 return VRQuals;
4058 }
4059
4060 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004061 if (!ClassDecl->hasDefinition())
4062 return VRQuals;
4063
John McCallad371252010-01-20 00:46:10 +00004064 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004065 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004066
John McCallad371252010-01-20 00:46:10 +00004067 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004068 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004069 NamedDecl *D = I.getDecl();
4070 if (isa<UsingShadowDecl>(D))
4071 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4072 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004073 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4074 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4075 CanTy = ResTypeRef->getPointeeType();
4076 // Need to go down the pointer/mempointer chain and add qualifiers
4077 // as see them.
4078 bool done = false;
4079 while (!done) {
4080 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4081 CanTy = ResTypePtr->getPointeeType();
4082 else if (const MemberPointerType *ResTypeMPtr =
4083 CanTy->getAs<MemberPointerType>())
4084 CanTy = ResTypeMPtr->getPointeeType();
4085 else
4086 done = true;
4087 if (CanTy.isVolatileQualified())
4088 VRQuals.addVolatile();
4089 if (CanTy.isRestrictQualified())
4090 VRQuals.addRestrict();
4091 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4092 return VRQuals;
4093 }
4094 }
4095 }
4096 return VRQuals;
4097}
4098
Douglas Gregord08452f2008-11-19 15:42:04 +00004099/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4100/// operator overloads to the candidate set (C++ [over.built]), based
4101/// on the operator @p Op and the arguments given. For example, if the
4102/// operator is a binary '+', this routine might add "int
4103/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004104void
Mike Stump11289f42009-09-09 15:08:12 +00004105Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004106 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004107 Expr **Args, unsigned NumArgs,
4108 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004109 // The set of "promoted arithmetic types", which are the arithmetic
4110 // types are that preserved by promotion (C++ [over.built]p2). Note
4111 // that the first few of these types are the promoted integral
4112 // types; these types need to be first.
4113 // FIXME: What about complex?
4114 const unsigned FirstIntegralType = 0;
4115 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004116 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004117 LastPromotedIntegralType = 13;
4118 const unsigned FirstPromotedArithmeticType = 7,
4119 LastPromotedArithmeticType = 16;
4120 const unsigned NumArithmeticTypes = 16;
4121 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004122 Context.BoolTy, Context.CharTy, Context.WCharTy,
4123// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004124 Context.SignedCharTy, Context.ShortTy,
4125 Context.UnsignedCharTy, Context.UnsignedShortTy,
4126 Context.IntTy, Context.LongTy, Context.LongLongTy,
4127 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4128 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4129 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004130 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4131 "Invalid first promoted integral type");
4132 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4133 == Context.UnsignedLongLongTy &&
4134 "Invalid last promoted integral type");
4135 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4136 "Invalid first promoted arithmetic type");
4137 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4138 == Context.LongDoubleTy &&
4139 "Invalid last promoted arithmetic type");
4140
Douglas Gregora11693b2008-11-12 17:17:38 +00004141 // Find all of the types that the arguments can convert to, but only
4142 // if the operator we're looking at has built-in operator candidates
4143 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004144 Qualifiers VisibleTypeConversionsQuals;
4145 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004146 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4147 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4148
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004149 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004150 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4151 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4152 OpLoc,
4153 true,
4154 (Op == OO_Exclaim ||
4155 Op == OO_AmpAmp ||
4156 Op == OO_PipePipe),
4157 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004158
4159 bool isComparison = false;
4160 switch (Op) {
4161 case OO_None:
4162 case NUM_OVERLOADED_OPERATORS:
4163 assert(false && "Expected an overloaded operator");
4164 break;
4165
Douglas Gregord08452f2008-11-19 15:42:04 +00004166 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004167 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004168 goto UnaryStar;
4169 else
4170 goto BinaryStar;
4171 break;
4172
4173 case OO_Plus: // '+' is either unary or binary
4174 if (NumArgs == 1)
4175 goto UnaryPlus;
4176 else
4177 goto BinaryPlus;
4178 break;
4179
4180 case OO_Minus: // '-' is either unary or binary
4181 if (NumArgs == 1)
4182 goto UnaryMinus;
4183 else
4184 goto BinaryMinus;
4185 break;
4186
4187 case OO_Amp: // '&' is either unary or binary
4188 if (NumArgs == 1)
4189 goto UnaryAmp;
4190 else
4191 goto BinaryAmp;
4192
4193 case OO_PlusPlus:
4194 case OO_MinusMinus:
4195 // C++ [over.built]p3:
4196 //
4197 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4198 // is either volatile or empty, there exist candidate operator
4199 // functions of the form
4200 //
4201 // VQ T& operator++(VQ T&);
4202 // T operator++(VQ T&, int);
4203 //
4204 // C++ [over.built]p4:
4205 //
4206 // For every pair (T, VQ), where T is an arithmetic type other
4207 // than bool, and VQ is either volatile or empty, there exist
4208 // candidate operator functions of the form
4209 //
4210 // VQ T& operator--(VQ T&);
4211 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004212 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004213 Arith < NumArithmeticTypes; ++Arith) {
4214 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004215 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004216 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004217
4218 // Non-volatile version.
4219 if (NumArgs == 1)
4220 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4221 else
4222 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004223 // heuristic to reduce number of builtin candidates in the set.
4224 // Add volatile version only if there are conversions to a volatile type.
4225 if (VisibleTypeConversionsQuals.hasVolatile()) {
4226 // Volatile version
4227 ParamTypes[0]
4228 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4229 if (NumArgs == 1)
4230 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4231 else
4232 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4233 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004234 }
4235
4236 // C++ [over.built]p5:
4237 //
4238 // For every pair (T, VQ), where T is a cv-qualified or
4239 // cv-unqualified object type, and VQ is either volatile or
4240 // empty, there exist candidate operator functions of the form
4241 //
4242 // T*VQ& operator++(T*VQ&);
4243 // T*VQ& operator--(T*VQ&);
4244 // T* operator++(T*VQ&, int);
4245 // T* operator--(T*VQ&, int);
4246 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4247 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4248 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004249 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004250 continue;
4251
Mike Stump11289f42009-09-09 15:08:12 +00004252 QualType ParamTypes[2] = {
4253 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004254 };
Mike Stump11289f42009-09-09 15:08:12 +00004255
Douglas Gregord08452f2008-11-19 15:42:04 +00004256 // Without volatile
4257 if (NumArgs == 1)
4258 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4259 else
4260 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4261
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004262 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4263 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004264 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004265 ParamTypes[0]
4266 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004267 if (NumArgs == 1)
4268 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4269 else
4270 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4271 }
4272 }
4273 break;
4274
4275 UnaryStar:
4276 // C++ [over.built]p6:
4277 // For every cv-qualified or cv-unqualified object type T, there
4278 // exist candidate operator functions of the form
4279 //
4280 // T& operator*(T*);
4281 //
4282 // C++ [over.built]p7:
4283 // For every function type T, there exist candidate operator
4284 // functions of the form
4285 // T& operator*(T*);
4286 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4287 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4288 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004289 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004290 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004291 &ParamTy, Args, 1, CandidateSet);
4292 }
4293 break;
4294
4295 UnaryPlus:
4296 // C++ [over.built]p8:
4297 // For every type T, there exist candidate operator functions of
4298 // the form
4299 //
4300 // T* operator+(T*);
4301 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4302 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4303 QualType ParamTy = *Ptr;
4304 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4305 }
Mike Stump11289f42009-09-09 15:08:12 +00004306
Douglas Gregord08452f2008-11-19 15:42:04 +00004307 // Fall through
4308
4309 UnaryMinus:
4310 // C++ [over.built]p9:
4311 // For every promoted arithmetic type T, there exist candidate
4312 // operator functions of the form
4313 //
4314 // T operator+(T);
4315 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004316 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004317 Arith < LastPromotedArithmeticType; ++Arith) {
4318 QualType ArithTy = ArithmeticTypes[Arith];
4319 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4320 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004321
4322 // Extension: We also add these operators for vector types.
4323 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4324 VecEnd = CandidateTypes.vector_end();
4325 Vec != VecEnd; ++Vec) {
4326 QualType VecTy = *Vec;
4327 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4328 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004329 break;
4330
4331 case OO_Tilde:
4332 // C++ [over.built]p10:
4333 // For every promoted integral type T, there exist candidate
4334 // operator functions of the form
4335 //
4336 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004337 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004338 Int < LastPromotedIntegralType; ++Int) {
4339 QualType IntTy = ArithmeticTypes[Int];
4340 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4341 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004342
4343 // Extension: We also add this operator for vector types.
4344 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4345 VecEnd = CandidateTypes.vector_end();
4346 Vec != VecEnd; ++Vec) {
4347 QualType VecTy = *Vec;
4348 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4349 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004350 break;
4351
Douglas Gregora11693b2008-11-12 17:17:38 +00004352 case OO_New:
4353 case OO_Delete:
4354 case OO_Array_New:
4355 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004356 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004357 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004358 break;
4359
4360 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004361 UnaryAmp:
4362 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004363 // C++ [over.match.oper]p3:
4364 // -- For the operator ',', the unary operator '&', or the
4365 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004366 break;
4367
Douglas Gregor84605ae2009-08-24 13:43:27 +00004368 case OO_EqualEqual:
4369 case OO_ExclaimEqual:
4370 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004371 // For every pointer to member type T, there exist candidate operator
4372 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004373 //
4374 // bool operator==(T,T);
4375 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004376 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004377 MemPtr = CandidateTypes.member_pointer_begin(),
4378 MemPtrEnd = CandidateTypes.member_pointer_end();
4379 MemPtr != MemPtrEnd;
4380 ++MemPtr) {
4381 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4382 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4383 }
Mike Stump11289f42009-09-09 15:08:12 +00004384
Douglas Gregor84605ae2009-08-24 13:43:27 +00004385 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004386
Douglas Gregora11693b2008-11-12 17:17:38 +00004387 case OO_Less:
4388 case OO_Greater:
4389 case OO_LessEqual:
4390 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004391 // C++ [over.built]p15:
4392 //
4393 // For every pointer or enumeration type T, there exist
4394 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004395 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004396 // bool operator<(T, T);
4397 // bool operator>(T, T);
4398 // bool operator<=(T, T);
4399 // bool operator>=(T, T);
4400 // bool operator==(T, T);
4401 // bool operator!=(T, T);
4402 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4403 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4404 QualType ParamTypes[2] = { *Ptr, *Ptr };
4405 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4406 }
Mike Stump11289f42009-09-09 15:08:12 +00004407 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004408 = CandidateTypes.enumeration_begin();
4409 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4410 QualType ParamTypes[2] = { *Enum, *Enum };
4411 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4412 }
4413
4414 // Fall through.
4415 isComparison = true;
4416
Douglas Gregord08452f2008-11-19 15:42:04 +00004417 BinaryPlus:
4418 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004419 if (!isComparison) {
4420 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4421
4422 // C++ [over.built]p13:
4423 //
4424 // For every cv-qualified or cv-unqualified object type T
4425 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004426 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004427 // T* operator+(T*, ptrdiff_t);
4428 // T& operator[](T*, ptrdiff_t); [BELOW]
4429 // T* operator-(T*, ptrdiff_t);
4430 // T* operator+(ptrdiff_t, T*);
4431 // T& operator[](ptrdiff_t, T*); [BELOW]
4432 //
4433 // C++ [over.built]p14:
4434 //
4435 // For every T, where T is a pointer to object type, there
4436 // exist candidate operator functions of the form
4437 //
4438 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004439 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004440 = CandidateTypes.pointer_begin();
4441 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4442 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4443
4444 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4445 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4446
4447 if (Op == OO_Plus) {
4448 // T* operator+(ptrdiff_t, T*);
4449 ParamTypes[0] = ParamTypes[1];
4450 ParamTypes[1] = *Ptr;
4451 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4452 } else {
4453 // ptrdiff_t operator-(T, T);
4454 ParamTypes[1] = *Ptr;
4455 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4456 Args, 2, CandidateSet);
4457 }
4458 }
4459 }
4460 // Fall through
4461
Douglas Gregora11693b2008-11-12 17:17:38 +00004462 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004463 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004464 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004465 // C++ [over.built]p12:
4466 //
4467 // For every pair of promoted arithmetic types L and R, there
4468 // exist candidate operator functions of the form
4469 //
4470 // LR operator*(L, R);
4471 // LR operator/(L, R);
4472 // LR operator+(L, R);
4473 // LR operator-(L, R);
4474 // bool operator<(L, R);
4475 // bool operator>(L, R);
4476 // bool operator<=(L, R);
4477 // bool operator>=(L, R);
4478 // bool operator==(L, R);
4479 // bool operator!=(L, R);
4480 //
4481 // where LR is the result of the usual arithmetic conversions
4482 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004483 //
4484 // C++ [over.built]p24:
4485 //
4486 // For every pair of promoted arithmetic types L and R, there exist
4487 // candidate operator functions of the form
4488 //
4489 // LR operator?(bool, L, R);
4490 //
4491 // where LR is the result of the usual arithmetic conversions
4492 // between types L and R.
4493 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004494 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004495 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004496 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004497 Right < LastPromotedArithmeticType; ++Right) {
4498 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004499 QualType Result
4500 = isComparison
4501 ? Context.BoolTy
4502 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004503 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4504 }
4505 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004506
4507 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4508 // conditional operator for vector types.
4509 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4510 Vec1End = CandidateTypes.vector_end();
4511 Vec1 != Vec1End; ++Vec1)
4512 for (BuiltinCandidateTypeSet::iterator
4513 Vec2 = CandidateTypes.vector_begin(),
4514 Vec2End = CandidateTypes.vector_end();
4515 Vec2 != Vec2End; ++Vec2) {
4516 QualType LandR[2] = { *Vec1, *Vec2 };
4517 QualType Result;
4518 if (isComparison)
4519 Result = Context.BoolTy;
4520 else {
4521 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4522 Result = *Vec1;
4523 else
4524 Result = *Vec2;
4525 }
4526
4527 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4528 }
4529
Douglas Gregora11693b2008-11-12 17:17:38 +00004530 break;
4531
4532 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004533 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004534 case OO_Caret:
4535 case OO_Pipe:
4536 case OO_LessLess:
4537 case OO_GreaterGreater:
4538 // C++ [over.built]p17:
4539 //
4540 // For every pair of promoted integral types L and R, there
4541 // exist candidate operator functions of the form
4542 //
4543 // LR operator%(L, R);
4544 // LR operator&(L, R);
4545 // LR operator^(L, R);
4546 // LR operator|(L, R);
4547 // L operator<<(L, R);
4548 // L operator>>(L, R);
4549 //
4550 // where LR is the result of the usual arithmetic conversions
4551 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004552 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004553 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004554 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004555 Right < LastPromotedIntegralType; ++Right) {
4556 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4557 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4558 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004559 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004560 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4561 }
4562 }
4563 break;
4564
4565 case OO_Equal:
4566 // C++ [over.built]p20:
4567 //
4568 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004569 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004570 // empty, there exist candidate operator functions of the form
4571 //
4572 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004573 for (BuiltinCandidateTypeSet::iterator
4574 Enum = CandidateTypes.enumeration_begin(),
4575 EnumEnd = CandidateTypes.enumeration_end();
4576 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004577 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004578 CandidateSet);
4579 for (BuiltinCandidateTypeSet::iterator
4580 MemPtr = CandidateTypes.member_pointer_begin(),
4581 MemPtrEnd = CandidateTypes.member_pointer_end();
4582 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004583 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004584 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004585
4586 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004587
4588 case OO_PlusEqual:
4589 case OO_MinusEqual:
4590 // C++ [over.built]p19:
4591 //
4592 // For every pair (T, VQ), where T is any type and VQ is either
4593 // volatile or empty, there exist candidate operator functions
4594 // of the form
4595 //
4596 // T*VQ& operator=(T*VQ&, T*);
4597 //
4598 // C++ [over.built]p21:
4599 //
4600 // For every pair (T, VQ), where T is a cv-qualified or
4601 // cv-unqualified object type and VQ is either volatile or
4602 // empty, there exist candidate operator functions of the form
4603 //
4604 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4605 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4606 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4607 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4608 QualType ParamTypes[2];
4609 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4610
4611 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004612 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004613 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4614 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004615
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004616 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4617 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004618 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004619 ParamTypes[0]
4620 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004621 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4622 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004623 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004624 }
4625 // Fall through.
4626
4627 case OO_StarEqual:
4628 case OO_SlashEqual:
4629 // C++ [over.built]p18:
4630 //
4631 // For every triple (L, VQ, R), where L is an arithmetic type,
4632 // VQ is either volatile or empty, and R is a promoted
4633 // arithmetic type, there exist candidate operator functions of
4634 // the form
4635 //
4636 // VQ L& operator=(VQ L&, R);
4637 // VQ L& operator*=(VQ L&, R);
4638 // VQ L& operator/=(VQ L&, R);
4639 // VQ L& operator+=(VQ L&, R);
4640 // VQ L& operator-=(VQ L&, R);
4641 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004642 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004643 Right < LastPromotedArithmeticType; ++Right) {
4644 QualType ParamTypes[2];
4645 ParamTypes[1] = ArithmeticTypes[Right];
4646
4647 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004648 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004649 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4650 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004651
4652 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004653 if (VisibleTypeConversionsQuals.hasVolatile()) {
4654 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4655 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4656 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4657 /*IsAssigmentOperator=*/Op == OO_Equal);
4658 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004659 }
4660 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004661
4662 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4663 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4664 Vec1End = CandidateTypes.vector_end();
4665 Vec1 != Vec1End; ++Vec1)
4666 for (BuiltinCandidateTypeSet::iterator
4667 Vec2 = CandidateTypes.vector_begin(),
4668 Vec2End = CandidateTypes.vector_end();
4669 Vec2 != Vec2End; ++Vec2) {
4670 QualType ParamTypes[2];
4671 ParamTypes[1] = *Vec2;
4672 // Add this built-in operator as a candidate (VQ is empty).
4673 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4674 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4675 /*IsAssigmentOperator=*/Op == OO_Equal);
4676
4677 // Add this built-in operator as a candidate (VQ is 'volatile').
4678 if (VisibleTypeConversionsQuals.hasVolatile()) {
4679 ParamTypes[0] = Context.getVolatileType(*Vec1);
4680 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4681 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4682 /*IsAssigmentOperator=*/Op == OO_Equal);
4683 }
4684 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004685 break;
4686
4687 case OO_PercentEqual:
4688 case OO_LessLessEqual:
4689 case OO_GreaterGreaterEqual:
4690 case OO_AmpEqual:
4691 case OO_CaretEqual:
4692 case OO_PipeEqual:
4693 // C++ [over.built]p22:
4694 //
4695 // For every triple (L, VQ, R), where L is an integral type, VQ
4696 // is either volatile or empty, and R is a promoted integral
4697 // type, there exist candidate operator functions of the form
4698 //
4699 // VQ L& operator%=(VQ L&, R);
4700 // VQ L& operator<<=(VQ L&, R);
4701 // VQ L& operator>>=(VQ L&, R);
4702 // VQ L& operator&=(VQ L&, R);
4703 // VQ L& operator^=(VQ L&, R);
4704 // VQ L& operator|=(VQ L&, R);
4705 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004706 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004707 Right < LastPromotedIntegralType; ++Right) {
4708 QualType ParamTypes[2];
4709 ParamTypes[1] = ArithmeticTypes[Right];
4710
4711 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004712 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004713 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004714 if (VisibleTypeConversionsQuals.hasVolatile()) {
4715 // Add this built-in operator as a candidate (VQ is 'volatile').
4716 ParamTypes[0] = ArithmeticTypes[Left];
4717 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4718 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4719 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4720 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004721 }
4722 }
4723 break;
4724
Douglas Gregord08452f2008-11-19 15:42:04 +00004725 case OO_Exclaim: {
4726 // C++ [over.operator]p23:
4727 //
4728 // There also exist candidate operator functions of the form
4729 //
Mike Stump11289f42009-09-09 15:08:12 +00004730 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004731 // bool operator&&(bool, bool); [BELOW]
4732 // bool operator||(bool, bool); [BELOW]
4733 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004734 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4735 /*IsAssignmentOperator=*/false,
4736 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004737 break;
4738 }
4739
Douglas Gregora11693b2008-11-12 17:17:38 +00004740 case OO_AmpAmp:
4741 case OO_PipePipe: {
4742 // C++ [over.operator]p23:
4743 //
4744 // There also exist candidate operator functions of the form
4745 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004746 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004747 // bool operator&&(bool, bool);
4748 // bool operator||(bool, bool);
4749 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004750 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4751 /*IsAssignmentOperator=*/false,
4752 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004753 break;
4754 }
4755
4756 case OO_Subscript:
4757 // C++ [over.built]p13:
4758 //
4759 // For every cv-qualified or cv-unqualified object type T there
4760 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004761 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004762 // T* operator+(T*, ptrdiff_t); [ABOVE]
4763 // T& operator[](T*, ptrdiff_t);
4764 // T* operator-(T*, ptrdiff_t); [ABOVE]
4765 // T* operator+(ptrdiff_t, T*); [ABOVE]
4766 // T& operator[](ptrdiff_t, T*);
4767 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4768 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4769 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004770 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004771 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004772
4773 // T& operator[](T*, ptrdiff_t)
4774 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4775
4776 // T& operator[](ptrdiff_t, T*);
4777 ParamTypes[0] = ParamTypes[1];
4778 ParamTypes[1] = *Ptr;
4779 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004780 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004781 break;
4782
4783 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004784 // C++ [over.built]p11:
4785 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4786 // C1 is the same type as C2 or is a derived class of C2, T is an object
4787 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4788 // there exist candidate operator functions of the form
4789 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4790 // where CV12 is the union of CV1 and CV2.
4791 {
4792 for (BuiltinCandidateTypeSet::iterator Ptr =
4793 CandidateTypes.pointer_begin();
4794 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4795 QualType C1Ty = (*Ptr);
4796 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004797 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004798 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004799 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004800 if (!isa<RecordType>(C1))
4801 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004802 // heuristic to reduce number of builtin candidates in the set.
4803 // Add volatile/restrict version only if there are conversions to a
4804 // volatile/restrict type.
4805 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4806 continue;
4807 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4808 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004809 }
4810 for (BuiltinCandidateTypeSet::iterator
4811 MemPtr = CandidateTypes.member_pointer_begin(),
4812 MemPtrEnd = CandidateTypes.member_pointer_end();
4813 MemPtr != MemPtrEnd; ++MemPtr) {
4814 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4815 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004816 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004817 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4818 break;
4819 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4820 // build CV12 T&
4821 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004822 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4823 T.isVolatileQualified())
4824 continue;
4825 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4826 T.isRestrictQualified())
4827 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004828 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004829 QualType ResultTy = Context.getLValueReferenceType(T);
4830 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4831 }
4832 }
4833 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004834 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004835
4836 case OO_Conditional:
4837 // Note that we don't consider the first argument, since it has been
4838 // contextually converted to bool long ago. The candidates below are
4839 // therefore added as binary.
4840 //
4841 // C++ [over.built]p24:
4842 // For every type T, where T is a pointer or pointer-to-member type,
4843 // there exist candidate operator functions of the form
4844 //
4845 // T operator?(bool, T, T);
4846 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004847 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4848 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4849 QualType ParamTypes[2] = { *Ptr, *Ptr };
4850 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4851 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004852 for (BuiltinCandidateTypeSet::iterator Ptr =
4853 CandidateTypes.member_pointer_begin(),
4854 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4855 QualType ParamTypes[2] = { *Ptr, *Ptr };
4856 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4857 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004858 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004859 }
4860}
4861
Douglas Gregore254f902009-02-04 00:32:51 +00004862/// \brief Add function candidates found via argument-dependent lookup
4863/// to the set of overloading candidates.
4864///
4865/// This routine performs argument-dependent name lookup based on the
4866/// given function name (which may also be an operator name) and adds
4867/// all of the overload candidates found by ADL to the overload
4868/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004869void
Douglas Gregore254f902009-02-04 00:32:51 +00004870Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004871 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004872 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004873 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004874 OverloadCandidateSet& CandidateSet,
4875 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004876 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004877
John McCall91f61fc2010-01-26 06:04:06 +00004878 // FIXME: This approach for uniquing ADL results (and removing
4879 // redundant candidates from the set) relies on pointer-equality,
4880 // which means we need to key off the canonical decl. However,
4881 // always going back to the canonical decl might not get us the
4882 // right set of default arguments. What default arguments are
4883 // we supposed to consider on ADL candidates, anyway?
4884
Douglas Gregorcabea402009-09-22 15:41:20 +00004885 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004886 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004887
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004888 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004889 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4890 CandEnd = CandidateSet.end();
4891 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004892 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004893 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004894 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004895 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004896 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004897
4898 // For each of the ADL candidates we found, add it to the overload
4899 // set.
John McCall8fe68082010-01-26 07:16:45 +00004900 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004901 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004902 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004903 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004904 continue;
4905
John McCalla0296f72010-03-19 07:35:19 +00004906 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004907 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004908 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004909 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004910 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004911 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004912 }
Douglas Gregore254f902009-02-04 00:32:51 +00004913}
4914
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004915/// isBetterOverloadCandidate - Determines whether the first overload
4916/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004917bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004918Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004919 const OverloadCandidate& Cand2,
4920 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004921 // Define viable functions to be better candidates than non-viable
4922 // functions.
4923 if (!Cand2.Viable)
4924 return Cand1.Viable;
4925 else if (!Cand1.Viable)
4926 return false;
4927
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004928 // C++ [over.match.best]p1:
4929 //
4930 // -- if F is a static member function, ICS1(F) is defined such
4931 // that ICS1(F) is neither better nor worse than ICS1(G) for
4932 // any function G, and, symmetrically, ICS1(G) is neither
4933 // better nor worse than ICS1(F).
4934 unsigned StartArg = 0;
4935 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4936 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004937
Douglas Gregord3cb3562009-07-07 23:38:56 +00004938 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004939 // A viable function F1 is defined to be a better function than another
4940 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004941 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004942 unsigned NumArgs = Cand1.Conversions.size();
4943 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4944 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004945 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004946 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4947 Cand2.Conversions[ArgIdx])) {
4948 case ImplicitConversionSequence::Better:
4949 // Cand1 has a better conversion sequence.
4950 HasBetterConversion = true;
4951 break;
4952
4953 case ImplicitConversionSequence::Worse:
4954 // Cand1 can't be better than Cand2.
4955 return false;
4956
4957 case ImplicitConversionSequence::Indistinguishable:
4958 // Do nothing.
4959 break;
4960 }
4961 }
4962
Mike Stump11289f42009-09-09 15:08:12 +00004963 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004964 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004965 if (HasBetterConversion)
4966 return true;
4967
Mike Stump11289f42009-09-09 15:08:12 +00004968 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004969 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00004970 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00004971 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4972 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004973
4974 // -- F1 and F2 are function template specializations, and the function
4975 // template for F1 is more specialized than the template for F2
4976 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004977 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004978 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4979 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004980 if (FunctionTemplateDecl *BetterTemplate
4981 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4982 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004983 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004984 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4985 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004986 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004987
Douglas Gregora1f013e2008-11-07 22:36:19 +00004988 // -- the context is an initialization by user-defined conversion
4989 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4990 // from the return type of F1 to the destination type (i.e.,
4991 // the type of the entity being initialized) is a better
4992 // conversion sequence than the standard conversion sequence
4993 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004994 if (Cand1.Function && Cand2.Function &&
4995 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004996 isa<CXXConversionDecl>(Cand2.Function)) {
4997 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4998 Cand2.FinalConversion)) {
4999 case ImplicitConversionSequence::Better:
5000 // Cand1 has a better conversion sequence.
5001 return true;
5002
5003 case ImplicitConversionSequence::Worse:
5004 // Cand1 can't be better than Cand2.
5005 return false;
5006
5007 case ImplicitConversionSequence::Indistinguishable:
5008 // Do nothing
5009 break;
5010 }
5011 }
5012
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005013 return false;
5014}
5015
Mike Stump11289f42009-09-09 15:08:12 +00005016/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005017/// within an overload candidate set.
5018///
5019/// \param CandidateSet the set of candidate functions.
5020///
5021/// \param Loc the location of the function name (or operator symbol) for
5022/// which overload resolution occurs.
5023///
Mike Stump11289f42009-09-09 15:08:12 +00005024/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005025/// function, Best points to the candidate function found.
5026///
5027/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005028OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5029 SourceLocation Loc,
5030 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005031 // Find the best viable function.
5032 Best = CandidateSet.end();
5033 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5034 Cand != CandidateSet.end(); ++Cand) {
5035 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005036 if (Best == CandidateSet.end() ||
5037 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005038 Best = Cand;
5039 }
5040 }
5041
5042 // If we didn't find any viable functions, abort.
5043 if (Best == CandidateSet.end())
5044 return OR_No_Viable_Function;
5045
5046 // Make sure that this function is better than every other viable
5047 // function. If not, we have an ambiguity.
5048 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5049 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005050 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005051 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005052 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005053 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005054 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005055 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005056 }
Mike Stump11289f42009-09-09 15:08:12 +00005057
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005058 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005059 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005060 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005061 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005062 return OR_Deleted;
5063
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005064 // C++ [basic.def.odr]p2:
5065 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005066 // when referred to from a potentially-evaluated expression. [Note: this
5067 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005068 // (clause 13), user-defined conversions (12.3.2), allocation function for
5069 // placement new (5.3.4), as well as non-default initialization (8.5).
5070 if (Best->Function)
5071 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005072 return OR_Success;
5073}
5074
John McCall53262c92010-01-12 02:15:36 +00005075namespace {
5076
5077enum OverloadCandidateKind {
5078 oc_function,
5079 oc_method,
5080 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005081 oc_function_template,
5082 oc_method_template,
5083 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005084 oc_implicit_default_constructor,
5085 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005086 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005087};
5088
John McCalle1ac8d12010-01-13 00:25:19 +00005089OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5090 FunctionDecl *Fn,
5091 std::string &Description) {
5092 bool isTemplate = false;
5093
5094 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5095 isTemplate = true;
5096 Description = S.getTemplateArgumentBindingsText(
5097 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5098 }
John McCallfd0b2f82010-01-06 09:43:14 +00005099
5100 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005101 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005102 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005103
John McCall53262c92010-01-12 02:15:36 +00005104 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5105 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005106 }
5107
5108 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5109 // This actually gets spelled 'candidate function' for now, but
5110 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005111 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005112 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005113
5114 assert(Meth->isCopyAssignment()
5115 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005116 return oc_implicit_copy_assignment;
5117 }
5118
John McCalle1ac8d12010-01-13 00:25:19 +00005119 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005120}
5121
5122} // end anonymous namespace
5123
5124// Notes the location of an overload candidate.
5125void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005126 std::string FnDesc;
5127 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5128 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5129 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005130}
5131
John McCall0d1da222010-01-12 00:44:57 +00005132/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5133/// "lead" diagnostic; it will be given two arguments, the source and
5134/// target types of the conversion.
5135void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5136 SourceLocation CaretLoc,
5137 const PartialDiagnostic &PDiag) {
5138 Diag(CaretLoc, PDiag)
5139 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5140 for (AmbiguousConversionSequence::const_iterator
5141 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5142 NoteOverloadCandidate(*I);
5143 }
John McCall12f97bc2010-01-08 04:41:39 +00005144}
5145
John McCall0d1da222010-01-12 00:44:57 +00005146namespace {
5147
John McCall6a61b522010-01-13 09:16:55 +00005148void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5149 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5150 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005151 assert(Cand->Function && "for now, candidate must be a function");
5152 FunctionDecl *Fn = Cand->Function;
5153
5154 // There's a conversion slot for the object argument if this is a
5155 // non-constructor method. Note that 'I' corresponds the
5156 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005157 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005158 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005159 if (I == 0)
5160 isObjectArgument = true;
5161 else
5162 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005163 }
5164
John McCalle1ac8d12010-01-13 00:25:19 +00005165 std::string FnDesc;
5166 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5167
John McCall6a61b522010-01-13 09:16:55 +00005168 Expr *FromExpr = Conv.Bad.FromExpr;
5169 QualType FromTy = Conv.Bad.getFromType();
5170 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005171
John McCallfb7ad0f2010-02-02 02:42:52 +00005172 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005173 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005174 Expr *E = FromExpr->IgnoreParens();
5175 if (isa<UnaryOperator>(E))
5176 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005177 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005178
5179 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5180 << (unsigned) FnKind << FnDesc
5181 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5182 << ToTy << Name << I+1;
5183 return;
5184 }
5185
John McCall6d174642010-01-23 08:10:49 +00005186 // Do some hand-waving analysis to see if the non-viability is due
5187 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005188 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5189 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5190 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5191 CToTy = RT->getPointeeType();
5192 else {
5193 // TODO: detect and diagnose the full richness of const mismatches.
5194 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5195 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5196 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5197 }
5198
5199 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5200 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5201 // It is dumb that we have to do this here.
5202 while (isa<ArrayType>(CFromTy))
5203 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5204 while (isa<ArrayType>(CToTy))
5205 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5206
5207 Qualifiers FromQs = CFromTy.getQualifiers();
5208 Qualifiers ToQs = CToTy.getQualifiers();
5209
5210 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5211 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5212 << (unsigned) FnKind << FnDesc
5213 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5214 << FromTy
5215 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5216 << (unsigned) isObjectArgument << I+1;
5217 return;
5218 }
5219
5220 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5221 assert(CVR && "unexpected qualifiers mismatch");
5222
5223 if (isObjectArgument) {
5224 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5225 << (unsigned) FnKind << FnDesc
5226 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5227 << FromTy << (CVR - 1);
5228 } else {
5229 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5230 << (unsigned) FnKind << FnDesc
5231 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5232 << FromTy << (CVR - 1) << I+1;
5233 }
5234 return;
5235 }
5236
John McCall6d174642010-01-23 08:10:49 +00005237 // Diagnose references or pointers to incomplete types differently,
5238 // since it's far from impossible that the incompleteness triggered
5239 // the failure.
5240 QualType TempFromTy = FromTy.getNonReferenceType();
5241 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5242 TempFromTy = PTy->getPointeeType();
5243 if (TempFromTy->isIncompleteType()) {
5244 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5245 << (unsigned) FnKind << FnDesc
5246 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5247 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5248 return;
5249 }
5250
John McCall47000992010-01-14 03:28:57 +00005251 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005252 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5253 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005254 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005255 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005256}
5257
5258void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5259 unsigned NumFormalArgs) {
5260 // TODO: treat calls to a missing default constructor as a special case
5261
5262 FunctionDecl *Fn = Cand->Function;
5263 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5264
5265 unsigned MinParams = Fn->getMinRequiredArguments();
5266
5267 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005268 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005269 unsigned mode, modeCount;
5270 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005271 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5272 (Cand->FailureKind == ovl_fail_bad_deduction &&
5273 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005274 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5275 mode = 0; // "at least"
5276 else
5277 mode = 2; // "exactly"
5278 modeCount = MinParams;
5279 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005280 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5281 (Cand->FailureKind == ovl_fail_bad_deduction &&
5282 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005283 if (MinParams != FnTy->getNumArgs())
5284 mode = 1; // "at most"
5285 else
5286 mode = 2; // "exactly"
5287 modeCount = FnTy->getNumArgs();
5288 }
5289
5290 std::string Description;
5291 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5292
5293 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005294 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5295 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005296}
5297
John McCall8b9ed552010-02-01 18:53:26 +00005298/// Diagnose a failed template-argument deduction.
5299void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5300 Expr **Args, unsigned NumArgs) {
5301 FunctionDecl *Fn = Cand->Function; // pattern
5302
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005303 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005304 NamedDecl *ParamD;
5305 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5306 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5307 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005308 switch (Cand->DeductionFailure.Result) {
5309 case Sema::TDK_Success:
5310 llvm_unreachable("TDK_success while diagnosing bad deduction");
5311
5312 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005313 assert(ParamD && "no parameter found for incomplete deduction result");
5314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5315 << ParamD->getDeclName();
5316 return;
5317 }
5318
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005319 case Sema::TDK_Inconsistent:
5320 case Sema::TDK_InconsistentQuals: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005321 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005322 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005323 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005324 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005325 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005326 which = 1;
5327 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005328 which = 2;
5329 }
5330
5331 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5332 << which << ParamD->getDeclName()
5333 << *Cand->DeductionFailure.getFirstArg()
5334 << *Cand->DeductionFailure.getSecondArg();
5335 return;
5336 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005337
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005338 case Sema::TDK_InvalidExplicitArguments:
5339 assert(ParamD && "no parameter found for invalid explicit arguments");
5340 if (ParamD->getDeclName())
5341 S.Diag(Fn->getLocation(),
5342 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5343 << ParamD->getDeclName();
5344 else {
5345 int index = 0;
5346 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5347 index = TTP->getIndex();
5348 else if (NonTypeTemplateParmDecl *NTTP
5349 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5350 index = NTTP->getIndex();
5351 else
5352 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5353 S.Diag(Fn->getLocation(),
5354 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5355 << (index + 1);
5356 }
5357 return;
5358
Douglas Gregor02eb4832010-05-08 18:13:28 +00005359 case Sema::TDK_TooManyArguments:
5360 case Sema::TDK_TooFewArguments:
5361 DiagnoseArityMismatch(S, Cand, NumArgs);
5362 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005363
5364 case Sema::TDK_InstantiationDepth:
5365 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5366 return;
5367
5368 case Sema::TDK_SubstitutionFailure: {
5369 std::string ArgString;
5370 if (TemplateArgumentList *Args
5371 = Cand->DeductionFailure.getTemplateArgumentList())
5372 ArgString = S.getTemplateArgumentBindingsText(
5373 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5374 *Args);
5375 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5376 << ArgString;
5377 return;
5378 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005379
John McCall8b9ed552010-02-01 18:53:26 +00005380 // TODO: diagnose these individually, then kill off
5381 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005382 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005383 case Sema::TDK_FailedOverloadResolution:
5384 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5385 return;
5386 }
5387}
5388
5389/// Generates a 'note' diagnostic for an overload candidate. We've
5390/// already generated a primary error at the call site.
5391///
5392/// It really does need to be a single diagnostic with its caret
5393/// pointed at the candidate declaration. Yes, this creates some
5394/// major challenges of technical writing. Yes, this makes pointing
5395/// out problems with specific arguments quite awkward. It's still
5396/// better than generating twenty screens of text for every failed
5397/// overload.
5398///
5399/// It would be great to be able to express per-candidate problems
5400/// more richly for those diagnostic clients that cared, but we'd
5401/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005402void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5403 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005404 FunctionDecl *Fn = Cand->Function;
5405
John McCall12f97bc2010-01-08 04:41:39 +00005406 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005407 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005408 std::string FnDesc;
5409 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005410
5411 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005412 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005413 return;
John McCall12f97bc2010-01-08 04:41:39 +00005414 }
5415
John McCalle1ac8d12010-01-13 00:25:19 +00005416 // We don't really have anything else to say about viable candidates.
5417 if (Cand->Viable) {
5418 S.NoteOverloadCandidate(Fn);
5419 return;
5420 }
John McCall0d1da222010-01-12 00:44:57 +00005421
John McCall6a61b522010-01-13 09:16:55 +00005422 switch (Cand->FailureKind) {
5423 case ovl_fail_too_many_arguments:
5424 case ovl_fail_too_few_arguments:
5425 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005426
John McCall6a61b522010-01-13 09:16:55 +00005427 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005428 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5429
John McCallfe796dd2010-01-23 05:17:32 +00005430 case ovl_fail_trivial_conversion:
5431 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005432 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005433 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005434
John McCall65eb8792010-02-25 01:37:24 +00005435 case ovl_fail_bad_conversion: {
5436 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5437 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005438 if (Cand->Conversions[I].isBad())
5439 return DiagnoseBadConversion(S, Cand, I);
5440
5441 // FIXME: this currently happens when we're called from SemaInit
5442 // when user-conversion overload fails. Figure out how to handle
5443 // those conditions and diagnose them well.
5444 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005445 }
John McCall65eb8792010-02-25 01:37:24 +00005446 }
John McCalld3224162010-01-08 00:58:21 +00005447}
5448
5449void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5450 // Desugar the type of the surrogate down to a function type,
5451 // retaining as many typedefs as possible while still showing
5452 // the function type (and, therefore, its parameter types).
5453 QualType FnType = Cand->Surrogate->getConversionType();
5454 bool isLValueReference = false;
5455 bool isRValueReference = false;
5456 bool isPointer = false;
5457 if (const LValueReferenceType *FnTypeRef =
5458 FnType->getAs<LValueReferenceType>()) {
5459 FnType = FnTypeRef->getPointeeType();
5460 isLValueReference = true;
5461 } else if (const RValueReferenceType *FnTypeRef =
5462 FnType->getAs<RValueReferenceType>()) {
5463 FnType = FnTypeRef->getPointeeType();
5464 isRValueReference = true;
5465 }
5466 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5467 FnType = FnTypePtr->getPointeeType();
5468 isPointer = true;
5469 }
5470 // Desugar down to a function type.
5471 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5472 // Reconstruct the pointer/reference as appropriate.
5473 if (isPointer) FnType = S.Context.getPointerType(FnType);
5474 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5475 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5476
5477 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5478 << FnType;
5479}
5480
5481void NoteBuiltinOperatorCandidate(Sema &S,
5482 const char *Opc,
5483 SourceLocation OpLoc,
5484 OverloadCandidate *Cand) {
5485 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5486 std::string TypeStr("operator");
5487 TypeStr += Opc;
5488 TypeStr += "(";
5489 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5490 if (Cand->Conversions.size() == 1) {
5491 TypeStr += ")";
5492 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5493 } else {
5494 TypeStr += ", ";
5495 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5496 TypeStr += ")";
5497 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5498 }
5499}
5500
5501void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5502 OverloadCandidate *Cand) {
5503 unsigned NoOperands = Cand->Conversions.size();
5504 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5505 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005506 if (ICS.isBad()) break; // all meaningless after first invalid
5507 if (!ICS.isAmbiguous()) continue;
5508
5509 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005510 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005511 }
5512}
5513
John McCall3712d9e2010-01-15 23:32:50 +00005514SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5515 if (Cand->Function)
5516 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005517 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005518 return Cand->Surrogate->getLocation();
5519 return SourceLocation();
5520}
5521
John McCallad2587a2010-01-12 00:48:53 +00005522struct CompareOverloadCandidatesForDisplay {
5523 Sema &S;
5524 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005525
5526 bool operator()(const OverloadCandidate *L,
5527 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005528 // Fast-path this check.
5529 if (L == R) return false;
5530
John McCall12f97bc2010-01-08 04:41:39 +00005531 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005532 if (L->Viable) {
5533 if (!R->Viable) return true;
5534
5535 // TODO: introduce a tri-valued comparison for overload
5536 // candidates. Would be more worthwhile if we had a sort
5537 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005538 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5539 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005540 } else if (R->Viable)
5541 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005542
John McCall3712d9e2010-01-15 23:32:50 +00005543 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005544
John McCall3712d9e2010-01-15 23:32:50 +00005545 // Criteria by which we can sort non-viable candidates:
5546 if (!L->Viable) {
5547 // 1. Arity mismatches come after other candidates.
5548 if (L->FailureKind == ovl_fail_too_many_arguments ||
5549 L->FailureKind == ovl_fail_too_few_arguments)
5550 return false;
5551 if (R->FailureKind == ovl_fail_too_many_arguments ||
5552 R->FailureKind == ovl_fail_too_few_arguments)
5553 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005554
John McCallfe796dd2010-01-23 05:17:32 +00005555 // 2. Bad conversions come first and are ordered by the number
5556 // of bad conversions and quality of good conversions.
5557 if (L->FailureKind == ovl_fail_bad_conversion) {
5558 if (R->FailureKind != ovl_fail_bad_conversion)
5559 return true;
5560
5561 // If there's any ordering between the defined conversions...
5562 // FIXME: this might not be transitive.
5563 assert(L->Conversions.size() == R->Conversions.size());
5564
5565 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005566 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5567 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005568 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5569 R->Conversions[I])) {
5570 case ImplicitConversionSequence::Better:
5571 leftBetter++;
5572 break;
5573
5574 case ImplicitConversionSequence::Worse:
5575 leftBetter--;
5576 break;
5577
5578 case ImplicitConversionSequence::Indistinguishable:
5579 break;
5580 }
5581 }
5582 if (leftBetter > 0) return true;
5583 if (leftBetter < 0) return false;
5584
5585 } else if (R->FailureKind == ovl_fail_bad_conversion)
5586 return false;
5587
John McCall3712d9e2010-01-15 23:32:50 +00005588 // TODO: others?
5589 }
5590
5591 // Sort everything else by location.
5592 SourceLocation LLoc = GetLocationForCandidate(L);
5593 SourceLocation RLoc = GetLocationForCandidate(R);
5594
5595 // Put candidates without locations (e.g. builtins) at the end.
5596 if (LLoc.isInvalid()) return false;
5597 if (RLoc.isInvalid()) return true;
5598
5599 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005600 }
5601};
5602
John McCallfe796dd2010-01-23 05:17:32 +00005603/// CompleteNonViableCandidate - Normally, overload resolution only
5604/// computes up to the first
5605void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5606 Expr **Args, unsigned NumArgs) {
5607 assert(!Cand->Viable);
5608
5609 // Don't do anything on failures other than bad conversion.
5610 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5611
5612 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005613 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005614 unsigned ConvCount = Cand->Conversions.size();
5615 while (true) {
5616 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5617 ConvIdx++;
5618 if (Cand->Conversions[ConvIdx - 1].isBad())
5619 break;
5620 }
5621
5622 if (ConvIdx == ConvCount)
5623 return;
5624
John McCall65eb8792010-02-25 01:37:24 +00005625 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5626 "remaining conversion is initialized?");
5627
Douglas Gregoradc7a702010-04-16 17:45:54 +00005628 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005629 // operation somehow.
5630 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005631
5632 const FunctionProtoType* Proto;
5633 unsigned ArgIdx = ConvIdx;
5634
5635 if (Cand->IsSurrogate) {
5636 QualType ConvType
5637 = Cand->Surrogate->getConversionType().getNonReferenceType();
5638 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5639 ConvType = ConvPtrType->getPointeeType();
5640 Proto = ConvType->getAs<FunctionProtoType>();
5641 ArgIdx--;
5642 } else if (Cand->Function) {
5643 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5644 if (isa<CXXMethodDecl>(Cand->Function) &&
5645 !isa<CXXConstructorDecl>(Cand->Function))
5646 ArgIdx--;
5647 } else {
5648 // Builtin binary operator with a bad first conversion.
5649 assert(ConvCount <= 3);
5650 for (; ConvIdx != ConvCount; ++ConvIdx)
5651 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005652 = TryCopyInitialization(S, Args[ConvIdx],
5653 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5654 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005655 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005656 return;
5657 }
5658
5659 // Fill in the rest of the conversions.
5660 unsigned NumArgsInProto = Proto->getNumArgs();
5661 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5662 if (ArgIdx < NumArgsInProto)
5663 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005664 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5665 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005666 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005667 else
5668 Cand->Conversions[ConvIdx].setEllipsis();
5669 }
5670}
5671
John McCalld3224162010-01-08 00:58:21 +00005672} // end anonymous namespace
5673
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005674/// PrintOverloadCandidates - When overload resolution fails, prints
5675/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005676/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005677void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005678Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005679 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005680 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005681 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005682 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005683 // Sort the candidates by viability and position. Sorting directly would
5684 // be prohibitive, so we make a set of pointers and sort those.
5685 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5686 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5687 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5688 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005689 Cand != LastCand; ++Cand) {
5690 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005691 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005692 else if (OCD == OCD_AllCandidates) {
5693 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005694 if (Cand->Function || Cand->IsSurrogate)
5695 Cands.push_back(Cand);
5696 // Otherwise, this a non-viable builtin candidate. We do not, in general,
5697 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00005698 }
5699 }
5700
John McCallad2587a2010-01-12 00:48:53 +00005701 std::sort(Cands.begin(), Cands.end(),
5702 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005703
John McCall0d1da222010-01-12 00:44:57 +00005704 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005705
John McCall12f97bc2010-01-08 04:41:39 +00005706 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005707 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
5708 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00005709 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5710 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005711
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005712 // Set an arbitrary limit on the number of candidate functions we'll spam
5713 // the user with. FIXME: This limit should depend on details of the
5714 // candidate list.
5715 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
5716 break;
5717 }
5718 ++CandsShown;
5719
John McCalld3224162010-01-08 00:58:21 +00005720 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005721 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005722 else if (Cand->IsSurrogate)
5723 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005724 else {
5725 assert(Cand->Viable &&
5726 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00005727 // Generally we only see ambiguities including viable builtin
5728 // operators if overload resolution got screwed up by an
5729 // ambiguous user-defined conversion.
5730 //
5731 // FIXME: It's quite possible for different conversions to see
5732 // different ambiguities, though.
5733 if (!ReportedAmbiguousConversions) {
5734 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5735 ReportedAmbiguousConversions = true;
5736 }
John McCalld3224162010-01-08 00:58:21 +00005737
John McCall0d1da222010-01-12 00:44:57 +00005738 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005739 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005740 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005741 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005742
5743 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00005744 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005745}
5746
John McCalla0296f72010-03-19 07:35:19 +00005747static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005748 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005749 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005750
John McCalla0296f72010-03-19 07:35:19 +00005751 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005752}
5753
Douglas Gregorcd695e52008-11-10 20:40:00 +00005754/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5755/// an overloaded function (C++ [over.over]), where @p From is an
5756/// expression with overloaded function type and @p ToType is the type
5757/// we're trying to resolve to. For example:
5758///
5759/// @code
5760/// int f(double);
5761/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005762///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005763/// int (*pfd)(double) = f; // selects f(double)
5764/// @endcode
5765///
5766/// This routine returns the resulting FunctionDecl if it could be
5767/// resolved, and NULL otherwise. When @p Complain is true, this
5768/// routine will emit diagnostics if there is an error.
5769FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005770Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005771 bool Complain,
5772 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005773 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005774 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005775 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005776 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005777 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005778 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005779 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005780 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005781 FunctionType = MemTypePtr->getPointeeType();
5782 IsMember = true;
5783 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005784
Douglas Gregorcd695e52008-11-10 20:40:00 +00005785 // C++ [over.over]p1:
5786 // [...] [Note: any redundant set of parentheses surrounding the
5787 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005788 // C++ [over.over]p1:
5789 // [...] The overloaded function name can be preceded by the &
5790 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005791 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5792 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5793 if (OvlExpr->hasExplicitTemplateArgs()) {
5794 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5795 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005796 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005797
5798 // We expect a pointer or reference to function, or a function pointer.
5799 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5800 if (!FunctionType->isFunctionType()) {
5801 if (Complain)
5802 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5803 << OvlExpr->getName() << ToType;
5804
5805 return 0;
5806 }
5807
5808 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005809
Douglas Gregorcd695e52008-11-10 20:40:00 +00005810 // Look through all of the overloaded functions, searching for one
5811 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005812 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005813 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5814
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005815 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005816 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5817 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005818 // Look through any using declarations to find the underlying function.
5819 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5820
Douglas Gregorcd695e52008-11-10 20:40:00 +00005821 // C++ [over.over]p3:
5822 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005823 // targets of type "pointer-to-function" or "reference-to-function."
5824 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005825 // type "pointer-to-member-function."
5826 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005827
Mike Stump11289f42009-09-09 15:08:12 +00005828 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005829 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005830 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005831 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005832 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005833 // static when converting to member pointer.
5834 if (Method->isStatic() == IsMember)
5835 continue;
5836 } else if (IsMember)
5837 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005838
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005839 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005840 // If the name is a function template, template argument deduction is
5841 // done (14.8.2.2), and if the argument deduction succeeds, the
5842 // resulting template argument list is used to generate a single
5843 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005844 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005845 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005846 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005847 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005848 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005849 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005850 FunctionType, Specialization, Info)) {
5851 // FIXME: make a note of the failed deduction for diagnostics.
5852 (void)Result;
5853 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005854 // FIXME: If the match isn't exact, shouldn't we just drop this as
5855 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005856 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005857 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005858 Matches.push_back(std::make_pair(I.getPair(),
5859 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005860 }
John McCalld14a8642009-11-21 08:51:07 +00005861
5862 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005863 }
Mike Stump11289f42009-09-09 15:08:12 +00005864
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005865 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005866 // Skip non-static functions when converting to pointer, and static
5867 // when converting to member pointer.
5868 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005869 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005870
5871 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005872 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005873 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005874 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005875 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005876
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005877 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005878 QualType ResultTy;
5879 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5880 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5881 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005882 Matches.push_back(std::make_pair(I.getPair(),
5883 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005884 FoundNonTemplateFunction = true;
5885 }
Mike Stump11289f42009-09-09 15:08:12 +00005886 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005887 }
5888
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005889 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005890 if (Matches.empty()) {
5891 if (Complain) {
5892 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5893 << OvlExpr->getName() << FunctionType;
5894 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5895 E = OvlExpr->decls_end();
5896 I != E; ++I)
5897 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5898 NoteOverloadCandidate(F);
5899 }
5900
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005901 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005902 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005903 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005904 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005905 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005906 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005907 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005908 return Result;
5909 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005910
5911 // C++ [over.over]p4:
5912 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005913 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005914 // [...] and any given function template specialization F1 is
5915 // eliminated if the set contains a second function template
5916 // specialization whose function template is more specialized
5917 // than the function template of F1 according to the partial
5918 // ordering rules of 14.5.5.2.
5919
5920 // The algorithm specified above is quadratic. We instead use a
5921 // two-pass algorithm (similar to the one used to identify the
5922 // best viable function in an overload set) that identifies the
5923 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005924
5925 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5926 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5927 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005928
5929 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005930 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005931 TPOC_Other, From->getLocStart(),
5932 PDiag(),
5933 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005934 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005935 PDiag(diag::note_ovl_candidate)
5936 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005937 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005938 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005939 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005940 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005941 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005942 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5943 }
John McCall58cc69d2010-01-27 01:50:18 +00005944 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005945 }
Mike Stump11289f42009-09-09 15:08:12 +00005946
Douglas Gregorfae1d712009-09-26 03:56:17 +00005947 // [...] any function template specializations in the set are
5948 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005949 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005950 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005951 ++I;
5952 else {
John McCalla0296f72010-03-19 07:35:19 +00005953 Matches[I] = Matches[--N];
5954 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005955 }
5956 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005957
Mike Stump11289f42009-09-09 15:08:12 +00005958 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005959 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005960 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005961 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005962 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005963 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00005964 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00005965 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5966 }
John McCalla0296f72010-03-19 07:35:19 +00005967 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005968 }
Mike Stump11289f42009-09-09 15:08:12 +00005969
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005970 // FIXME: We should probably return the same thing that BestViableFunction
5971 // returns (even if we issue the diagnostics here).
5972 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005973 << Matches[0].second->getDeclName();
5974 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5975 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005976 return 0;
5977}
5978
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005979/// \brief Given an expression that refers to an overloaded function, try to
5980/// resolve that overloaded function expression down to a single function.
5981///
5982/// This routine can only resolve template-ids that refer to a single function
5983/// template, where that template-id refers to a single template whose template
5984/// arguments are either provided by the template-id or have defaults,
5985/// as described in C++0x [temp.arg.explicit]p3.
5986FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5987 // C++ [over.over]p1:
5988 // [...] [Note: any redundant set of parentheses surrounding the
5989 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005990 // C++ [over.over]p1:
5991 // [...] The overloaded function name can be preceded by the &
5992 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005993
5994 if (From->getType() != Context.OverloadTy)
5995 return 0;
5996
5997 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005998
5999 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006000 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006001 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006002
6003 TemplateArgumentListInfo ExplicitTemplateArgs;
6004 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006005
6006 // Look through all of the overloaded functions, searching for one
6007 // whose type matches exactly.
6008 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006009 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6010 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006011 // C++0x [temp.arg.explicit]p3:
6012 // [...] In contexts where deduction is done and fails, or in contexts
6013 // where deduction is not done, if a template argument list is
6014 // specified and it, along with any default template arguments,
6015 // identifies a single function template specialization, then the
6016 // template-id is an lvalue for the function template specialization.
6017 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
6018
6019 // C++ [over.over]p2:
6020 // If the name is a function template, template argument deduction is
6021 // done (14.8.2.2), and if the argument deduction succeeds, the
6022 // resulting template argument list is used to generate a single
6023 // function template specialization, which is added to the set of
6024 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006025 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006026 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006027 if (TemplateDeductionResult Result
6028 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6029 Specialization, Info)) {
6030 // FIXME: make a note of the failed deduction for diagnostics.
6031 (void)Result;
6032 continue;
6033 }
6034
6035 // Multiple matches; we can't resolve to a single declaration.
6036 if (Matched)
6037 return 0;
6038
6039 Matched = Specialization;
6040 }
6041
6042 return Matched;
6043}
6044
Douglas Gregorcabea402009-09-22 15:41:20 +00006045/// \brief Add a single candidate to the overload set.
6046static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006047 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006048 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006049 Expr **Args, unsigned NumArgs,
6050 OverloadCandidateSet &CandidateSet,
6051 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006052 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006053 if (isa<UsingShadowDecl>(Callee))
6054 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6055
Douglas Gregorcabea402009-09-22 15:41:20 +00006056 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006057 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006058 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006059 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006060 return;
John McCalld14a8642009-11-21 08:51:07 +00006061 }
6062
6063 if (FunctionTemplateDecl *FuncTemplate
6064 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006065 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6066 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006067 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006068 return;
6069 }
6070
6071 assert(false && "unhandled case in overloaded call candidate");
6072
6073 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006074}
6075
6076/// \brief Add the overload candidates named by callee and/or found by argument
6077/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006078void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006079 Expr **Args, unsigned NumArgs,
6080 OverloadCandidateSet &CandidateSet,
6081 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006082
6083#ifndef NDEBUG
6084 // Verify that ArgumentDependentLookup is consistent with the rules
6085 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006086 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006087 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6088 // and let Y be the lookup set produced by argument dependent
6089 // lookup (defined as follows). If X contains
6090 //
6091 // -- a declaration of a class member, or
6092 //
6093 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006094 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006095 //
6096 // -- a declaration that is neither a function or a function
6097 // template
6098 //
6099 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006100
John McCall57500772009-12-16 12:17:52 +00006101 if (ULE->requiresADL()) {
6102 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6103 E = ULE->decls_end(); I != E; ++I) {
6104 assert(!(*I)->getDeclContext()->isRecord());
6105 assert(isa<UsingShadowDecl>(*I) ||
6106 !(*I)->getDeclContext()->isFunctionOrMethod());
6107 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006108 }
6109 }
6110#endif
6111
John McCall57500772009-12-16 12:17:52 +00006112 // It would be nice to avoid this copy.
6113 TemplateArgumentListInfo TABuffer;
6114 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6115 if (ULE->hasExplicitTemplateArgs()) {
6116 ULE->copyTemplateArgumentsInto(TABuffer);
6117 ExplicitTemplateArgs = &TABuffer;
6118 }
6119
6120 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6121 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006122 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006123 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006124 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006125
John McCall57500772009-12-16 12:17:52 +00006126 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006127 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6128 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006129 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006130 CandidateSet,
6131 PartialOverloading);
6132}
John McCalld681c392009-12-16 08:11:27 +00006133
John McCall57500772009-12-16 12:17:52 +00006134static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6135 Expr **Args, unsigned NumArgs) {
6136 Fn->Destroy(SemaRef.Context);
6137 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6138 Args[Arg]->Destroy(SemaRef.Context);
6139 return SemaRef.ExprError();
6140}
6141
John McCalld681c392009-12-16 08:11:27 +00006142/// Attempts to recover from a call where no functions were found.
6143///
6144/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006145static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006146BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006147 UnresolvedLookupExpr *ULE,
6148 SourceLocation LParenLoc,
6149 Expr **Args, unsigned NumArgs,
6150 SourceLocation *CommaLocs,
6151 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006152
6153 CXXScopeSpec SS;
6154 if (ULE->getQualifier()) {
6155 SS.setScopeRep(ULE->getQualifier());
6156 SS.setRange(ULE->getQualifierRange());
6157 }
6158
John McCall57500772009-12-16 12:17:52 +00006159 TemplateArgumentListInfo TABuffer;
6160 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6161 if (ULE->hasExplicitTemplateArgs()) {
6162 ULE->copyTemplateArgumentsInto(TABuffer);
6163 ExplicitTemplateArgs = &TABuffer;
6164 }
6165
John McCalld681c392009-12-16 08:11:27 +00006166 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6167 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006168 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall57500772009-12-16 12:17:52 +00006169 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00006170
John McCall57500772009-12-16 12:17:52 +00006171 assert(!R.empty() && "lookup results empty despite recovery");
6172
6173 // Build an implicit member call if appropriate. Just drop the
6174 // casts and such from the call, we don't really care.
6175 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6176 if ((*R.begin())->isCXXClassMember())
6177 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6178 else if (ExplicitTemplateArgs)
6179 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6180 else
6181 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6182
6183 if (NewFn.isInvalid())
6184 return Destroy(SemaRef, Fn, Args, NumArgs);
6185
6186 Fn->Destroy(SemaRef.Context);
6187
6188 // This shouldn't cause an infinite loop because we're giving it
6189 // an expression with non-empty lookup results, which should never
6190 // end up here.
6191 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6192 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6193 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006194}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006195
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006196/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006197/// (which eventually refers to the declaration Func) and the call
6198/// arguments Args/NumArgs, attempt to resolve the function call down
6199/// to a specific function. If overload resolution succeeds, returns
6200/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006201/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006202/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006203Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006204Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006205 SourceLocation LParenLoc,
6206 Expr **Args, unsigned NumArgs,
6207 SourceLocation *CommaLocs,
6208 SourceLocation RParenLoc) {
6209#ifndef NDEBUG
6210 if (ULE->requiresADL()) {
6211 // To do ADL, we must have found an unqualified name.
6212 assert(!ULE->getQualifier() && "qualified name with ADL");
6213
6214 // We don't perform ADL for implicit declarations of builtins.
6215 // Verify that this was correctly set up.
6216 FunctionDecl *F;
6217 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6218 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6219 F->getBuiltinID() && F->isImplicit())
6220 assert(0 && "performing ADL for builtin");
6221
6222 // We don't perform ADL in C.
6223 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6224 }
6225#endif
6226
John McCallbc077cf2010-02-08 23:07:23 +00006227 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006228
John McCall57500772009-12-16 12:17:52 +00006229 // Add the functions denoted by the callee to the set of candidate
6230 // functions, including those from argument-dependent lookup.
6231 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006232
6233 // If we found nothing, try to recover.
6234 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6235 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006236 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006237 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006238 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006239
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006240 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006241 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006242 case OR_Success: {
6243 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006244 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006245 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006246 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006247 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6248 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006249
6250 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006251 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006252 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006253 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006254 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006255 break;
6256
6257 case OR_Ambiguous:
6258 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006259 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006260 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006261 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006262
6263 case OR_Deleted:
6264 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6265 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006266 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006267 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006268 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006269 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006270 }
6271
6272 // Overload resolution failed. Destroy all of the subexpressions and
6273 // return NULL.
6274 Fn->Destroy(Context);
6275 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6276 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006277 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006278}
6279
John McCall4c4c1df2010-01-26 03:27:55 +00006280static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006281 return Functions.size() > 1 ||
6282 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6283}
6284
Douglas Gregor084d8552009-03-13 23:49:33 +00006285/// \brief Create a unary operation that may resolve to an overloaded
6286/// operator.
6287///
6288/// \param OpLoc The location of the operator itself (e.g., '*').
6289///
6290/// \param OpcIn The UnaryOperator::Opcode that describes this
6291/// operator.
6292///
6293/// \param Functions The set of non-member functions that will be
6294/// considered by overload resolution. The caller needs to build this
6295/// set based on the context using, e.g.,
6296/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6297/// set should not contain any member functions; those will be added
6298/// by CreateOverloadedUnaryOp().
6299///
6300/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006301Sema::OwningExprResult
6302Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6303 const UnresolvedSetImpl &Fns,
6304 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006305 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6306 Expr *Input = (Expr *)input.get();
6307
6308 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6309 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6310 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6311
6312 Expr *Args[2] = { Input, 0 };
6313 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006314
Douglas Gregor084d8552009-03-13 23:49:33 +00006315 // For post-increment and post-decrement, add the implicit '0' as
6316 // the second argument, so that we know this is a post-increment or
6317 // post-decrement.
6318 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6319 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006320 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006321 SourceLocation());
6322 NumArgs = 2;
6323 }
6324
6325 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00006326 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006327 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006328 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006329 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006330 /*ADL*/ true, IsOverloaded(Fns),
6331 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006332 input.release();
6333 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6334 &Args[0], NumArgs,
6335 Context.DependentTy,
6336 OpLoc));
6337 }
6338
6339 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006340 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006341
6342 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006343 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006344
6345 // Add operator candidates that are member functions.
6346 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6347
John McCall4c4c1df2010-01-26 03:27:55 +00006348 // Add candidates from ADL.
6349 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006350 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006351 /*ExplicitTemplateArgs*/ 0,
6352 CandidateSet);
6353
Douglas Gregor084d8552009-03-13 23:49:33 +00006354 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006355 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006356
6357 // Perform overload resolution.
6358 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006359 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006360 case OR_Success: {
6361 // We found a built-in operator or an overloaded operator.
6362 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006363
Douglas Gregor084d8552009-03-13 23:49:33 +00006364 if (FnDecl) {
6365 // We matched an overloaded operator. Build a call to that
6366 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006367
Douglas Gregor084d8552009-03-13 23:49:33 +00006368 // Convert the arguments.
6369 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006370 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006371
John McCall16df1e52010-03-30 21:47:33 +00006372 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6373 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006374 return ExprError();
6375 } else {
6376 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006377 OwningExprResult InputInit
6378 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006379 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006380 SourceLocation(),
6381 move(input));
6382 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006383 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006384
Douglas Gregore6600372009-12-23 17:40:29 +00006385 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006386 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006387 }
6388
John McCall4fa0d5f2010-05-06 18:15:07 +00006389 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6390
Douglas Gregor084d8552009-03-13 23:49:33 +00006391 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006392 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006393
Douglas Gregor084d8552009-03-13 23:49:33 +00006394 // Build the actual expression node.
6395 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6396 SourceLocation());
6397 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006398
Douglas Gregor084d8552009-03-13 23:49:33 +00006399 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006400 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006401 ExprOwningPtr<CallExpr> TheCall(this,
6402 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006403 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006404
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006405 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6406 FnDecl))
6407 return ExprError();
6408
6409 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006410 } else {
6411 // We matched a built-in operator. Convert the arguments, then
6412 // break out so that we will build the appropriate built-in
6413 // operator node.
6414 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006415 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006416 return ExprError();
6417
6418 break;
6419 }
6420 }
6421
6422 case OR_No_Viable_Function:
6423 // No viable function; fall through to handling this as a
6424 // built-in operator, which will produce an error message for us.
6425 break;
6426
6427 case OR_Ambiguous:
6428 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6429 << UnaryOperator::getOpcodeStr(Opc)
6430 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006431 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006432 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006433 return ExprError();
6434
6435 case OR_Deleted:
6436 Diag(OpLoc, diag::err_ovl_deleted_oper)
6437 << Best->Function->isDeleted()
6438 << UnaryOperator::getOpcodeStr(Opc)
6439 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006440 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006441 return ExprError();
6442 }
6443
6444 // Either we found no viable overloaded operator or we matched a
6445 // built-in operator. In either case, fall through to trying to
6446 // build a built-in operation.
6447 input.release();
6448 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6449}
6450
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006451/// \brief Create a binary operation that may resolve to an overloaded
6452/// operator.
6453///
6454/// \param OpLoc The location of the operator itself (e.g., '+').
6455///
6456/// \param OpcIn The BinaryOperator::Opcode that describes this
6457/// operator.
6458///
6459/// \param Functions The set of non-member functions that will be
6460/// considered by overload resolution. The caller needs to build this
6461/// set based on the context using, e.g.,
6462/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6463/// set should not contain any member functions; those will be added
6464/// by CreateOverloadedBinOp().
6465///
6466/// \param LHS Left-hand argument.
6467/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006468Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006469Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006470 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006471 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006472 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006473 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006474 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006475
6476 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6477 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6478 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6479
6480 // If either side is type-dependent, create an appropriate dependent
6481 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006482 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006483 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006484 // If there are no functions to store, just build a dependent
6485 // BinaryOperator or CompoundAssignment.
6486 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6487 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6488 Context.DependentTy, OpLoc));
6489
6490 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6491 Context.DependentTy,
6492 Context.DependentTy,
6493 Context.DependentTy,
6494 OpLoc));
6495 }
John McCall4c4c1df2010-01-26 03:27:55 +00006496
6497 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006498 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006499 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006500 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006501 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006502 /*ADL*/ true, IsOverloaded(Fns),
6503 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006504 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006505 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006506 Context.DependentTy,
6507 OpLoc));
6508 }
6509
6510 // If this is the .* operator, which is not overloadable, just
6511 // create a built-in binary operator.
6512 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006513 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006514
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006515 // If this is the assignment operator, we only perform overload resolution
6516 // if the left-hand side is a class or enumeration type. This is actually
6517 // a hack. The standard requires that we do overload resolution between the
6518 // various built-in candidates, but as DR507 points out, this can lead to
6519 // problems. So we do it this way, which pretty much follows what GCC does.
6520 // Note that we go the traditional code path for compound assignment forms.
6521 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006522 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006523
Douglas Gregor084d8552009-03-13 23:49:33 +00006524 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006525 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006526
6527 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006528 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006529
6530 // Add operator candidates that are member functions.
6531 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6532
John McCall4c4c1df2010-01-26 03:27:55 +00006533 // Add candidates from ADL.
6534 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6535 Args, 2,
6536 /*ExplicitTemplateArgs*/ 0,
6537 CandidateSet);
6538
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006539 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006540 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006541
6542 // Perform overload resolution.
6543 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006544 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006545 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006546 // We found a built-in operator or an overloaded operator.
6547 FunctionDecl *FnDecl = Best->Function;
6548
6549 if (FnDecl) {
6550 // We matched an overloaded operator. Build a call to that
6551 // operator.
6552
6553 // Convert the arguments.
6554 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006555 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006556 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006557
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006558 OwningExprResult Arg1
6559 = PerformCopyInitialization(
6560 InitializedEntity::InitializeParameter(
6561 FnDecl->getParamDecl(0)),
6562 SourceLocation(),
6563 Owned(Args[1]));
6564 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006565 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006566
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006567 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006568 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006569 return ExprError();
6570
6571 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006572 } else {
6573 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006574 OwningExprResult Arg0
6575 = PerformCopyInitialization(
6576 InitializedEntity::InitializeParameter(
6577 FnDecl->getParamDecl(0)),
6578 SourceLocation(),
6579 Owned(Args[0]));
6580 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006581 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006582
6583 OwningExprResult Arg1
6584 = PerformCopyInitialization(
6585 InitializedEntity::InitializeParameter(
6586 FnDecl->getParamDecl(1)),
6587 SourceLocation(),
6588 Owned(Args[1]));
6589 if (Arg1.isInvalid())
6590 return ExprError();
6591 Args[0] = LHS = Arg0.takeAs<Expr>();
6592 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006593 }
6594
John McCall4fa0d5f2010-05-06 18:15:07 +00006595 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6596
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006597 // Determine the result type
6598 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006599 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006600 ResultTy = ResultTy.getNonReferenceType();
6601
6602 // Build the actual expression node.
6603 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006604 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006605 UsualUnaryConversions(FnExpr);
6606
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006607 ExprOwningPtr<CXXOperatorCallExpr>
6608 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6609 Args, 2, ResultTy,
6610 OpLoc));
6611
6612 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6613 FnDecl))
6614 return ExprError();
6615
6616 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006617 } else {
6618 // We matched a built-in operator. Convert the arguments, then
6619 // break out so that we will build the appropriate built-in
6620 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006621 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006622 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006623 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006624 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006625 return ExprError();
6626
6627 break;
6628 }
6629 }
6630
Douglas Gregor66950a32009-09-30 21:46:01 +00006631 case OR_No_Viable_Function: {
6632 // C++ [over.match.oper]p9:
6633 // If the operator is the operator , [...] and there are no
6634 // viable functions, then the operator is assumed to be the
6635 // built-in operator and interpreted according to clause 5.
6636 if (Opc == BinaryOperator::Comma)
6637 break;
6638
Sebastian Redl027de2a2009-05-21 11:50:50 +00006639 // For class as left operand for assignment or compound assigment operator
6640 // do not fall through to handling in built-in, but report that no overloaded
6641 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006642 OwningExprResult Result = ExprError();
6643 if (Args[0]->getType()->isRecordType() &&
6644 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006645 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6646 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006647 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006648 } else {
6649 // No viable function; try to create a built-in operation, which will
6650 // produce an error. Then, show the non-viable candidates.
6651 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006652 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006653 assert(Result.isInvalid() &&
6654 "C++ binary operator overloading is missing candidates!");
6655 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006656 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006657 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006658 return move(Result);
6659 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006660
6661 case OR_Ambiguous:
6662 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6663 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006664 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006665 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006666 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006667 return ExprError();
6668
6669 case OR_Deleted:
6670 Diag(OpLoc, diag::err_ovl_deleted_oper)
6671 << Best->Function->isDeleted()
6672 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006673 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006674 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006675 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006676 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006677
Douglas Gregor66950a32009-09-30 21:46:01 +00006678 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006679 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006680}
6681
Sebastian Redladba46e2009-10-29 20:17:01 +00006682Action::OwningExprResult
6683Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6684 SourceLocation RLoc,
6685 ExprArg Base, ExprArg Idx) {
6686 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6687 static_cast<Expr*>(Idx.get()) };
6688 DeclarationName OpName =
6689 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6690
6691 // If either side is type-dependent, create an appropriate dependent
6692 // expression.
6693 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6694
John McCall58cc69d2010-01-27 01:50:18 +00006695 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006696 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006697 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006698 0, SourceRange(), OpName, LLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006699 /*ADL*/ true, /*Overloaded*/ false,
6700 UnresolvedSetIterator(),
6701 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00006702 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006703
6704 Base.release();
6705 Idx.release();
6706 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6707 Args, 2,
6708 Context.DependentTy,
6709 RLoc));
6710 }
6711
6712 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006713 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006714
6715 // Subscript can only be overloaded as a member function.
6716
6717 // Add operator candidates that are member functions.
6718 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6719
6720 // Add builtin operator candidates.
6721 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6722
6723 // Perform overload resolution.
6724 OverloadCandidateSet::iterator Best;
6725 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6726 case OR_Success: {
6727 // We found a built-in operator or an overloaded operator.
6728 FunctionDecl *FnDecl = Best->Function;
6729
6730 if (FnDecl) {
6731 // We matched an overloaded operator. Build a call to that
6732 // operator.
6733
John McCalla0296f72010-03-19 07:35:19 +00006734 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006735 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006736
Sebastian Redladba46e2009-10-29 20:17:01 +00006737 // Convert the arguments.
6738 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006739 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006740 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006741 return ExprError();
6742
Anders Carlssona68e51e2010-01-29 18:37:50 +00006743 // Convert the arguments.
6744 OwningExprResult InputInit
6745 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6746 FnDecl->getParamDecl(0)),
6747 SourceLocation(),
6748 Owned(Args[1]));
6749 if (InputInit.isInvalid())
6750 return ExprError();
6751
6752 Args[1] = InputInit.takeAs<Expr>();
6753
Sebastian Redladba46e2009-10-29 20:17:01 +00006754 // Determine the result type
6755 QualType ResultTy
6756 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6757 ResultTy = ResultTy.getNonReferenceType();
6758
6759 // Build the actual expression node.
6760 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6761 LLoc);
6762 UsualUnaryConversions(FnExpr);
6763
6764 Base.release();
6765 Idx.release();
6766 ExprOwningPtr<CXXOperatorCallExpr>
6767 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6768 FnExpr, Args, 2,
6769 ResultTy, RLoc));
6770
6771 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6772 FnDecl))
6773 return ExprError();
6774
6775 return MaybeBindToTemporary(TheCall.release());
6776 } else {
6777 // We matched a built-in operator. Convert the arguments, then
6778 // break out so that we will build the appropriate built-in
6779 // operator node.
6780 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006781 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006782 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006783 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006784 return ExprError();
6785
6786 break;
6787 }
6788 }
6789
6790 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006791 if (CandidateSet.empty())
6792 Diag(LLoc, diag::err_ovl_no_oper)
6793 << Args[0]->getType() << /*subscript*/ 0
6794 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6795 else
6796 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6797 << Args[0]->getType()
6798 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006799 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006800 "[]", LLoc);
6801 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006802 }
6803
6804 case OR_Ambiguous:
6805 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6806 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006807 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006808 "[]", LLoc);
6809 return ExprError();
6810
6811 case OR_Deleted:
6812 Diag(LLoc, diag::err_ovl_deleted_oper)
6813 << Best->Function->isDeleted() << "[]"
6814 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006815 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006816 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006817 return ExprError();
6818 }
6819
6820 // We matched a built-in operator; build it.
6821 Base.release();
6822 Idx.release();
6823 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6824 Owned(Args[1]), RLoc);
6825}
6826
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006827/// BuildCallToMemberFunction - Build a call to a member
6828/// function. MemExpr is the expression that refers to the member
6829/// function (and includes the object parameter), Args/NumArgs are the
6830/// arguments to the function call (not including the object
6831/// parameter). The caller needs to validate that the member
6832/// expression refers to a member function or an overloaded member
6833/// function.
John McCall2d74de92009-12-01 22:10:20 +00006834Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006835Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6836 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006837 unsigned NumArgs, SourceLocation *CommaLocs,
6838 SourceLocation RParenLoc) {
6839 // Dig out the member expression. This holds both the object
6840 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006841 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6842
John McCall10eae182009-11-30 22:42:35 +00006843 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006844 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006845 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006846 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006847 if (isa<MemberExpr>(NakedMemExpr)) {
6848 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006849 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006850 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006851 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006852 } else {
6853 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006854 Qualifier = UnresExpr->getQualifier();
6855
John McCall6e9f8f62009-12-03 04:06:58 +00006856 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006857
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006858 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006859 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006860
John McCall2d74de92009-12-01 22:10:20 +00006861 // FIXME: avoid copy.
6862 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6863 if (UnresExpr->hasExplicitTemplateArgs()) {
6864 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6865 TemplateArgs = &TemplateArgsBuffer;
6866 }
6867
John McCall10eae182009-11-30 22:42:35 +00006868 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6869 E = UnresExpr->decls_end(); I != E; ++I) {
6870
John McCall6e9f8f62009-12-03 04:06:58 +00006871 NamedDecl *Func = *I;
6872 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6873 if (isa<UsingShadowDecl>(Func))
6874 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6875
John McCall10eae182009-11-30 22:42:35 +00006876 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006877 // If explicit template arguments were provided, we can't call a
6878 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006879 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006880 continue;
6881
John McCalla0296f72010-03-19 07:35:19 +00006882 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006883 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006884 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006885 } else {
John McCall10eae182009-11-30 22:42:35 +00006886 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006887 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006888 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006889 CandidateSet,
6890 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006891 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006892 }
Mike Stump11289f42009-09-09 15:08:12 +00006893
John McCall10eae182009-11-30 22:42:35 +00006894 DeclarationName DeclName = UnresExpr->getMemberName();
6895
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006896 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006897 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006898 case OR_Success:
6899 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006900 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006901 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006902 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006903 break;
6904
6905 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006906 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006907 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006908 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006909 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006910 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006911 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006912
6913 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006914 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006915 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006916 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006917 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006918 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006919
6920 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006921 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006922 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006923 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006924 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006925 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006926 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006927 }
6928
John McCall16df1e52010-03-30 21:47:33 +00006929 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006930
John McCall2d74de92009-12-01 22:10:20 +00006931 // If overload resolution picked a static member, build a
6932 // non-member call based on that function.
6933 if (Method->isStatic()) {
6934 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6935 Args, NumArgs, RParenLoc);
6936 }
6937
John McCall10eae182009-11-30 22:42:35 +00006938 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006939 }
6940
6941 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006942 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006943 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006944 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006945 Method->getResultType().getNonReferenceType(),
6946 RParenLoc));
6947
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006948 // Check for a valid return type.
6949 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6950 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006951 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006952
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006953 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006954 // We only need to do this if there was actually an overload; otherwise
6955 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006956 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006957 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006958 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6959 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006960 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006961 MemExpr->setBase(ObjectArg);
6962
6963 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00006964 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00006965 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006966 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006967 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006968
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006969 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006970 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006971
John McCall2d74de92009-12-01 22:10:20 +00006972 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006973}
6974
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006975/// BuildCallToObjectOfClassType - Build a call to an object of class
6976/// type (C++ [over.call.object]), which can end up invoking an
6977/// overloaded function call operator (@c operator()) or performing a
6978/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006979Sema::ExprResult
6980Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006981 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006982 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006983 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006984 SourceLocation RParenLoc) {
6985 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006986 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006987
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006988 // C++ [over.call.object]p1:
6989 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006990 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006991 // candidate functions includes at least the function call
6992 // operators of T. The function call operators of T are obtained by
6993 // ordinary lookup of the name operator() in the context of
6994 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006995 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006996 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006997
6998 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006999 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007000 << Object->getSourceRange()))
7001 return true;
7002
John McCall27b18f82009-11-17 02:14:36 +00007003 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7004 LookupQualifiedName(R, Record->getDecl());
7005 R.suppressDiagnostics();
7006
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007007 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007008 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007009 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007010 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007011 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007012 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007013
Douglas Gregorab7897a2008-11-19 22:57:39 +00007014 // C++ [over.call.object]p2:
7015 // In addition, for each conversion function declared in T of the
7016 // form
7017 //
7018 // operator conversion-type-id () cv-qualifier;
7019 //
7020 // where cv-qualifier is the same cv-qualification as, or a
7021 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007022 // denotes the type "pointer to function of (P1,...,Pn) returning
7023 // R", or the type "reference to pointer to function of
7024 // (P1,...,Pn) returning R", or the type "reference to function
7025 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007026 // is also considered as a candidate function. Similarly,
7027 // surrogate call functions are added to the set of candidate
7028 // functions for each conversion function declared in an
7029 // accessible base class provided the function is not hidden
7030 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007031 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007032 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007033 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007034 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007035 NamedDecl *D = *I;
7036 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7037 if (isa<UsingShadowDecl>(D))
7038 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7039
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007040 // Skip over templated conversion functions; they aren't
7041 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007042 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007043 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007044
John McCall6e9f8f62009-12-03 04:06:58 +00007045 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007046
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007047 // Strip the reference type (if any) and then the pointer type (if
7048 // any) to get down to what might be a function type.
7049 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7050 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7051 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007052
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007053 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007054 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007055 Object->getType(), Args, NumArgs,
7056 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007057 }
Mike Stump11289f42009-09-09 15:08:12 +00007058
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007059 // Perform overload resolution.
7060 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007061 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007062 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007063 // Overload resolution succeeded; we'll build the appropriate call
7064 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007065 break;
7066
7067 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007068 if (CandidateSet.empty())
7069 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7070 << Object->getType() << /*call*/ 1
7071 << Object->getSourceRange();
7072 else
7073 Diag(Object->getSourceRange().getBegin(),
7074 diag::err_ovl_no_viable_object_call)
7075 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007076 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007077 break;
7078
7079 case OR_Ambiguous:
7080 Diag(Object->getSourceRange().getBegin(),
7081 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007082 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007083 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007084 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007085
7086 case OR_Deleted:
7087 Diag(Object->getSourceRange().getBegin(),
7088 diag::err_ovl_deleted_object_call)
7089 << Best->Function->isDeleted()
7090 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007091 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007092 break;
Mike Stump11289f42009-09-09 15:08:12 +00007093 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007094
Douglas Gregorab7897a2008-11-19 22:57:39 +00007095 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007096 // We had an error; delete all of the subexpressions and return
7097 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00007098 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007099 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00007100 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007101 return true;
7102 }
7103
Douglas Gregorab7897a2008-11-19 22:57:39 +00007104 if (Best->Function == 0) {
7105 // Since there is no function declaration, this is one of the
7106 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007107 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007108 = cast<CXXConversionDecl>(
7109 Best->Conversions[0].UserDefined.ConversionFunction);
7110
John McCalla0296f72010-03-19 07:35:19 +00007111 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007112 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007113
Douglas Gregorab7897a2008-11-19 22:57:39 +00007114 // We selected one of the surrogate functions that converts the
7115 // object parameter to a function pointer. Perform the conversion
7116 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007117
7118 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007119 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007120 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7121 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007122
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007123 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007124 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007125 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007126 }
7127
John McCalla0296f72010-03-19 07:35:19 +00007128 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007129 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007130
Douglas Gregorab7897a2008-11-19 22:57:39 +00007131 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7132 // that calls this method, using Object for the implicit object
7133 // parameter and passing along the remaining arguments.
7134 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007135 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007136
7137 unsigned NumArgsInProto = Proto->getNumArgs();
7138 unsigned NumArgsToCheck = NumArgs;
7139
7140 // Build the full argument list for the method call (the
7141 // implicit object parameter is placed at the beginning of the
7142 // list).
7143 Expr **MethodArgs;
7144 if (NumArgs < NumArgsInProto) {
7145 NumArgsToCheck = NumArgsInProto;
7146 MethodArgs = new Expr*[NumArgsInProto + 1];
7147 } else {
7148 MethodArgs = new Expr*[NumArgs + 1];
7149 }
7150 MethodArgs[0] = Object;
7151 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7152 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007153
7154 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007155 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007156 UsualUnaryConversions(NewFn);
7157
7158 // Once we've built TheCall, all of the expressions are properly
7159 // owned.
7160 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00007161 ExprOwningPtr<CXXOperatorCallExpr>
7162 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007163 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007164 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007165 delete [] MethodArgs;
7166
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007167 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7168 Method))
7169 return true;
7170
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007171 // We may have default arguments. If so, we need to allocate more
7172 // slots in the call for them.
7173 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007174 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007175 else if (NumArgs > NumArgsInProto)
7176 NumArgsToCheck = NumArgsInProto;
7177
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007178 bool IsError = false;
7179
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007180 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007181 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007182 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007183 TheCall->setArg(0, Object);
7184
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007185
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007186 // Check the argument types.
7187 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007188 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007189 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007190 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007191
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007192 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007193
7194 OwningExprResult InputInit
7195 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7196 Method->getParamDecl(i)),
7197 SourceLocation(), Owned(Arg));
7198
7199 IsError |= InputInit.isInvalid();
7200 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007201 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007202 OwningExprResult DefArg
7203 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7204 if (DefArg.isInvalid()) {
7205 IsError = true;
7206 break;
7207 }
7208
7209 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007210 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007211
7212 TheCall->setArg(i + 1, Arg);
7213 }
7214
7215 // If this is a variadic call, handle args passed through "...".
7216 if (Proto->isVariadic()) {
7217 // Promote the arguments (C99 6.5.2.2p7).
7218 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7219 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007220 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007221 TheCall->setArg(i + 1, Arg);
7222 }
7223 }
7224
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007225 if (IsError) return true;
7226
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007227 if (CheckFunctionCall(Method, TheCall.get()))
7228 return true;
7229
Douglas Gregore5e775b2010-04-13 15:50:39 +00007230 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007231}
7232
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007233/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007234/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007235/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007236Sema::OwningExprResult
7237Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7238 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007239 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007240
John McCallbc077cf2010-02-08 23:07:23 +00007241 SourceLocation Loc = Base->getExprLoc();
7242
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007243 // C++ [over.ref]p1:
7244 //
7245 // [...] An expression x->m is interpreted as (x.operator->())->m
7246 // for a class object x of type T if T::operator->() exists and if
7247 // the operator is selected as the best match function by the
7248 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007249 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007250 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007251 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007252
John McCallbc077cf2010-02-08 23:07:23 +00007253 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007254 PDiag(diag::err_typecheck_incomplete_tag)
7255 << Base->getSourceRange()))
7256 return ExprError();
7257
John McCall27b18f82009-11-17 02:14:36 +00007258 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7259 LookupQualifiedName(R, BaseRecord->getDecl());
7260 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007261
7262 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007263 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007264 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007265 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007266 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007267
7268 // Perform overload resolution.
7269 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007270 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007271 case OR_Success:
7272 // Overload resolution succeeded; we'll build the call below.
7273 break;
7274
7275 case OR_No_Viable_Function:
7276 if (CandidateSet.empty())
7277 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007278 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007279 else
7280 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007281 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007282 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007283 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007284
7285 case OR_Ambiguous:
7286 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007287 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007288 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007289 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007290
7291 case OR_Deleted:
7292 Diag(OpLoc, diag::err_ovl_deleted_oper)
7293 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007294 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007295 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007296 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007297 }
7298
John McCalla0296f72010-03-19 07:35:19 +00007299 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007300 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007301
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007302 // Convert the object parameter.
7303 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007304 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7305 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007306 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007307
7308 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007309 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007310
7311 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007312 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7313 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007314 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007315
7316 QualType ResultTy = Method->getResultType().getNonReferenceType();
7317 ExprOwningPtr<CXXOperatorCallExpr>
7318 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7319 &Base, 1, ResultTy, OpLoc));
7320
7321 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7322 Method))
7323 return ExprError();
7324 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007325}
7326
Douglas Gregorcd695e52008-11-10 20:40:00 +00007327/// FixOverloadedFunctionReference - E is an expression that refers to
7328/// a C++ overloaded function (possibly with some parentheses and
7329/// perhaps a '&' around it). We have resolved the overloaded function
7330/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007331/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007332Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007333 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007334 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007335 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7336 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007337 if (SubExpr == PE->getSubExpr())
7338 return PE->Retain();
7339
7340 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7341 }
7342
7343 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007344 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7345 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007346 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007347 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007348 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007349 if (SubExpr == ICE->getSubExpr())
7350 return ICE->Retain();
7351
7352 return new (Context) ImplicitCastExpr(ICE->getType(),
7353 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007354 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007355 ICE->isLvalueCast());
7356 }
7357
7358 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007359 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007360 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007361 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7362 if (Method->isStatic()) {
7363 // Do nothing: static member functions aren't any different
7364 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007365 } else {
John McCalle66edc12009-11-24 19:00:30 +00007366 // Fix the sub expression, which really has to be an
7367 // UnresolvedLookupExpr holding an overloaded member function
7368 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007369 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7370 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007371 if (SubExpr == UnOp->getSubExpr())
7372 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007373
John McCalld14a8642009-11-21 08:51:07 +00007374 assert(isa<DeclRefExpr>(SubExpr)
7375 && "fixed to something other than a decl ref");
7376 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7377 && "fixed to a member ref with no nested name qualifier");
7378
7379 // We have taken the address of a pointer to member
7380 // function. Perform the computation here so that we get the
7381 // appropriate pointer to member type.
7382 QualType ClassType
7383 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7384 QualType MemPtrType
7385 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7386
7387 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7388 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007389 }
7390 }
John McCall16df1e52010-03-30 21:47:33 +00007391 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7392 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007393 if (SubExpr == UnOp->getSubExpr())
7394 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007395
Douglas Gregor51c538b2009-11-20 19:42:02 +00007396 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7397 Context.getPointerType(SubExpr->getType()),
7398 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007399 }
John McCalld14a8642009-11-21 08:51:07 +00007400
7401 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007402 // FIXME: avoid copy.
7403 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007404 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007405 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7406 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007407 }
7408
John McCalld14a8642009-11-21 08:51:07 +00007409 return DeclRefExpr::Create(Context,
7410 ULE->getQualifier(),
7411 ULE->getQualifierRange(),
7412 Fn,
7413 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007414 Fn->getType(),
7415 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007416 }
7417
John McCall10eae182009-11-30 22:42:35 +00007418 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007419 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007420 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7421 if (MemExpr->hasExplicitTemplateArgs()) {
7422 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7423 TemplateArgs = &TemplateArgsBuffer;
7424 }
John McCall6b51f282009-11-23 01:53:49 +00007425
John McCall2d74de92009-12-01 22:10:20 +00007426 Expr *Base;
7427
7428 // If we're filling in
7429 if (MemExpr->isImplicitAccess()) {
7430 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7431 return DeclRefExpr::Create(Context,
7432 MemExpr->getQualifier(),
7433 MemExpr->getQualifierRange(),
7434 Fn,
7435 MemExpr->getMemberLoc(),
7436 Fn->getType(),
7437 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007438 } else {
7439 SourceLocation Loc = MemExpr->getMemberLoc();
7440 if (MemExpr->getQualifier())
7441 Loc = MemExpr->getQualifierRange().getBegin();
7442 Base = new (Context) CXXThisExpr(Loc,
7443 MemExpr->getBaseType(),
7444 /*isImplicit=*/true);
7445 }
John McCall2d74de92009-12-01 22:10:20 +00007446 } else
7447 Base = MemExpr->getBase()->Retain();
7448
7449 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007450 MemExpr->isArrow(),
7451 MemExpr->getQualifier(),
7452 MemExpr->getQualifierRange(),
7453 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007454 Found,
John McCall6b51f282009-11-23 01:53:49 +00007455 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007456 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007457 Fn->getType());
7458 }
7459
Douglas Gregor51c538b2009-11-20 19:42:02 +00007460 assert(false && "Invalid reference to overloaded function");
7461 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007462}
7463
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007464Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007465 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007466 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007467 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007468}
7469
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007470} // end namespace clang