blob: 09adf144503437811b0b8c77d5fba1bf330acb1c [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
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:
John McCall42d7d192010-08-05 09:05:08 +0000318 case Sema::TDK_Underqualified: {
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:
John McCall42d7d192010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified:
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:
John McCall42d7d192010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384 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:
John McCall42d7d192010-08-05 09:05:08 +0000405 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000406 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:
John McCall42d7d192010-08-05 09:05:08 +0000432 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000433 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:
John McCall42d7d192010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor461761d2010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000475// overload of the declarations in Old. This routine returns false if
476// New and Old cannot be overloaded, e.g., if New has the same
477// signature as some function in Old (C++ 1.3.10) or if the Old
478// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000479// it does return false, MatchedDecl will point to the decl that New
480// cannot be overloaded with. This decl may be a UsingShadowDecl on
481// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482//
483// Example: Given the following input:
484//
485// void f(int, float); // #1
486// void f(int, int); // #2
487// int f(int, int); // #3
488//
489// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491//
John McCall3d988d92009-12-02 08:47:38 +0000492// When we process #2, Old contains only the FunctionDecl for #1. By
493// comparing the parameter types, we see that #1 and #2 are overloaded
494// (since they have different signatures), so this routine returns
495// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496//
John McCall3d988d92009-12-02 08:47:38 +0000497// When we process #3, Old is an overload set containing #1 and #2. We
498// compare the signatures of #3 to #1 (they're overloaded, so we do
499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
500// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000503//
504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
505// into a class by a using declaration. The rules for whether to hide
506// shadow declarations ignore some properties which otherwise figure
507// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000513 NamedDecl *OldD = *I;
514
515 bool OldIsUsingDecl = false;
516 if (isa<UsingShadowDecl>(OldD)) {
517 OldIsUsingDecl = true;
518
519 // We can always introduce two using declarations into the same
520 // context, even if they have identical signatures.
521 if (NewIsUsingDecl) continue;
522
523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
524 }
525
526 // If either declaration was introduced by a using declaration,
527 // we'll need to use slightly different rules for matching.
528 // Essentially, these rules are the normal rules, except that
529 // function templates hide function templates with different
530 // return types or template parameter lists.
531 bool UseMemberUsingDeclRules =
532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
533
John McCall3d988d92009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
536 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
538 continue;
539 }
540
John McCalldaa3d6b2009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000543 }
John McCall3d988d92009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
546 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
548 continue;
549 }
550
John McCalldaa3d6b2009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000553 }
John McCall84d87672009-12-10 09:41:52 +0000554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
555 // We can overload with these, which can show up when doing
556 // redeclaration checks for UsingDecls.
557 assert(Old.getLookupKind() == LookupUsingDeclName);
558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
559 // Optimistically assume that an unresolved using decl will
560 // overload; if it doesn't, we'll have to diagnose during
561 // template instantiation.
562 } else {
John McCall1f82f242009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000568 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 }
John McCall1f82f242009-11-18 22:49:29 +0000570
John McCalldaa3d6b2009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000572}
573
John McCalle9cccd82010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000576 // If both of the functions are extern "C", then they are not
577 // overloads.
578 if (Old->isExternC() && New->isExternC())
579 return false;
580
John McCall1f82f242009-11-18 22:49:29 +0000581 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
582 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
583
584 // C++ [temp.fct]p2:
585 // A function template can be overloaded with other function templates
586 // and with normal (non-template) functions.
587 if ((OldTemplate == 0) != (NewTemplate == 0))
588 return true;
589
590 // Is the function New an overload of the function Old?
591 QualType OldQType = Context.getCanonicalType(Old->getType());
592 QualType NewQType = Context.getCanonicalType(New->getType());
593
594 // Compare the signatures (C++ 1.3.10) of the two functions to
595 // determine whether they are overloads. If we find any mismatch
596 // in the signature, they are overloads.
597
598 // If either of these functions is a K&R-style function (no
599 // prototype), then we consider them to have matching signatures.
600 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
601 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
602 return false;
603
604 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
605 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
606
607 // The signature of a function includes the types of its
608 // parameters (C++ 1.3.10), which includes the presence or absence
609 // of the ellipsis; see C++ DR 357).
610 if (OldQType != NewQType &&
611 (OldType->getNumArgs() != NewType->getNumArgs() ||
612 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000613 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000614 return true;
615
616 // C++ [temp.over.link]p4:
617 // The signature of a function template consists of its function
618 // signature, its return type and its template parameter list. The names
619 // of the template parameters are significant only for establishing the
620 // relationship between the template parameters and the rest of the
621 // signature.
622 //
623 // We check the return type and template parameter lists for function
624 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000625 //
626 // However, we don't consider either of these when deciding whether
627 // a member introduced by a shadow declaration is hidden.
628 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000629 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
630 OldTemplate->getTemplateParameters(),
631 false, TPL_TemplateMatch) ||
632 OldType->getResultType() != NewType->getResultType()))
633 return true;
634
635 // If the function is a class member, its signature includes the
636 // cv-qualifiers (if any) on the function itself.
637 //
638 // As part of this, also check whether one of the member functions
639 // is static, in which case they are not overloads (C++
640 // 13.1p2). While not part of the definition of the signature,
641 // this check is important to determine whether these functions
642 // can be overloaded.
643 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
644 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
645 if (OldMethod && NewMethod &&
646 !OldMethod->isStatic() && !NewMethod->isStatic() &&
647 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
648 return true;
649
650 // The signatures match; this is not an overload.
651 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652}
653
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000654/// TryImplicitConversion - Attempt to perform an implicit conversion
655/// from the given expression (Expr) to the given type (ToType). This
656/// function returns an implicit conversion sequence that can be used
657/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658///
659/// void f(float f);
660/// void g(int i) { f(i); }
661///
662/// this routine would produce an implicit conversion sequence to
663/// describe the initialization of f from i, which will be a standard
664/// conversion sequence containing an lvalue-to-rvalue conversion (C++
665/// 4.1) followed by a floating-integral conversion (C++ 4.9).
666//
667/// Note that this routine only determines how the conversion can be
668/// performed; it does not actually perform the conversion. As such,
669/// it will not produce any diagnostics if no conversion is available,
670/// but will instead return an implicit conversion sequence of kind
671/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000672///
673/// If @p SuppressUserConversions, then user-defined conversions are
674/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000675/// If @p AllowExplicit, then explicit user-defined conversions are
676/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000677ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000678Sema::TryImplicitConversion(Expr* From, QualType ToType,
679 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000680 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000681 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000682 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000683 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000684 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000685 return ICS;
686 }
687
688 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000689 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000690 return ICS;
691 }
692
Douglas Gregor836a7e82010-08-11 02:15:33 +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/move
698 // constructor (i.e., a user-defined conversion function) is
699 // called for those cases.
700 QualType FromType = From->getType();
701 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
702 (Context.hasSameUnqualifiedType(FromType, ToType) ||
703 IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000704 ICS.setStandard();
705 ICS.Standard.setAsIdentityConversion();
706 ICS.Standard.setFromType(FromType);
707 ICS.Standard.setAllToTypes(ToType);
708
709 // We don't actually check at this point whether there is a valid
710 // copy/move constructor, since overloading just assumes that it
711 // exists. When we actually perform initialization, we'll find the
712 // appropriate constructor to copy the returned object, if needed.
713 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000714
Douglas Gregor5ab11652010-04-17 22:01:05 +0000715 // Determine whether this is considered a derived-to-base conversion.
716 if (!Context.hasSameUnqualifiedType(FromType, ToType))
717 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000718
719 return ICS;
720 }
721
722 if (SuppressUserConversions) {
723 // We're not in the case above, so there is no conversion that
724 // we can perform.
725 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000726 return ICS;
727 }
728
729 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000730 OverloadCandidateSet Conversions(From->getExprLoc());
731 OverloadingResult UserDefResult
732 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000733 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000734
735 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000736 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000737 // C++ [over.ics.user]p4:
738 // A conversion of an expression of class type to the same class
739 // type is given Exact Match rank, and a conversion of an
740 // expression of class type to a base class of that type is
741 // given Conversion rank, in spite of the fact that a copy
742 // constructor (i.e., a user-defined conversion function) is
743 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000744 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000745 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000746 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000747 = Context.getCanonicalType(From->getType().getUnqualifiedType());
748 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000749 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000750 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000751 // Turn this into a "standard" conversion sequence, so that it
752 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000753 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000754 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000755 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000756 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000757 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000758 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000759 ICS.Standard.Second = ICK_Derived_To_Base;
760 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000761 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000762
763 // C++ [over.best.ics]p4:
764 // However, when considering the argument of a user-defined
765 // conversion function that is a candidate by 13.3.1.3 when
766 // invoked for the copying of the temporary in the second step
767 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
768 // 13.3.1.6 in all cases, only standard conversion sequences and
769 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000770 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000771 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000772 }
John McCalle8c8cd22010-01-13 22:30:33 +0000773 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000774 ICS.setAmbiguous();
775 ICS.Ambiguous.setFromType(From->getType());
776 ICS.Ambiguous.setToType(ToType);
777 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
778 Cand != Conversions.end(); ++Cand)
779 if (Cand->Viable)
780 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000781 } else {
John McCall65eb8792010-02-25 01:37:24 +0000782 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000783 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000784
785 return ICS;
786}
787
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000788/// PerformImplicitConversion - Perform an implicit conversion of the
789/// expression From to the type ToType. Returns true if there was an
790/// error, false otherwise. The expression From is replaced with the
791/// converted expression. Flavor is the kind of conversion we're
792/// performing, used in the error message. If @p AllowExplicit,
793/// explicit user-defined conversions are permitted.
794bool
795Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
796 AssignmentAction Action, bool AllowExplicit) {
797 ImplicitConversionSequence ICS;
798 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
799}
800
801bool
802Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
803 AssignmentAction Action, bool AllowExplicit,
804 ImplicitConversionSequence& ICS) {
805 ICS = TryImplicitConversion(From, ToType,
806 /*SuppressUserConversions=*/false,
807 AllowExplicit,
808 /*InOverloadResolution=*/false);
809 return PerformImplicitConversion(From, ToType, ICS, Action);
810}
811
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000812/// \brief Determine whether the conversion from FromType to ToType is a valid
813/// conversion that strips "noreturn" off the nested function type.
814static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
815 QualType ToType, QualType &ResultTy) {
816 if (Context.hasSameUnqualifiedType(FromType, ToType))
817 return false;
818
819 // Strip the noreturn off the type we're converting from; noreturn can
820 // safely be removed.
821 FromType = Context.getNoReturnType(FromType, false);
822 if (!Context.hasSameUnqualifiedType(FromType, ToType))
823 return false;
824
825 ResultTy = FromType;
826 return true;
827}
Douglas Gregor46188682010-05-18 22:42:18 +0000828
829/// \brief Determine whether the conversion from FromType to ToType is a valid
830/// vector conversion.
831///
832/// \param ICK Will be set to the vector conversion kind, if this is a vector
833/// conversion.
834static bool IsVectorConversion(ASTContext &Context, QualType FromType,
835 QualType ToType, ImplicitConversionKind &ICK) {
836 // We need at least one of these types to be a vector type to have a vector
837 // conversion.
838 if (!ToType->isVectorType() && !FromType->isVectorType())
839 return false;
840
841 // Identical types require no conversions.
842 if (Context.hasSameUnqualifiedType(FromType, ToType))
843 return false;
844
845 // There are no conversions between extended vector types, only identity.
846 if (ToType->isExtVectorType()) {
847 // There are no conversions between extended vector types other than the
848 // identity conversion.
849 if (FromType->isExtVectorType())
850 return false;
851
852 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000853 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000854 ICK = ICK_Vector_Splat;
855 return true;
856 }
857 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000858
859 // We can perform the conversion between vector types in the following cases:
860 // 1)vector types are equivalent AltiVec and GCC vector types
861 // 2)lax vector conversions are permitted and the vector types are of the
862 // same size
863 if (ToType->isVectorType() && FromType->isVectorType()) {
864 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000865 (Context.getLangOptions().LaxVectorConversions &&
866 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000867 ICK = ICK_Vector_Conversion;
868 return true;
869 }
Douglas Gregor46188682010-05-18 22:42:18 +0000870 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000871
Douglas Gregor46188682010-05-18 22:42:18 +0000872 return false;
873}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000874
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000875/// IsStandardConversion - Determines whether there is a standard
876/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
877/// expression From to the type ToType. Standard conversion sequences
878/// only consider non-class types; for conversions that involve class
879/// types, use TryImplicitConversion. If a conversion exists, SCS will
880/// contain the standard conversion sequence required to perform this
881/// conversion and this routine will return true. Otherwise, this
882/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000883bool
884Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000885 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000886 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000887 QualType FromType = From->getType();
888
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000889 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000890 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000891 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000892 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000893 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000894 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000896 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000897 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000898 if (FromType->isRecordType() || ToType->isRecordType()) {
899 if (getLangOptions().CPlusPlus)
900 return false;
901
Mike Stump11289f42009-09-09 15:08:12 +0000902 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000903 }
904
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000905 // The first conversion can be an lvalue-to-rvalue conversion,
906 // array-to-pointer conversion, or function-to-pointer conversion
907 // (C++ 4p1).
908
Douglas Gregor980fb162010-04-29 18:24:40 +0000909 if (FromType == Context.OverloadTy) {
910 DeclAccessPair AccessPair;
911 if (FunctionDecl *Fn
912 = ResolveAddressOfOverloadedFunction(From, ToType, false,
913 AccessPair)) {
914 // We were able to resolve the address of the overloaded function,
915 // so we can convert to the type of that function.
916 FromType = Fn->getType();
917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
918 if (!Method->isStatic()) {
919 Type *ClassType
920 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
921 FromType = Context.getMemberPointerType(FromType, ClassType);
922 }
923 }
924
925 // If the "from" expression takes the address of the overloaded
926 // function, update the type of the resulting expression accordingly.
927 if (FromType->getAs<FunctionType>())
928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
929 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
930 FromType = Context.getPointerType(FromType);
931
932 // Check that we've computed the proper type after overload resolution.
933 assert(Context.hasSameType(FromType,
934 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
935 } else {
936 return false;
937 }
938 }
Mike Stump11289f42009-09-09 15:08:12 +0000939 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000940 // An lvalue (3.10) of a non-function, non-array type T can be
941 // converted to an rvalue.
942 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000943 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000944 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000945 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000946 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947
948 // If T is a non-class type, the type of the rvalue is the
949 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000950 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
951 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000952 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000953 } else if (FromType->isArrayType()) {
954 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000955 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956
957 // An lvalue or rvalue of type "array of N T" or "array of unknown
958 // bound of T" can be converted to an rvalue of type "pointer to
959 // T" (C++ 4.2p1).
960 FromType = Context.getArrayDecayedType(FromType);
961
962 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
963 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000964 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000965
966 // For the purpose of ranking in overload resolution
967 // (13.3.3.1.1), this conversion is considered an
968 // array-to-pointer conversion followed by a qualification
969 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000970 SCS.Second = ICK_Identity;
971 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000972 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000973 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000975 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
976 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000977 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000978
979 // An lvalue of function type T can be converted to an rvalue of
980 // type "pointer to T." The result is a pointer to the
981 // function. (C++ 4.3p1).
982 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000983 } else {
984 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000985 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000986 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000987 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000988
989 // The second conversion can be an integral promotion, floating
990 // point promotion, integral conversion, floating point conversion,
991 // floating-integral conversion, pointer conversion,
992 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000993 // For overloading in C, this can also be a "compatible-type"
994 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000995 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000996 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000997 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998 // The unqualified versions of the types are the same: there's no
999 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001000 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +00001001 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001002 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001003 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001004 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001005 } else if (IsFloatingPointPromotion(FromType, ToType)) {
1006 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001007 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001009 } else if (IsComplexPromotion(FromType, ToType)) {
1010 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Promotion;
1012 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001013 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001014 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001015 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001016 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001017 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001018 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1019 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001020 SCS.Second = ICK_Complex_Conversion;
1021 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001022 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1023 (ToType->isComplexType() && FromType->isArithmeticType())) {
1024 // Complex-real conversions (C99 6.3.1.7)
1025 SCS.Second = ICK_Complex_Real;
1026 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001027 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001028 // Floating point conversions (C++ 4.8).
1029 SCS.Second = ICK_Floating_Conversion;
1030 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001031 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001032 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001033 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001034 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001035 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001036 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001037 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +00001038 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1039 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001040 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001041 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001042 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +00001043 } else if (IsMemberPointerConversion(From, FromType, ToType,
1044 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001045 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001046 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001047 } else if (ToType->isBooleanType() &&
1048 (FromType->isArithmeticType() ||
1049 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001050 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001051 FromType->isBlockPointerType() ||
1052 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001053 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001054 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001055 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001056 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001057 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1058 SCS.Second = SecondICK;
1059 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001060 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001061 Context.typesAreCompatible(ToType, FromType)) {
1062 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001063 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001064 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001065 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1066 // Treat a conversion that strips "noreturn" as an identity conversion.
1067 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068 } else {
1069 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001070 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001072 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001074 QualType CanonFrom;
1075 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001076 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001077 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001078 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001079 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001080 CanonFrom = Context.getCanonicalType(FromType);
1081 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001082 } else {
1083 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001084 SCS.Third = ICK_Identity;
1085
Mike Stump11289f42009-09-09 15:08:12 +00001086 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001087 // [...] Any difference in top-level cv-qualification is
1088 // subsumed by the initialization itself and does not constitute
1089 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001090 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001091 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001092 if (CanonFrom.getLocalUnqualifiedType()
1093 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001094 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1095 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001096 FromType = ToType;
1097 CanonFrom = CanonTo;
1098 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001099 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001100 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001101
1102 // If we have not converted the argument type to the parameter type,
1103 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001104 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001105 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001106
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001107 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001108}
1109
1110/// IsIntegralPromotion - Determines whether the conversion from the
1111/// expression From (whose potentially-adjusted type is FromType) to
1112/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1113/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001114bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001115 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001116 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001117 if (!To) {
1118 return false;
1119 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001120
1121 // An rvalue of type char, signed char, unsigned char, short int, or
1122 // unsigned short int can be converted to an rvalue of type int if
1123 // int can represent all the values of the source type; otherwise,
1124 // the source rvalue can be converted to an rvalue of type unsigned
1125 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001126 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1127 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128 if (// We can promote any signed, promotable integer type to an int
1129 (FromType->isSignedIntegerType() ||
1130 // We can promote any unsigned integer type whose size is
1131 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001132 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001133 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001134 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001135 }
1136
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001137 return To->getKind() == BuiltinType::UInt;
1138 }
1139
1140 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1141 // can be converted to an rvalue of the first of the following types
1142 // that can represent all the values of its underlying type: int,
1143 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001144
1145 // We pre-calculate the promotion type for enum types.
1146 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1147 if (ToType->isIntegerType())
1148 return Context.hasSameUnqualifiedType(ToType,
1149 FromEnumType->getDecl()->getPromotionType());
1150
1151 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 // Determine whether the type we're converting from is signed or
1153 // unsigned.
1154 bool FromIsSigned;
1155 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001156
1157 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1158 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159
1160 // The types we'll try to promote to, in the appropriate
1161 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001162 QualType PromoteTypes[6] = {
1163 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001164 Context.LongTy, Context.UnsignedLongTy ,
1165 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001167 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1169 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001170 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1172 // We found the type that we can promote to. If this is the
1173 // type we wanted, we have a promotion. Otherwise, no
1174 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001175 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001176 }
1177 }
1178 }
1179
1180 // An rvalue for an integral bit-field (9.6) can be converted to an
1181 // rvalue of type int if int can represent all the values of the
1182 // bit-field; otherwise, it can be converted to unsigned int if
1183 // unsigned int can represent all the values of the bit-field. If
1184 // the bit-field is larger yet, no integral promotion applies to
1185 // it. If the bit-field has an enumerated type, it is treated as any
1186 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001187 // FIXME: We should delay checking of bit-fields until we actually perform the
1188 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001189 using llvm::APSInt;
1190 if (From)
1191 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001192 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001193 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001194 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1195 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1196 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001197
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001198 // Are we promoting to an int from a bitfield that fits in an int?
1199 if (BitWidth < ToSize ||
1200 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1201 return To->getKind() == BuiltinType::Int;
1202 }
Mike Stump11289f42009-09-09 15:08:12 +00001203
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001204 // Are we promoting to an unsigned int from an unsigned bitfield
1205 // that fits into an unsigned int?
1206 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1207 return To->getKind() == BuiltinType::UInt;
1208 }
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001210 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001211 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001212 }
Mike Stump11289f42009-09-09 15:08:12 +00001213
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001214 // An rvalue of type bool can be converted to an rvalue of type int,
1215 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001216 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001218 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001219
1220 return false;
1221}
1222
1223/// IsFloatingPointPromotion - Determines whether the conversion from
1224/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1225/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001226bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001227 /// An rvalue of type float can be converted to an rvalue of type
1228 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001229 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1230 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231 if (FromBuiltin->getKind() == BuiltinType::Float &&
1232 ToBuiltin->getKind() == BuiltinType::Double)
1233 return true;
1234
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001235 // C99 6.3.1.5p1:
1236 // When a float is promoted to double or long double, or a
1237 // double is promoted to long double [...].
1238 if (!getLangOptions().CPlusPlus &&
1239 (FromBuiltin->getKind() == BuiltinType::Float ||
1240 FromBuiltin->getKind() == BuiltinType::Double) &&
1241 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1242 return true;
1243 }
1244
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001245 return false;
1246}
1247
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001248/// \brief Determine if a conversion is a complex promotion.
1249///
1250/// A complex promotion is defined as a complex -> complex conversion
1251/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001252/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001253bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001254 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001255 if (!FromComplex)
1256 return false;
1257
John McCall9dd450b2009-09-21 23:43:11 +00001258 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001259 if (!ToComplex)
1260 return false;
1261
1262 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001263 ToComplex->getElementType()) ||
1264 IsIntegralPromotion(0, FromComplex->getElementType(),
1265 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001266}
1267
Douglas Gregor237f96c2008-11-26 23:31:11 +00001268/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1269/// the pointer type FromPtr to a pointer to type ToPointee, with the
1270/// same type qualifiers as FromPtr has on its pointee type. ToType,
1271/// if non-empty, will be a pointer to ToType that may or may not have
1272/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001273static QualType
1274BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001275 QualType ToPointee, QualType ToType,
1276 ASTContext &Context) {
1277 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1278 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001279 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001280
1281 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001282 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001283 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001284 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001285 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001286
1287 // Build a pointer to ToPointee. It has the right qualifiers
1288 // already.
1289 return Context.getPointerType(ToPointee);
1290 }
1291
1292 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001293 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001294 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1295 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001296}
1297
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001298/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1299/// the FromType, which is an objective-c pointer, to ToType, which may or may
1300/// not have the right set of qualifiers.
1301static QualType
1302BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1303 QualType ToType,
1304 ASTContext &Context) {
1305 QualType CanonFromType = Context.getCanonicalType(FromType);
1306 QualType CanonToType = Context.getCanonicalType(ToType);
1307 Qualifiers Quals = CanonFromType.getQualifiers();
1308
1309 // Exact qualifier match -> return the pointer type we're converting to.
1310 if (CanonToType.getLocalQualifiers() == Quals)
1311 return ToType;
1312
1313 // Just build a canonical type that has the right qualifiers.
1314 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1315}
1316
Mike Stump11289f42009-09-09 15:08:12 +00001317static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001318 bool InOverloadResolution,
1319 ASTContext &Context) {
1320 // Handle value-dependent integral null pointer constants correctly.
1321 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1322 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001323 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001324 return !InOverloadResolution;
1325
Douglas Gregor56751b52009-09-25 04:25:58 +00001326 return Expr->isNullPointerConstant(Context,
1327 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1328 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001329}
Mike Stump11289f42009-09-09 15:08:12 +00001330
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001331/// IsPointerConversion - Determines whether the conversion of the
1332/// expression From, which has the (possibly adjusted) type FromType,
1333/// can be converted to the type ToType via a pointer conversion (C++
1334/// 4.10). If so, returns true and places the converted type (that
1335/// might differ from ToType in its cv-qualifiers at some level) into
1336/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001337///
Douglas Gregora29dc052008-11-27 01:19:21 +00001338/// This routine also supports conversions to and from block pointers
1339/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1340/// pointers to interfaces. FIXME: Once we've determined the
1341/// appropriate overloading rules for Objective-C, we may want to
1342/// split the Objective-C checks into a different routine; however,
1343/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001344/// conversions, so for now they live here. IncompatibleObjC will be
1345/// set if the conversion is an allowed Objective-C conversion that
1346/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001347bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001348 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001349 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001350 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001351 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001352 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1353 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001354
Mike Stump11289f42009-09-09 15:08:12 +00001355 // Conversion from a null pointer constant to any Objective-C pointer type.
1356 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001357 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001358 ConvertedType = ToType;
1359 return true;
1360 }
1361
Douglas Gregor231d1c62008-11-27 00:15:41 +00001362 // Blocks: Block pointers can be converted to void*.
1363 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001364 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001365 ConvertedType = ToType;
1366 return true;
1367 }
1368 // Blocks: A null pointer constant can be converted to a block
1369 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001370 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001372 ConvertedType = ToType;
1373 return true;
1374 }
1375
Sebastian Redl576fd422009-05-10 18:38:11 +00001376 // If the left-hand-side is nullptr_t, the right side can be a null
1377 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001378 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001379 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001380 ConvertedType = ToType;
1381 return true;
1382 }
1383
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001384 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001385 if (!ToTypePtr)
1386 return false;
1387
1388 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001389 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001390 ConvertedType = ToType;
1391 return true;
1392 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001393
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001394 // Beyond this point, both types need to be pointers
1395 // , including objective-c pointers.
1396 QualType ToPointeeType = ToTypePtr->getPointeeType();
1397 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1398 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1399 ToType, Context);
1400 return true;
1401
1402 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001403 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001404 if (!FromTypePtr)
1405 return false;
1406
1407 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001408
Douglas Gregorfb640862010-08-18 21:25:30 +00001409 // If the unqualified pointee types are the same, this can't be a
1410 // pointer conversion, so don't do all of the work below.
1411 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1412 return false;
1413
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001414 // An rvalue of type "pointer to cv T," where T is an object type,
1415 // can be converted to an rvalue of type "pointer to cv void" (C++
1416 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001417 if (FromPointeeType->isIncompleteOrObjectType() &&
1418 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001419 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001420 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001421 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001422 return true;
1423 }
1424
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001425 // When we're overloading in C, we allow a special kind of pointer
1426 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001427 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001428 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001429 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001430 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001431 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001432 return true;
1433 }
1434
Douglas Gregor5c407d92008-10-23 00:40:37 +00001435 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001436 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001437 // An rvalue of type "pointer to cv D," where D is a class type,
1438 // can be converted to an rvalue of type "pointer to cv B," where
1439 // B is a base class (clause 10) of D. If B is an inaccessible
1440 // (clause 11) or ambiguous (10.2) base class of D, a program that
1441 // necessitates this conversion is ill-formed. The result of the
1442 // conversion is a pointer to the base class sub-object of the
1443 // derived class object. The null pointer value is converted to
1444 // the null pointer value of the destination type.
1445 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001446 // Note that we do not check for ambiguity or inaccessibility
1447 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001448 if (getLangOptions().CPlusPlus &&
1449 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001450 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001451 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001452 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001453 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001454 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001455 ToType, Context);
1456 return true;
1457 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001458
Douglas Gregora119f102008-12-19 19:13:09 +00001459 return false;
1460}
1461
1462/// isObjCPointerConversion - Determines whether this is an
1463/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1464/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001465bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001466 QualType& ConvertedType,
1467 bool &IncompatibleObjC) {
1468 if (!getLangOptions().ObjC1)
1469 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001470
Steve Naroff7cae42b2009-07-10 23:34:53 +00001471 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001472 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001473 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001474 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001475
Steve Naroff7cae42b2009-07-10 23:34:53 +00001476 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001477 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001478 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001479 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001480 ConvertedType = ToType;
1481 return true;
1482 }
1483 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001484 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001485 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001486 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001487 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001488 ConvertedType = ToType;
1489 return true;
1490 }
1491 // Objective C++: We're able to convert from a pointer to an
1492 // interface to a pointer to a different interface.
1493 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001494 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1495 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1496 if (getLangOptions().CPlusPlus && LHS && RHS &&
1497 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1498 FromObjCPtr->getPointeeType()))
1499 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001500 ConvertedType = ToType;
1501 return true;
1502 }
1503
1504 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1505 // Okay: this is some kind of implicit downcast of Objective-C
1506 // interfaces, which is permitted. However, we're going to
1507 // complain about it.
1508 IncompatibleObjC = true;
1509 ConvertedType = FromType;
1510 return true;
1511 }
Mike Stump11289f42009-09-09 15:08:12 +00001512 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001513 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001514 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001515 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001516 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001517 else if (const BlockPointerType *ToBlockPtr =
1518 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001519 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001520 // to a block pointer type.
1521 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1522 ConvertedType = ToType;
1523 return true;
1524 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001525 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001526 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001527 else if (FromType->getAs<BlockPointerType>() &&
1528 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1529 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001530 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001531 ConvertedType = ToType;
1532 return true;
1533 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001534 else
Douglas Gregora119f102008-12-19 19:13:09 +00001535 return false;
1536
Douglas Gregor033f56d2008-12-23 00:53:59 +00001537 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001538 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001539 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001540 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001541 FromPointeeType = FromBlockPtr->getPointeeType();
1542 else
Douglas Gregora119f102008-12-19 19:13:09 +00001543 return false;
1544
Douglas Gregora119f102008-12-19 19:13:09 +00001545 // If we have pointers to pointers, recursively check whether this
1546 // is an Objective-C conversion.
1547 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1548 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1549 IncompatibleObjC)) {
1550 // We always complain about this conversion.
1551 IncompatibleObjC = true;
1552 ConvertedType = ToType;
1553 return true;
1554 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001555 // Allow conversion of pointee being objective-c pointer to another one;
1556 // as in I* to id.
1557 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1558 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1559 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1560 IncompatibleObjC)) {
1561 ConvertedType = ToType;
1562 return true;
1563 }
1564
Douglas Gregor033f56d2008-12-23 00:53:59 +00001565 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001566 // differences in the argument and result types are in Objective-C
1567 // pointer conversions. If so, we permit the conversion (but
1568 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001569 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001570 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001571 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001572 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001573 if (FromFunctionType && ToFunctionType) {
1574 // If the function types are exactly the same, this isn't an
1575 // Objective-C pointer conversion.
1576 if (Context.getCanonicalType(FromPointeeType)
1577 == Context.getCanonicalType(ToPointeeType))
1578 return false;
1579
1580 // Perform the quick checks that will tell us whether these
1581 // function types are obviously different.
1582 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1583 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1584 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1585 return false;
1586
1587 bool HasObjCConversion = false;
1588 if (Context.getCanonicalType(FromFunctionType->getResultType())
1589 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1590 // Okay, the types match exactly. Nothing to do.
1591 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1592 ToFunctionType->getResultType(),
1593 ConvertedType, IncompatibleObjC)) {
1594 // Okay, we have an Objective-C pointer conversion.
1595 HasObjCConversion = true;
1596 } else {
1597 // Function types are too different. Abort.
1598 return false;
1599 }
Mike Stump11289f42009-09-09 15:08:12 +00001600
Douglas Gregora119f102008-12-19 19:13:09 +00001601 // Check argument types.
1602 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1603 ArgIdx != NumArgs; ++ArgIdx) {
1604 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1605 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1606 if (Context.getCanonicalType(FromArgType)
1607 == Context.getCanonicalType(ToArgType)) {
1608 // Okay, the types match exactly. Nothing to do.
1609 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1610 ConvertedType, IncompatibleObjC)) {
1611 // Okay, we have an Objective-C pointer conversion.
1612 HasObjCConversion = true;
1613 } else {
1614 // Argument types are too different. Abort.
1615 return false;
1616 }
1617 }
1618
1619 if (HasObjCConversion) {
1620 // We had an Objective-C conversion. Allow this pointer
1621 // conversion, but complain about it.
1622 ConvertedType = ToType;
1623 IncompatibleObjC = true;
1624 return true;
1625 }
1626 }
1627
Sebastian Redl72b597d2009-01-25 19:43:20 +00001628 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001630
1631/// FunctionArgTypesAreEqual - This routine checks two function proto types
1632/// for equlity of their argument types. Caller has already checked that
1633/// they have same number of arguments. This routine assumes that Objective-C
1634/// pointer types which only differ in their protocol qualifiers are equal.
1635bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1636 FunctionProtoType* NewType){
1637 if (!getLangOptions().ObjC1)
1638 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1639 NewType->arg_type_begin());
1640
1641 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1642 N = NewType->arg_type_begin(),
1643 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1644 QualType ToType = (*O);
1645 QualType FromType = (*N);
1646 if (ToType != FromType) {
1647 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1648 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001649 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1650 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1651 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1652 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001653 continue;
1654 }
John McCall8b07ec22010-05-15 11:32:37 +00001655 else if (const ObjCObjectPointerType *PTTo =
1656 ToType->getAs<ObjCObjectPointerType>()) {
1657 if (const ObjCObjectPointerType *PTFr =
1658 FromType->getAs<ObjCObjectPointerType>())
1659 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1660 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001661 }
1662 return false;
1663 }
1664 }
1665 return true;
1666}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667
Douglas Gregor39c16d42008-10-24 04:54:22 +00001668/// CheckPointerConversion - Check the pointer conversion from the
1669/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001670/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001671/// conversions for which IsPointerConversion has already returned
1672/// true. It returns true and produces a diagnostic if there was an
1673/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001674bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001675 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001676 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001677 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001678 QualType FromType = From->getType();
1679
Douglas Gregor4038cf42010-06-08 17:35:15 +00001680 if (CXXBoolLiteralExpr* LitBool
1681 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1682 if (LitBool->getValue() == false)
1683 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1684 << ToType;
1685
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001686 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1687 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001688 QualType FromPointeeType = FromPtrType->getPointeeType(),
1689 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001690
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001691 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1692 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001693 // We must have a derived-to-base conversion. Check an
1694 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001695 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1696 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001697 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001698 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001699 return true;
1700
1701 // The conversion was successful.
1702 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001703 }
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001706 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001707 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001708 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001709 // Objective-C++ conversions are always okay.
1710 // FIXME: We should have a different class of conversions for the
1711 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001712 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001713 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001714
Steve Naroff7cae42b2009-07-10 23:34:53 +00001715 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001716 return false;
1717}
1718
Sebastian Redl72b597d2009-01-25 19:43:20 +00001719/// IsMemberPointerConversion - Determines whether the conversion of the
1720/// expression From, which has the (possibly adjusted) type FromType, can be
1721/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1722/// If so, returns true and places the converted type (that might differ from
1723/// ToType in its cv-qualifiers at some level) into ConvertedType.
1724bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001725 QualType ToType,
1726 bool InOverloadResolution,
1727 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001728 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001729 if (!ToTypePtr)
1730 return false;
1731
1732 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001733 if (From->isNullPointerConstant(Context,
1734 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1735 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001736 ConvertedType = ToType;
1737 return true;
1738 }
1739
1740 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001741 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001742 if (!FromTypePtr)
1743 return false;
1744
1745 // A pointer to member of B can be converted to a pointer to member of D,
1746 // where D is derived from B (C++ 4.11p2).
1747 QualType FromClass(FromTypePtr->getClass(), 0);
1748 QualType ToClass(ToTypePtr->getClass(), 0);
1749 // FIXME: What happens when these are dependent? Is this function even called?
1750
1751 if (IsDerivedFrom(ToClass, FromClass)) {
1752 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1753 ToClass.getTypePtr());
1754 return true;
1755 }
1756
1757 return false;
1758}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001759
Sebastian Redl72b597d2009-01-25 19:43:20 +00001760/// CheckMemberPointerConversion - Check the member pointer conversion from the
1761/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001762/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001763/// for which IsMemberPointerConversion has already returned true. It returns
1764/// true and produces a diagnostic if there was an error, or returns false
1765/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001766bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001767 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001768 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001769 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001770 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001771 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001772 if (!FromPtrType) {
1773 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001774 assert(From->isNullPointerConstant(Context,
1775 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001776 "Expr must be null pointer constant!");
1777 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001778 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001779 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001780
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001781 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001782 assert(ToPtrType && "No member pointer cast has a target type "
1783 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001784
Sebastian Redled8f2002009-01-28 18:33:18 +00001785 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1786 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001787
Sebastian Redled8f2002009-01-28 18:33:18 +00001788 // FIXME: What about dependent types?
1789 assert(FromClass->isRecordType() && "Pointer into non-class.");
1790 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001791
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001792 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001793 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001794 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1795 assert(DerivationOkay &&
1796 "Should not have been called if derivation isn't OK.");
1797 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001798
Sebastian Redled8f2002009-01-28 18:33:18 +00001799 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1800 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1802 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1803 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1804 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001805 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001806
Douglas Gregor89ee6822009-02-28 01:32:25 +00001807 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001808 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1809 << FromClass << ToClass << QualType(VBase, 0)
1810 << From->getSourceRange();
1811 return true;
1812 }
1813
John McCall5b0829a2010-02-10 09:31:12 +00001814 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001815 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1816 Paths.front(),
1817 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001818
Anders Carlssond7923c62009-08-22 23:33:40 +00001819 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001820 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001821 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001822 return false;
1823}
1824
Douglas Gregor9a657932008-10-21 23:43:52 +00001825/// IsQualificationConversion - Determines whether the conversion from
1826/// an rvalue of type FromType to ToType is a qualification conversion
1827/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001828bool
1829Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001830 FromType = Context.getCanonicalType(FromType);
1831 ToType = Context.getCanonicalType(ToType);
1832
1833 // If FromType and ToType are the same type, this is not a
1834 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001835 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001836 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001837
Douglas Gregor9a657932008-10-21 23:43:52 +00001838 // (C++ 4.4p4):
1839 // A conversion can add cv-qualifiers at levels other than the first
1840 // in multi-level pointers, subject to the following rules: [...]
1841 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001842 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001843 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001844 // Within each iteration of the loop, we check the qualifiers to
1845 // determine if this still looks like a qualification
1846 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001847 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001848 // until there are no more pointers or pointers-to-members left to
1849 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001850 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001851
1852 // -- for every j > 0, if const is in cv 1,j then const is in cv
1853 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001854 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001855 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001856
Douglas Gregor9a657932008-10-21 23:43:52 +00001857 // -- if the cv 1,j and cv 2,j are different, then const is in
1858 // every cv for 0 < k < j.
1859 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001860 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001861 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001862
Douglas Gregor9a657932008-10-21 23:43:52 +00001863 // Keep track of whether all prior cv-qualifiers in the "to" type
1864 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001865 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001866 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001867 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001868
1869 // We are left with FromType and ToType being the pointee types
1870 // after unwrapping the original FromType and ToType the same number
1871 // of types. If we unwrapped any pointers, and if FromType and
1872 // ToType have the same unqualified type (since we checked
1873 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001874 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001875}
1876
Douglas Gregor576e98c2009-01-30 23:27:23 +00001877/// Determines whether there is a user-defined conversion sequence
1878/// (C++ [over.ics.user]) that converts expression From to the type
1879/// ToType. If such a conversion exists, User will contain the
1880/// user-defined conversion sequence that performs such a conversion
1881/// and this routine will return true. Otherwise, this routine returns
1882/// false and User is unspecified.
1883///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001884/// \param AllowExplicit true if the conversion should consider C++0x
1885/// "explicit" conversion functions as well as non-explicit conversion
1886/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001887OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1888 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001889 OverloadCandidateSet& CandidateSet,
1890 bool AllowExplicit) {
1891 // Whether we will only visit constructors.
1892 bool ConstructorsOnly = false;
1893
1894 // If the type we are conversion to is a class type, enumerate its
1895 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001896 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001897 // C++ [over.match.ctor]p1:
1898 // When objects of class type are direct-initialized (8.5), or
1899 // copy-initialized from an expression of the same or a
1900 // derived class type (8.5), overload resolution selects the
1901 // constructor. [...] For copy-initialization, the candidate
1902 // functions are all the converting constructors (12.3.1) of
1903 // that class. The argument list is the expression-list within
1904 // the parentheses of the initializer.
1905 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1906 (From->getType()->getAs<RecordType>() &&
1907 IsDerivedFrom(From->getType(), ToType)))
1908 ConstructorsOnly = true;
1909
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001910 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1911 // We're not going to find any constructors.
1912 } else if (CXXRecordDecl *ToRecordDecl
1913 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001914 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00001915 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001916 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001917 NamedDecl *D = *Con;
1918 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1919
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001920 // Find the constructor (which may be a template).
1921 CXXConstructorDecl *Constructor = 0;
1922 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001923 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001924 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001925 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001926 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1927 else
John McCalla0296f72010-03-19 07:35:19 +00001928 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001929
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001930 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001931 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001932 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001933 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001934 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001935 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001936 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001937 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001938 // Allow one user-defined conversion when user specifies a
1939 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001940 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001941 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001942 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001943 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001944 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001945 }
1946 }
1947
Douglas Gregor5ab11652010-04-17 22:01:05 +00001948 // Enumerate conversion functions, if we're allowed to.
1949 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001950 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001951 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001952 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001953 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001954 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001955 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001956 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1957 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001958 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001959 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001960 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001961 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001962 DeclAccessPair FoundDecl = I.getPair();
1963 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001964 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1965 if (isa<UsingShadowDecl>(D))
1966 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1967
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001968 CXXConversionDecl *Conv;
1969 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001970 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1971 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001972 else
John McCallda4458e2010-03-31 01:36:47 +00001973 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001974
1975 if (AllowExplicit || !Conv->isExplicit()) {
1976 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001977 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001978 ActingContext, From, ToType,
1979 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001980 else
John McCalla0296f72010-03-19 07:35:19 +00001981 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001982 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001983 }
1984 }
1985 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001986 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001987
1988 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001989 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001990 case OR_Success:
1991 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001992 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001993 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1994 // C++ [over.ics.user]p1:
1995 // If the user-defined conversion is specified by a
1996 // constructor (12.3.1), the initial standard conversion
1997 // sequence converts the source type to the type required by
1998 // the argument of the constructor.
1999 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002000 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00002001 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00002002 User.EllipsisConversion = true;
2003 else {
2004 User.Before = Best->Conversions[0].Standard;
2005 User.EllipsisConversion = false;
2006 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002007 User.ConversionFunction = Constructor;
2008 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002009 User.After.setFromType(
2010 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002011 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002012 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002013 } else if (CXXConversionDecl *Conversion
2014 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2015 // C++ [over.ics.user]p1:
2016 //
2017 // [...] If the user-defined conversion is specified by a
2018 // conversion function (12.3.2), the initial standard
2019 // conversion sequence converts the source type to the
2020 // implicit object parameter of the conversion function.
2021 User.Before = Best->Conversions[0].Standard;
2022 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002023 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002024
2025 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002026 // The second standard conversion sequence converts the
2027 // result of the user-defined conversion to the target type
2028 // for the sequence. Since an implicit conversion sequence
2029 // is an initialization, the special rules for
2030 // initialization by user-defined conversion apply when
2031 // selecting the best user-defined conversion for a
2032 // user-defined conversion sequence (see 13.3.3 and
2033 // 13.3.3.1).
2034 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002035 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002036 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002037 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002038 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002039 }
Mike Stump11289f42009-09-09 15:08:12 +00002040
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002041 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002042 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002043 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002044 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002045 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002046
2047 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002048 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002049 }
2050
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002051 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002052}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002053
2054bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002055Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002056 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002057 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002058 OverloadingResult OvResult =
2059 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002060 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002061 if (OvResult == OR_Ambiguous)
2062 Diag(From->getSourceRange().getBegin(),
2063 diag::err_typecheck_ambiguous_condition)
2064 << From->getType() << ToType << From->getSourceRange();
2065 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2066 Diag(From->getSourceRange().getBegin(),
2067 diag::err_typecheck_nonviable_condition)
2068 << From->getType() << ToType << From->getSourceRange();
2069 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002070 return false;
John McCallad907772010-01-12 07:18:19 +00002071 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002072 return true;
2073}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002074
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002075/// CompareImplicitConversionSequences - Compare two implicit
2076/// conversion sequences to determine whether one is better than the
2077/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002078ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002079Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2080 const ImplicitConversionSequence& ICS2)
2081{
2082 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2083 // conversion sequences (as defined in 13.3.3.1)
2084 // -- a standard conversion sequence (13.3.3.1.1) is a better
2085 // conversion sequence than a user-defined conversion sequence or
2086 // an ellipsis conversion sequence, and
2087 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2088 // conversion sequence than an ellipsis conversion sequence
2089 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002090 //
John McCall0d1da222010-01-12 00:44:57 +00002091 // C++0x [over.best.ics]p10:
2092 // For the purpose of ranking implicit conversion sequences as
2093 // described in 13.3.3.2, the ambiguous conversion sequence is
2094 // treated as a user-defined sequence that is indistinguishable
2095 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002096 if (ICS1.getKindRank() < ICS2.getKindRank())
2097 return ImplicitConversionSequence::Better;
2098 else if (ICS2.getKindRank() < ICS1.getKindRank())
2099 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002100
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002101 // The following checks require both conversion sequences to be of
2102 // the same kind.
2103 if (ICS1.getKind() != ICS2.getKind())
2104 return ImplicitConversionSequence::Indistinguishable;
2105
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002106 // Two implicit conversion sequences of the same form are
2107 // indistinguishable conversion sequences unless one of the
2108 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002109 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002110 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002111 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002112 // User-defined conversion sequence U1 is a better conversion
2113 // sequence than another user-defined conversion sequence U2 if
2114 // they contain the same user-defined conversion function or
2115 // constructor and if the second standard conversion sequence of
2116 // U1 is better than the second standard conversion sequence of
2117 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002118 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002119 ICS2.UserDefined.ConversionFunction)
2120 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2121 ICS2.UserDefined.After);
2122 }
2123
2124 return ImplicitConversionSequence::Indistinguishable;
2125}
2126
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002127static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2128 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2129 Qualifiers Quals;
2130 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2131 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2132 }
2133
2134 return Context.hasSameUnqualifiedType(T1, T2);
2135}
2136
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002137// Per 13.3.3.2p3, compare the given standard conversion sequences to
2138// determine if one is a proper subset of the other.
2139static ImplicitConversionSequence::CompareKind
2140compareStandardConversionSubsets(ASTContext &Context,
2141 const StandardConversionSequence& SCS1,
2142 const StandardConversionSequence& SCS2) {
2143 ImplicitConversionSequence::CompareKind Result
2144 = ImplicitConversionSequence::Indistinguishable;
2145
Douglas Gregore87561a2010-05-23 22:10:15 +00002146 // the identity conversion sequence is considered to be a subsequence of
2147 // any non-identity conversion sequence
2148 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2149 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2150 return ImplicitConversionSequence::Better;
2151 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2152 return ImplicitConversionSequence::Worse;
2153 }
2154
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002155 if (SCS1.Second != SCS2.Second) {
2156 if (SCS1.Second == ICK_Identity)
2157 Result = ImplicitConversionSequence::Better;
2158 else if (SCS2.Second == ICK_Identity)
2159 Result = ImplicitConversionSequence::Worse;
2160 else
2161 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002162 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002163 return ImplicitConversionSequence::Indistinguishable;
2164
2165 if (SCS1.Third == SCS2.Third) {
2166 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2167 : ImplicitConversionSequence::Indistinguishable;
2168 }
2169
2170 if (SCS1.Third == ICK_Identity)
2171 return Result == ImplicitConversionSequence::Worse
2172 ? ImplicitConversionSequence::Indistinguishable
2173 : ImplicitConversionSequence::Better;
2174
2175 if (SCS2.Third == ICK_Identity)
2176 return Result == ImplicitConversionSequence::Better
2177 ? ImplicitConversionSequence::Indistinguishable
2178 : ImplicitConversionSequence::Worse;
2179
2180 return ImplicitConversionSequence::Indistinguishable;
2181}
2182
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002183/// CompareStandardConversionSequences - Compare two standard
2184/// conversion sequences to determine whether one is better than the
2185/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002186ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2188 const StandardConversionSequence& SCS2)
2189{
2190 // Standard conversion sequence S1 is a better conversion sequence
2191 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2192
2193 // -- S1 is a proper subsequence of S2 (comparing the conversion
2194 // sequences in the canonical form defined by 13.3.3.1.1,
2195 // excluding any Lvalue Transformation; the identity conversion
2196 // sequence is considered to be a subsequence of any
2197 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002198 if (ImplicitConversionSequence::CompareKind CK
2199 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2200 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002201
2202 // -- the rank of S1 is better than the rank of S2 (by the rules
2203 // defined below), or, if not that,
2204 ImplicitConversionRank Rank1 = SCS1.getRank();
2205 ImplicitConversionRank Rank2 = SCS2.getRank();
2206 if (Rank1 < Rank2)
2207 return ImplicitConversionSequence::Better;
2208 else if (Rank2 < Rank1)
2209 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002210
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002211 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2212 // are indistinguishable unless one of the following rules
2213 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002214
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002215 // A conversion that is not a conversion of a pointer, or
2216 // pointer to member, to bool is better than another conversion
2217 // that is such a conversion.
2218 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2219 return SCS2.isPointerConversionToBool()
2220 ? ImplicitConversionSequence::Better
2221 : ImplicitConversionSequence::Worse;
2222
Douglas Gregor5c407d92008-10-23 00:40:37 +00002223 // C++ [over.ics.rank]p4b2:
2224 //
2225 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002226 // conversion of B* to A* is better than conversion of B* to
2227 // void*, and conversion of A* to void* is better than conversion
2228 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002229 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002230 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002231 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002232 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002233 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2234 // Exactly one of the conversion sequences is a conversion to
2235 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002236 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2237 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002238 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2239 // Neither conversion sequence converts to a void pointer; compare
2240 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002241 if (ImplicitConversionSequence::CompareKind DerivedCK
2242 = CompareDerivedToBaseConversions(SCS1, SCS2))
2243 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002244 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2245 // Both conversion sequences are conversions to void
2246 // pointers. Compare the source types to determine if there's an
2247 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002248 QualType FromType1 = SCS1.getFromType();
2249 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002250
2251 // Adjust the types we're converting from via the array-to-pointer
2252 // conversion, if we need to.
2253 if (SCS1.First == ICK_Array_To_Pointer)
2254 FromType1 = Context.getArrayDecayedType(FromType1);
2255 if (SCS2.First == ICK_Array_To_Pointer)
2256 FromType2 = Context.getArrayDecayedType(FromType2);
2257
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002258 QualType FromPointee1
2259 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2260 QualType FromPointee2
2261 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002262
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002263 if (IsDerivedFrom(FromPointee2, FromPointee1))
2264 return ImplicitConversionSequence::Better;
2265 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2266 return ImplicitConversionSequence::Worse;
2267
2268 // Objective-C++: If one interface is more specific than the
2269 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002270 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2271 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002272 if (FromIface1 && FromIface1) {
2273 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2274 return ImplicitConversionSequence::Better;
2275 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2276 return ImplicitConversionSequence::Worse;
2277 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002278 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002279
2280 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2281 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002282 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002283 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002284 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002285
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002286 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002287 // C++0x [over.ics.rank]p3b4:
2288 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2289 // implicit object parameter of a non-static member function declared
2290 // without a ref-qualifier, and S1 binds an rvalue reference to an
2291 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002292 // FIXME: We don't know if we're dealing with the implicit object parameter,
2293 // or if the member function in this case has a ref qualifier.
2294 // (Of course, we don't have ref qualifiers yet.)
2295 if (SCS1.RRefBinding != SCS2.RRefBinding)
2296 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2297 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002298
2299 // C++ [over.ics.rank]p3b4:
2300 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2301 // which the references refer are the same type except for
2302 // top-level cv-qualifiers, and the type to which the reference
2303 // initialized by S2 refers is more cv-qualified than the type
2304 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002305 QualType T1 = SCS1.getToType(2);
2306 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002307 T1 = Context.getCanonicalType(T1);
2308 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002309 Qualifiers T1Quals, T2Quals;
2310 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2311 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2312 if (UnqualT1 == UnqualT2) {
2313 // If the type is an array type, promote the element qualifiers to the type
2314 // for comparison.
2315 if (isa<ArrayType>(T1) && T1Quals)
2316 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2317 if (isa<ArrayType>(T2) && T2Quals)
2318 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002319 if (T2.isMoreQualifiedThan(T1))
2320 return ImplicitConversionSequence::Better;
2321 else if (T1.isMoreQualifiedThan(T2))
2322 return ImplicitConversionSequence::Worse;
2323 }
2324 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002325
2326 return ImplicitConversionSequence::Indistinguishable;
2327}
2328
2329/// CompareQualificationConversions - Compares two standard conversion
2330/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002331/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2332ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002333Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002334 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002335 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002336 // -- S1 and S2 differ only in their qualification conversion and
2337 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2338 // cv-qualification signature of type T1 is a proper subset of
2339 // the cv-qualification signature of type T2, and S1 is not the
2340 // deprecated string literal array-to-pointer conversion (4.2).
2341 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2342 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2343 return ImplicitConversionSequence::Indistinguishable;
2344
2345 // FIXME: the example in the standard doesn't use a qualification
2346 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002347 QualType T1 = SCS1.getToType(2);
2348 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002349 T1 = Context.getCanonicalType(T1);
2350 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002351 Qualifiers T1Quals, T2Quals;
2352 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2353 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002354
2355 // If the types are the same, we won't learn anything by unwrapped
2356 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002357 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002358 return ImplicitConversionSequence::Indistinguishable;
2359
Chandler Carruth607f38e2009-12-29 07:16:59 +00002360 // If the type is an array type, promote the element qualifiers to the type
2361 // for comparison.
2362 if (isa<ArrayType>(T1) && T1Quals)
2363 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2364 if (isa<ArrayType>(T2) && T2Quals)
2365 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2366
Mike Stump11289f42009-09-09 15:08:12 +00002367 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002368 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002369 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002370 // Within each iteration of the loop, we check the qualifiers to
2371 // determine if this still looks like a qualification
2372 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002373 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002374 // until there are no more pointers or pointers-to-members left
2375 // to unwrap. This essentially mimics what
2376 // IsQualificationConversion does, but here we're checking for a
2377 // strict subset of qualifiers.
2378 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2379 // The qualifiers are the same, so this doesn't tell us anything
2380 // about how the sequences rank.
2381 ;
2382 else if (T2.isMoreQualifiedThan(T1)) {
2383 // T1 has fewer qualifiers, so it could be the better sequence.
2384 if (Result == ImplicitConversionSequence::Worse)
2385 // Neither has qualifiers that are a subset of the other's
2386 // qualifiers.
2387 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002388
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002389 Result = ImplicitConversionSequence::Better;
2390 } else if (T1.isMoreQualifiedThan(T2)) {
2391 // T2 has fewer qualifiers, so it could be the better sequence.
2392 if (Result == ImplicitConversionSequence::Better)
2393 // Neither has qualifiers that are a subset of the other's
2394 // qualifiers.
2395 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002397 Result = ImplicitConversionSequence::Worse;
2398 } else {
2399 // Qualifiers are disjoint.
2400 return ImplicitConversionSequence::Indistinguishable;
2401 }
2402
2403 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002404 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002405 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002406 }
2407
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002408 // Check that the winning standard conversion sequence isn't using
2409 // the deprecated string literal array to pointer conversion.
2410 switch (Result) {
2411 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002412 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002413 Result = ImplicitConversionSequence::Indistinguishable;
2414 break;
2415
2416 case ImplicitConversionSequence::Indistinguishable:
2417 break;
2418
2419 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002420 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002421 Result = ImplicitConversionSequence::Indistinguishable;
2422 break;
2423 }
2424
2425 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002426}
2427
Douglas Gregor5c407d92008-10-23 00:40:37 +00002428/// CompareDerivedToBaseConversions - Compares two standard conversion
2429/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002430/// various kinds of derived-to-base conversions (C++
2431/// [over.ics.rank]p4b3). As part of these checks, we also look at
2432/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002433ImplicitConversionSequence::CompareKind
2434Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2435 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002436 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002437 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002438 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002439 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002440
2441 // Adjust the types we're converting from via the array-to-pointer
2442 // conversion, if we need to.
2443 if (SCS1.First == ICK_Array_To_Pointer)
2444 FromType1 = Context.getArrayDecayedType(FromType1);
2445 if (SCS2.First == ICK_Array_To_Pointer)
2446 FromType2 = Context.getArrayDecayedType(FromType2);
2447
2448 // Canonicalize all of the types.
2449 FromType1 = Context.getCanonicalType(FromType1);
2450 ToType1 = Context.getCanonicalType(ToType1);
2451 FromType2 = Context.getCanonicalType(FromType2);
2452 ToType2 = Context.getCanonicalType(ToType2);
2453
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002454 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002455 //
2456 // If class B is derived directly or indirectly from class A and
2457 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002458 //
2459 // For Objective-C, we let A, B, and C also be Objective-C
2460 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002461
2462 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002463 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002464 SCS2.Second == ICK_Pointer_Conversion &&
2465 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2466 FromType1->isPointerType() && FromType2->isPointerType() &&
2467 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002468 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002469 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002470 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002471 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002472 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002473 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002474 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002475 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002476
John McCall8b07ec22010-05-15 11:32:37 +00002477 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2478 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2479 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2480 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002481
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002482 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002483 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2484 if (IsDerivedFrom(ToPointee1, ToPointee2))
2485 return ImplicitConversionSequence::Better;
2486 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2487 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002488
2489 if (ToIface1 && ToIface2) {
2490 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2491 return ImplicitConversionSequence::Better;
2492 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2493 return ImplicitConversionSequence::Worse;
2494 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002495 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002496
2497 // -- conversion of B* to A* is better than conversion of C* to A*,
2498 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2499 if (IsDerivedFrom(FromPointee2, FromPointee1))
2500 return ImplicitConversionSequence::Better;
2501 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2502 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002503
Douglas Gregor237f96c2008-11-26 23:31:11 +00002504 if (FromIface1 && FromIface2) {
2505 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2506 return ImplicitConversionSequence::Better;
2507 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2508 return ImplicitConversionSequence::Worse;
2509 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002510 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002511 }
2512
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002513 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002514 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2515 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2516 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2517 const MemberPointerType * FromMemPointer1 =
2518 FromType1->getAs<MemberPointerType>();
2519 const MemberPointerType * ToMemPointer1 =
2520 ToType1->getAs<MemberPointerType>();
2521 const MemberPointerType * FromMemPointer2 =
2522 FromType2->getAs<MemberPointerType>();
2523 const MemberPointerType * ToMemPointer2 =
2524 ToType2->getAs<MemberPointerType>();
2525 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2526 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2527 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2528 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2529 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2530 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2531 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2532 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002533 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002534 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2535 if (IsDerivedFrom(ToPointee1, ToPointee2))
2536 return ImplicitConversionSequence::Worse;
2537 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2538 return ImplicitConversionSequence::Better;
2539 }
2540 // conversion of B::* to C::* is better than conversion of A::* to C::*
2541 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2542 if (IsDerivedFrom(FromPointee1, FromPointee2))
2543 return ImplicitConversionSequence::Better;
2544 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2545 return ImplicitConversionSequence::Worse;
2546 }
2547 }
2548
Douglas Gregor5ab11652010-04-17 22:01:05 +00002549 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002550 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002551 // -- binding of an expression of type C to a reference of type
2552 // B& is better than binding an expression of type C to a
2553 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002554 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2555 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002556 if (IsDerivedFrom(ToType1, ToType2))
2557 return ImplicitConversionSequence::Better;
2558 else if (IsDerivedFrom(ToType2, ToType1))
2559 return ImplicitConversionSequence::Worse;
2560 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002561
Douglas Gregor2fe98832008-11-03 19:09:14 +00002562 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002563 // -- binding of an expression of type B to a reference of type
2564 // A& is better than binding an expression of type C to a
2565 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002566 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2567 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002568 if (IsDerivedFrom(FromType2, FromType1))
2569 return ImplicitConversionSequence::Better;
2570 else if (IsDerivedFrom(FromType1, FromType2))
2571 return ImplicitConversionSequence::Worse;
2572 }
2573 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002574
Douglas Gregor5c407d92008-10-23 00:40:37 +00002575 return ImplicitConversionSequence::Indistinguishable;
2576}
2577
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002578/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2579/// determine whether they are reference-related,
2580/// reference-compatible, reference-compatible with added
2581/// qualification, or incompatible, for use in C++ initialization by
2582/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2583/// type, and the first type (T1) is the pointee type of the reference
2584/// type being initialized.
2585Sema::ReferenceCompareResult
2586Sema::CompareReferenceRelationship(SourceLocation Loc,
2587 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002588 bool &DerivedToBase,
2589 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002590 assert(!OrigT1->isReferenceType() &&
2591 "T1 must be the pointee type of the reference type");
2592 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2593
2594 QualType T1 = Context.getCanonicalType(OrigT1);
2595 QualType T2 = Context.getCanonicalType(OrigT2);
2596 Qualifiers T1Quals, T2Quals;
2597 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2598 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2599
2600 // C++ [dcl.init.ref]p4:
2601 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2602 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2603 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002604 DerivedToBase = false;
2605 ObjCConversion = false;
2606 if (UnqualT1 == UnqualT2) {
2607 // Nothing to do.
2608 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002609 IsDerivedFrom(UnqualT2, UnqualT1))
2610 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002611 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2612 UnqualT2->isObjCObjectOrInterfaceType() &&
2613 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2614 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002615 else
2616 return Ref_Incompatible;
2617
2618 // At this point, we know that T1 and T2 are reference-related (at
2619 // least).
2620
2621 // If the type is an array type, promote the element qualifiers to the type
2622 // for comparison.
2623 if (isa<ArrayType>(T1) && T1Quals)
2624 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2625 if (isa<ArrayType>(T2) && T2Quals)
2626 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2627
2628 // C++ [dcl.init.ref]p4:
2629 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2630 // reference-related to T2 and cv1 is the same cv-qualification
2631 // as, or greater cv-qualification than, cv2. For purposes of
2632 // overload resolution, cases for which cv1 is greater
2633 // cv-qualification than cv2 are identified as
2634 // reference-compatible with added qualification (see 13.3.3.2).
2635 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2636 return Ref_Compatible;
2637 else if (T1.isMoreQualifiedThan(T2))
2638 return Ref_Compatible_With_Added_Qualification;
2639 else
2640 return Ref_Related;
2641}
2642
Douglas Gregor836a7e82010-08-11 02:15:33 +00002643/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002644/// with DeclType. Return true if something definite is found.
2645static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002646FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2647 QualType DeclType, SourceLocation DeclLoc,
2648 Expr *Init, QualType T2, bool AllowRvalues,
2649 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002650 assert(T2->isRecordType() && "Can only find conversions of record types.");
2651 CXXRecordDecl *T2RecordDecl
2652 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2653
Douglas Gregor836a7e82010-08-11 02:15:33 +00002654 QualType ToType
2655 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2656 : DeclType;
2657
Sebastian Redld92badf2010-06-30 18:13:39 +00002658 OverloadCandidateSet CandidateSet(DeclLoc);
2659 const UnresolvedSetImpl *Conversions
2660 = T2RecordDecl->getVisibleConversionFunctions();
2661 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2662 E = Conversions->end(); I != E; ++I) {
2663 NamedDecl *D = *I;
2664 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2665 if (isa<UsingShadowDecl>(D))
2666 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2667
2668 FunctionTemplateDecl *ConvTemplate
2669 = dyn_cast<FunctionTemplateDecl>(D);
2670 CXXConversionDecl *Conv;
2671 if (ConvTemplate)
2672 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2673 else
2674 Conv = cast<CXXConversionDecl>(D);
2675
Douglas Gregor836a7e82010-08-11 02:15:33 +00002676 // If this is an explicit conversion, and we're not allowed to consider
2677 // explicit conversions, skip it.
2678 if (!AllowExplicit && Conv->isExplicit())
2679 continue;
2680
2681 if (AllowRvalues) {
2682 bool DerivedToBase = false;
2683 bool ObjCConversion = false;
2684 if (!ConvTemplate &&
2685 S.CompareReferenceRelationship(DeclLoc,
2686 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2687 DeclType.getNonReferenceType().getUnqualifiedType(),
2688 DerivedToBase, ObjCConversion)
2689 == Sema::Ref_Incompatible)
2690 continue;
2691 } else {
2692 // If the conversion function doesn't return a reference type,
2693 // it can't be considered for this conversion. An rvalue reference
2694 // is only acceptable if its referencee is a function type.
2695
2696 const ReferenceType *RefType =
2697 Conv->getConversionType()->getAs<ReferenceType>();
2698 if (!RefType ||
2699 (!RefType->isLValueReferenceType() &&
2700 !RefType->getPointeeType()->isFunctionType()))
2701 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002702 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002703
2704 if (ConvTemplate)
2705 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2706 Init, ToType, CandidateSet);
2707 else
2708 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2709 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002710 }
2711
2712 OverloadCandidateSet::iterator Best;
2713 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2714 case OR_Success:
2715 // C++ [over.ics.ref]p1:
2716 //
2717 // [...] If the parameter binds directly to the result of
2718 // applying a conversion function to the argument
2719 // expression, the implicit conversion sequence is a
2720 // user-defined conversion sequence (13.3.3.1.2), with the
2721 // second standard conversion sequence either an identity
2722 // conversion or, if the conversion function returns an
2723 // entity of a type that is a derived class of the parameter
2724 // type, a derived-to-base Conversion.
2725 if (!Best->FinalConversion.DirectBinding)
2726 return false;
2727
2728 ICS.setUserDefined();
2729 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2730 ICS.UserDefined.After = Best->FinalConversion;
2731 ICS.UserDefined.ConversionFunction = Best->Function;
2732 ICS.UserDefined.EllipsisConversion = false;
2733 assert(ICS.UserDefined.After.ReferenceBinding &&
2734 ICS.UserDefined.After.DirectBinding &&
2735 "Expected a direct reference binding!");
2736 return true;
2737
2738 case OR_Ambiguous:
2739 ICS.setAmbiguous();
2740 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2741 Cand != CandidateSet.end(); ++Cand)
2742 if (Cand->Viable)
2743 ICS.Ambiguous.addConversion(Cand->Function);
2744 return true;
2745
2746 case OR_No_Viable_Function:
2747 case OR_Deleted:
2748 // There was no suitable conversion, or we found a deleted
2749 // conversion; continue with other checks.
2750 return false;
2751 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002752
2753 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002754}
2755
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002756/// \brief Compute an implicit conversion sequence for reference
2757/// initialization.
2758static ImplicitConversionSequence
2759TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2760 SourceLocation DeclLoc,
2761 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002762 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002763 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2764
2765 // Most paths end in a failed conversion.
2766 ImplicitConversionSequence ICS;
2767 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2768
2769 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2770 QualType T2 = Init->getType();
2771
2772 // If the initializer is the address of an overloaded function, try
2773 // to resolve the overloaded function. If all goes well, T2 is the
2774 // type of the resulting function.
2775 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2776 DeclAccessPair Found;
2777 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2778 false, Found))
2779 T2 = Fn->getType();
2780 }
2781
2782 // Compute some basic properties of the types and the initializer.
2783 bool isRValRef = DeclType->isRValueReferenceType();
2784 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002785 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002786 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002787 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002788 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2789 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002790
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002791
Sebastian Redld92badf2010-06-30 18:13:39 +00002792 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002793 // A reference to type "cv1 T1" is initialized by an expression
2794 // of type "cv2 T2" as follows:
2795
Sebastian Redld92badf2010-06-30 18:13:39 +00002796 // -- If reference is an lvalue reference and the initializer expression
2797 // The next bullet point (T1 is a function) is pretty much equivalent to this
2798 // one, so it's handled here.
2799 if (!isRValRef || T1->isFunctionType()) {
2800 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2801 // reference-compatible with "cv2 T2," or
2802 //
2803 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2804 if (InitCategory.isLValue() &&
2805 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002806 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002807 // When a parameter of reference type binds directly (8.5.3)
2808 // to an argument expression, the implicit conversion sequence
2809 // is the identity conversion, unless the argument expression
2810 // has a type that is a derived class of the parameter type,
2811 // in which case the implicit conversion sequence is a
2812 // derived-to-base Conversion (13.3.3.1).
2813 ICS.setStandard();
2814 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002815 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2816 : ObjCConversion? ICK_Compatible_Conversion
2817 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002818 ICS.Standard.Third = ICK_Identity;
2819 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2820 ICS.Standard.setToType(0, T2);
2821 ICS.Standard.setToType(1, T1);
2822 ICS.Standard.setToType(2, T1);
2823 ICS.Standard.ReferenceBinding = true;
2824 ICS.Standard.DirectBinding = true;
2825 ICS.Standard.RRefBinding = isRValRef;
2826 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002827
Sebastian Redld92badf2010-06-30 18:13:39 +00002828 // Nothing more to do: the inaccessibility/ambiguity check for
2829 // derived-to-base conversions is suppressed when we're
2830 // computing the implicit conversion sequence (C++
2831 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002832 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002833 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002834
Sebastian Redld92badf2010-06-30 18:13:39 +00002835 // -- has a class type (i.e., T2 is a class type), where T1 is
2836 // not reference-related to T2, and can be implicitly
2837 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2838 // is reference-compatible with "cv3 T3" 92) (this
2839 // conversion is selected by enumerating the applicable
2840 // conversion functions (13.3.1.6) and choosing the best
2841 // one through overload resolution (13.3)),
2842 if (!SuppressUserConversions && T2->isRecordType() &&
2843 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2844 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002845 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2846 Init, T2, /*AllowRvalues=*/false,
2847 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002848 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002849 }
2850 }
2851
Sebastian Redld92badf2010-06-30 18:13:39 +00002852 // -- Otherwise, the reference shall be an lvalue reference to a
2853 // non-volatile const type (i.e., cv1 shall be const), or the reference
2854 // shall be an rvalue reference and the initializer expression shall be
2855 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002856 //
2857 // We actually handle one oddity of C++ [over.ics.ref] at this
2858 // point, which is that, due to p2 (which short-circuits reference
2859 // binding by only attempting a simple conversion for non-direct
2860 // bindings) and p3's strange wording, we allow a const volatile
2861 // reference to bind to an rvalue. Hence the check for the presence
2862 // of "const" rather than checking for "const" being the only
2863 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002864 // This is also the point where rvalue references and lvalue inits no longer
2865 // go together.
2866 if ((!isRValRef && !T1.isConstQualified()) ||
2867 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002868 return ICS;
2869
Sebastian Redld92badf2010-06-30 18:13:39 +00002870 // -- If T1 is a function type, then
2871 // -- if T2 is the same type as T1, the reference is bound to the
2872 // initializer expression lvalue;
2873 // -- if T2 is a class type and the initializer expression can be
2874 // implicitly converted to an lvalue of type T1 [...], the
2875 // reference is bound to the function lvalue that is the result
2876 // of the conversion;
2877 // This is the same as for the lvalue case above, so it was handled there.
2878 // -- otherwise, the program is ill-formed.
2879 // This is the one difference to the lvalue case.
2880 if (T1->isFunctionType())
2881 return ICS;
2882
2883 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002884 // -- the initializer expression is an rvalue and "cv1 T1"
2885 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002886 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002887 // -- T1 is not reference-related to T2 and the initializer
2888 // expression can be implicitly converted to an rvalue
2889 // of type "cv3 T3" (this conversion is selected by
2890 // enumerating the applicable conversion functions
2891 // (13.3.1.6) and choosing the best one through overload
2892 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002893 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002894 // then the reference is bound to the initializer
2895 // expression rvalue in the first case and to the object
2896 // that is the result of the conversion in the second case
2897 // (or, in either case, to the appropriate base class
2898 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002899 if (T2->isRecordType()) {
2900 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2901 // direct binding in C++0x but not in C++03.
2902 if (InitCategory.isRValue() &&
2903 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2904 ICS.setStandard();
2905 ICS.Standard.First = ICK_Identity;
2906 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2907 : ObjCConversion? ICK_Compatible_Conversion
2908 : ICK_Identity;
2909 ICS.Standard.Third = ICK_Identity;
2910 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2911 ICS.Standard.setToType(0, T2);
2912 ICS.Standard.setToType(1, T1);
2913 ICS.Standard.setToType(2, T1);
2914 ICS.Standard.ReferenceBinding = true;
2915 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2916 ICS.Standard.RRefBinding = isRValRef;
2917 ICS.Standard.CopyConstructor = 0;
2918 return ICS;
2919 }
2920
2921 // Second case: not reference-related.
2922 if (RefRelationship == Sema::Ref_Incompatible &&
2923 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2924 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2925 Init, T2, /*AllowRvalues=*/true,
2926 AllowExplicit))
2927 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002928 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002929
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002930 // -- Otherwise, a temporary of type "cv1 T1" is created and
2931 // initialized from the initializer expression using the
2932 // rules for a non-reference copy initialization (8.5). The
2933 // reference is then bound to the temporary. If T1 is
2934 // reference-related to T2, cv1 must be the same
2935 // cv-qualification as, or greater cv-qualification than,
2936 // cv2; otherwise, the program is ill-formed.
2937 if (RefRelationship == Sema::Ref_Related) {
2938 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2939 // we would be reference-compatible or reference-compatible with
2940 // added qualification. But that wasn't the case, so the reference
2941 // initialization fails.
2942 return ICS;
2943 }
2944
2945 // If at least one of the types is a class type, the types are not
2946 // related, and we aren't allowed any user conversions, the
2947 // reference binding fails. This case is important for breaking
2948 // recursion, since TryImplicitConversion below will attempt to
2949 // create a temporary through the use of a copy constructor.
2950 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2951 (T1->isRecordType() || T2->isRecordType()))
2952 return ICS;
2953
2954 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002955 // When a parameter of reference type is not bound directly to
2956 // an argument expression, the conversion sequence is the one
2957 // required to convert the argument expression to the
2958 // underlying type of the reference according to
2959 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2960 // to copy-initializing a temporary of the underlying type with
2961 // the argument expression. Any difference in top-level
2962 // cv-qualification is subsumed by the initialization itself
2963 // and does not constitute a conversion.
2964 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2965 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002966 /*InOverloadResolution=*/false);
2967
2968 // Of course, that's still a reference binding.
2969 if (ICS.isStandard()) {
2970 ICS.Standard.ReferenceBinding = true;
2971 ICS.Standard.RRefBinding = isRValRef;
2972 } else if (ICS.isUserDefined()) {
2973 ICS.UserDefined.After.ReferenceBinding = true;
2974 ICS.UserDefined.After.RRefBinding = isRValRef;
2975 }
2976 return ICS;
2977}
2978
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002979/// TryCopyInitialization - Try to copy-initialize a value of type
2980/// ToType from the expression From. Return the implicit conversion
2981/// sequence required to pass this argument, which may be a bad
2982/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002983/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002984/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002985static ImplicitConversionSequence
2986TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002987 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002988 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002989 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002990 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002991 /*FIXME:*/From->getLocStart(),
2992 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002993 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002994
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002995 return S.TryImplicitConversion(From, ToType,
2996 SuppressUserConversions,
2997 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002998 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002999}
3000
Douglas Gregor436424c2008-11-18 23:14:02 +00003001/// TryObjectArgumentInitialization - Try to initialize the object
3002/// parameter of the given member function (@c Method) from the
3003/// expression @p From.
3004ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00003005Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00003006 CXXMethodDecl *Method,
3007 CXXRecordDecl *ActingContext) {
3008 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003009 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3010 // const volatile object.
3011 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3012 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3013 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003014
3015 // Set up the conversion sequence as a "bad" conversion, to allow us
3016 // to exit early.
3017 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003018
3019 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003020 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003021 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003022 FromType = PT->getPointeeType();
3023
3024 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003025
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003026 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003027 // where X is the class of which the function is a member
3028 // (C++ [over.match.funcs]p4). However, when finding an implicit
3029 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003030 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003031 // (C++ [over.match.funcs]p5). We perform a simplified version of
3032 // reference binding here, that allows class rvalues to bind to
3033 // non-constant references.
3034
3035 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3036 // with the implicit object parameter (C++ [over.match.funcs]p5).
3037 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003038 if (ImplicitParamType.getCVRQualifiers()
3039 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003040 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003041 ICS.setBad(BadConversionSequence::bad_qualifiers,
3042 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003043 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003044 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003045
3046 // Check that we have either the same type or a derived type. It
3047 // affects the conversion rank.
3048 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003049 ImplicitConversionKind SecondKind;
3050 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3051 SecondKind = ICK_Identity;
3052 } else if (IsDerivedFrom(FromType, ClassType))
3053 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003054 else {
John McCall65eb8792010-02-25 01:37:24 +00003055 ICS.setBad(BadConversionSequence::unrelated_class,
3056 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003057 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003058 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003059
3060 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003061 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003062 ICS.Standard.setAsIdentityConversion();
3063 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003064 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003065 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003066 ICS.Standard.ReferenceBinding = true;
3067 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003068 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003069 return ICS;
3070}
3071
3072/// PerformObjectArgumentInitialization - Perform initialization of
3073/// the implicit object parameter for the given Method with the given
3074/// expression.
3075bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003076Sema::PerformObjectArgumentInitialization(Expr *&From,
3077 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003078 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003079 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003080 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003081 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003082 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003083
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003084 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003085 FromRecordType = PT->getPointeeType();
3086 DestType = Method->getThisType(Context);
3087 } else {
3088 FromRecordType = From->getType();
3089 DestType = ImplicitParamRecordType;
3090 }
3091
John McCall6e9f8f62009-12-03 04:06:58 +00003092 // Note that we always use the true parent context when performing
3093 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003094 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003095 = TryObjectArgumentInitialization(From->getType(), Method,
3096 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003097 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003098 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003099 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003100 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003101
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003102 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003103 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003104
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003105 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003106 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003107 From->getType()->isPointerType() ?
3108 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003109 return false;
3110}
3111
Douglas Gregor5fb53972009-01-14 15:45:31 +00003112/// TryContextuallyConvertToBool - Attempt to contextually convert the
3113/// expression From to bool (C++0x [conv]p3).
3114ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003115 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003116 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003117 // FIXME: Are these flags correct?
3118 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003119 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003120 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003121}
3122
3123/// PerformContextuallyConvertToBool - Perform a contextual conversion
3124/// of the expression From to bool (C++0x [conv]p3).
3125bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3126 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003127 if (!ICS.isBad())
3128 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003129
Fariborz Jahanian76197412009-11-18 18:26:29 +00003130 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003131 return Diag(From->getSourceRange().getBegin(),
3132 diag::err_typecheck_bool_condition)
3133 << From->getType() << From->getSourceRange();
3134 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003135}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003136
3137/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3138/// expression From to 'id'.
3139ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003140 QualType Ty = Context.getObjCIdType();
3141 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003142 // FIXME: Are these flags correct?
3143 /*SuppressUserConversions=*/false,
3144 /*AllowExplicit=*/true,
3145 /*InOverloadResolution=*/false);
3146}
3147
3148/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3149/// of the expression From to 'id'.
3150bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003151 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003152 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3153 if (!ICS.isBad())
3154 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3155 return true;
3156}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003157
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003158/// \brief Attempt to convert the given expression to an integral or
3159/// enumeration type.
3160///
3161/// This routine will attempt to convert an expression of class type to an
3162/// integral or enumeration type, if that class type only has a single
3163/// conversion to an integral or enumeration type.
3164///
Douglas Gregor4799d032010-06-30 00:20:43 +00003165/// \param Loc The source location of the construct that requires the
3166/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003167///
Douglas Gregor4799d032010-06-30 00:20:43 +00003168/// \param FromE The expression we're converting from.
3169///
3170/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3171/// have integral or enumeration type.
3172///
3173/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3174/// incomplete class type.
3175///
3176/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3177/// explicit conversion function (because no implicit conversion functions
3178/// were available). This is a recovery mode.
3179///
3180/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3181/// showing which conversion was picked.
3182///
3183/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3184/// conversion function that could convert to integral or enumeration type.
3185///
3186/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3187/// usable conversion function.
3188///
3189/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3190/// function, which may be an extension in this case.
3191///
3192/// \returns The expression, converted to an integral or enumeration type if
3193/// successful.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003194Sema::OwningExprResult
John McCallb268a282010-08-23 23:25:46 +00003195Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003196 const PartialDiagnostic &NotIntDiag,
3197 const PartialDiagnostic &IncompleteDiag,
3198 const PartialDiagnostic &ExplicitConvDiag,
3199 const PartialDiagnostic &ExplicitConvNote,
3200 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003201 const PartialDiagnostic &AmbigNote,
3202 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003203 // We can't perform any more checking for type-dependent expressions.
3204 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003205 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003206
3207 // If the expression already has integral or enumeration type, we're golden.
3208 QualType T = From->getType();
3209 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003210 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003211
3212 // FIXME: Check for missing '()' if T is a function type?
3213
3214 // If we don't have a class type in C++, there's no way we can get an
3215 // expression of integral or enumeration type.
3216 const RecordType *RecordTy = T->getAs<RecordType>();
3217 if (!RecordTy || !getLangOptions().CPlusPlus) {
3218 Diag(Loc, NotIntDiag)
3219 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003220 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003221 }
3222
3223 // We must have a complete class type.
3224 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003225 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003226
3227 // Look for a conversion to an integral or enumeration type.
3228 UnresolvedSet<4> ViableConversions;
3229 UnresolvedSet<4> ExplicitConversions;
3230 const UnresolvedSetImpl *Conversions
3231 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3232
3233 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3234 E = Conversions->end();
3235 I != E;
3236 ++I) {
3237 if (CXXConversionDecl *Conversion
3238 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3239 if (Conversion->getConversionType().getNonReferenceType()
3240 ->isIntegralOrEnumerationType()) {
3241 if (Conversion->isExplicit())
3242 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3243 else
3244 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3245 }
3246 }
3247
3248 switch (ViableConversions.size()) {
3249 case 0:
3250 if (ExplicitConversions.size() == 1) {
3251 DeclAccessPair Found = ExplicitConversions[0];
3252 CXXConversionDecl *Conversion
3253 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3254
3255 // The user probably meant to invoke the given explicit
3256 // conversion; use it.
3257 QualType ConvTy
3258 = Conversion->getConversionType().getNonReferenceType();
3259 std::string TypeStr;
3260 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3261
3262 Diag(Loc, ExplicitConvDiag)
3263 << T << ConvTy
3264 << FixItHint::CreateInsertion(From->getLocStart(),
3265 "static_cast<" + TypeStr + ">(")
3266 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3267 ")");
3268 Diag(Conversion->getLocation(), ExplicitConvNote)
3269 << ConvTy->isEnumeralType() << ConvTy;
3270
3271 // If we aren't in a SFINAE context, build a call to the
3272 // explicit conversion function.
3273 if (isSFINAEContext())
3274 return ExprError();
3275
3276 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003277 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003278 }
3279
3280 // We'll complain below about a non-integral condition type.
3281 break;
3282
3283 case 1: {
3284 // Apply this conversion.
3285 DeclAccessPair Found = ViableConversions[0];
3286 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003287
3288 CXXConversionDecl *Conversion
3289 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3290 QualType ConvTy
3291 = Conversion->getConversionType().getNonReferenceType();
3292 if (ConvDiag.getDiagID()) {
3293 if (isSFINAEContext())
3294 return ExprError();
3295
3296 Diag(Loc, ConvDiag)
3297 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3298 }
3299
John McCallb268a282010-08-23 23:25:46 +00003300 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003301 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003302 break;
3303 }
3304
3305 default:
3306 Diag(Loc, AmbigDiag)
3307 << T << From->getSourceRange();
3308 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3309 CXXConversionDecl *Conv
3310 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3311 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3312 Diag(Conv->getLocation(), AmbigNote)
3313 << ConvTy->isEnumeralType() << ConvTy;
3314 }
John McCallb268a282010-08-23 23:25:46 +00003315 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003316 }
3317
Douglas Gregor5823da32010-06-29 23:25:20 +00003318 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003319 Diag(Loc, NotIntDiag)
3320 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003321
John McCallb268a282010-08-23 23:25:46 +00003322 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003323}
3324
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003325/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003326/// candidate functions, using the given function call arguments. If
3327/// @p SuppressUserConversions, then don't allow user-defined
3328/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003329///
3330/// \para PartialOverloading true if we are performing "partial" overloading
3331/// based on an incomplete set of function arguments. This feature is used by
3332/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003333void
3334Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003335 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003336 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003337 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003338 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003339 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003340 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003341 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003342 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003343 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003344 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003345
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003346 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003347 if (!isa<CXXConstructorDecl>(Method)) {
3348 // If we get here, it's because we're calling a member function
3349 // that is named without a member access expression (e.g.,
3350 // "this->f") that was either written explicitly or created
3351 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003352 // function, e.g., X::f(). We use an empty type for the implied
3353 // object argument (C++ [over.call.func]p3), and the acting context
3354 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003355 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003356 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003357 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003358 return;
3359 }
3360 // We treat a constructor like a non-member function, since its object
3361 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003362 }
3363
Douglas Gregorff7028a2009-11-13 23:59:09 +00003364 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003365 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003366
Douglas Gregor27381f32009-11-23 12:27:39 +00003367 // Overload resolution is always an unevaluated context.
3368 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3369
Douglas Gregorffe14e32009-11-14 01:20:54 +00003370 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3371 // C++ [class.copy]p3:
3372 // A member function template is never instantiated to perform the copy
3373 // of a class object to an object of its class type.
3374 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3375 if (NumArgs == 1 &&
3376 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003377 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3378 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003379 return;
3380 }
3381
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003382 // Add this candidate
3383 CandidateSet.push_back(OverloadCandidate());
3384 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003385 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003386 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003387 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003388 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003389 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003390
3391 unsigned NumArgsInProto = Proto->getNumArgs();
3392
3393 // (C++ 13.3.2p2): A candidate function having fewer than m
3394 // parameters is viable only if it has an ellipsis in its parameter
3395 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003396 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3397 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003398 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003399 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003400 return;
3401 }
3402
3403 // (C++ 13.3.2p2): A candidate function having more than m parameters
3404 // is viable only if the (m+1)st parameter has a default argument
3405 // (8.3.6). For the purposes of overload resolution, the
3406 // parameter list is truncated on the right, so that there are
3407 // exactly m parameters.
3408 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003409 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003410 // Not enough arguments.
3411 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003412 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003413 return;
3414 }
3415
3416 // Determine the implicit conversion sequences for each of the
3417 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003418 Candidate.Conversions.resize(NumArgs);
3419 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3420 if (ArgIdx < NumArgsInProto) {
3421 // (C++ 13.3.2p3): for F to be a viable function, there shall
3422 // exist for each argument an implicit conversion sequence
3423 // (13.3.3.1) that converts that argument to the corresponding
3424 // parameter of F.
3425 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003426 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003427 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003428 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003429 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003430 if (Candidate.Conversions[ArgIdx].isBad()) {
3431 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003432 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003433 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003434 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003435 } else {
3436 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3437 // argument for which there is no corresponding parameter is
3438 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003439 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003440 }
3441 }
3442}
3443
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003444/// \brief Add all of the function declarations in the given function set to
3445/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003446void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003447 Expr **Args, unsigned NumArgs,
3448 OverloadCandidateSet& CandidateSet,
3449 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003450 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003451 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3452 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003453 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003454 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003455 cast<CXXMethodDecl>(FD)->getParent(),
3456 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003457 CandidateSet, SuppressUserConversions);
3458 else
John McCalla0296f72010-03-19 07:35:19 +00003459 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003460 SuppressUserConversions);
3461 } else {
John McCalla0296f72010-03-19 07:35:19 +00003462 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003463 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3464 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003465 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003466 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003467 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003468 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003469 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003470 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003471 else
John McCalla0296f72010-03-19 07:35:19 +00003472 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003473 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003474 Args, NumArgs, CandidateSet,
3475 SuppressUserConversions);
3476 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003477 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003478}
3479
John McCallf0f1cf02009-11-17 07:50:12 +00003480/// AddMethodCandidate - Adds a named decl (which is some kind of
3481/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003482void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003483 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003484 Expr **Args, unsigned NumArgs,
3485 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003486 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003487 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003488 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003489
3490 if (isa<UsingShadowDecl>(Decl))
3491 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3492
3493 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3494 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3495 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003496 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3497 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003498 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003499 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003500 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003501 } else {
John McCalla0296f72010-03-19 07:35:19 +00003502 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003503 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003504 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003505 }
3506}
3507
Douglas Gregor436424c2008-11-18 23:14:02 +00003508/// AddMethodCandidate - Adds the given C++ member function to the set
3509/// of candidate functions, using the given function call arguments
3510/// and the object argument (@c Object). For example, in a call
3511/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3512/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3513/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003514/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003515void
John McCalla0296f72010-03-19 07:35:19 +00003516Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003517 CXXRecordDecl *ActingContext, QualType ObjectType,
3518 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003519 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003520 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003521 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003522 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003523 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003524 assert(!isa<CXXConstructorDecl>(Method) &&
3525 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003526
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003527 if (!CandidateSet.isNewCandidate(Method))
3528 return;
3529
Douglas Gregor27381f32009-11-23 12:27:39 +00003530 // Overload resolution is always an unevaluated context.
3531 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3532
Douglas Gregor436424c2008-11-18 23:14:02 +00003533 // Add this candidate
3534 CandidateSet.push_back(OverloadCandidate());
3535 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003536 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003537 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003538 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003539 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003540
3541 unsigned NumArgsInProto = Proto->getNumArgs();
3542
3543 // (C++ 13.3.2p2): A candidate function having fewer than m
3544 // parameters is viable only if it has an ellipsis in its parameter
3545 // list (8.3.5).
3546 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3547 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003548 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003549 return;
3550 }
3551
3552 // (C++ 13.3.2p2): A candidate function having more than m parameters
3553 // is viable only if the (m+1)st parameter has a default argument
3554 // (8.3.6). For the purposes of overload resolution, the
3555 // parameter list is truncated on the right, so that there are
3556 // exactly m parameters.
3557 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3558 if (NumArgs < MinRequiredArgs) {
3559 // Not enough arguments.
3560 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003561 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003562 return;
3563 }
3564
3565 Candidate.Viable = true;
3566 Candidate.Conversions.resize(NumArgs + 1);
3567
John McCall6e9f8f62009-12-03 04:06:58 +00003568 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003569 // The implicit object argument is ignored.
3570 Candidate.IgnoreObjectArgument = true;
3571 else {
3572 // Determine the implicit conversion sequence for the object
3573 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003574 Candidate.Conversions[0]
3575 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003576 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003577 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003578 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003579 return;
3580 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003581 }
3582
3583 // Determine the implicit conversion sequences for each of the
3584 // arguments.
3585 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3586 if (ArgIdx < NumArgsInProto) {
3587 // (C++ 13.3.2p3): for F to be a viable function, there shall
3588 // exist for each argument an implicit conversion sequence
3589 // (13.3.3.1) that converts that argument to the corresponding
3590 // parameter of F.
3591 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003592 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003593 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003594 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003595 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003596 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003597 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003598 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003599 break;
3600 }
3601 } else {
3602 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3603 // argument for which there is no corresponding parameter is
3604 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003605 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003606 }
3607 }
3608}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003609
Douglas Gregor97628d62009-08-21 00:16:32 +00003610/// \brief Add a C++ member function template as a candidate to the candidate
3611/// set, using template argument deduction to produce an appropriate member
3612/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003613void
Douglas Gregor97628d62009-08-21 00:16:32 +00003614Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003615 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003616 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003617 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003618 QualType ObjectType,
3619 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003620 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003621 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003622 if (!CandidateSet.isNewCandidate(MethodTmpl))
3623 return;
3624
Douglas Gregor97628d62009-08-21 00:16:32 +00003625 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003626 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003627 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003628 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003629 // candidate functions in the usual way.113) A given name can refer to one
3630 // or more function templates and also to a set of overloaded non-template
3631 // functions. In such a case, the candidate functions generated from each
3632 // function template are combined with the set of non-template candidate
3633 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003634 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003635 FunctionDecl *Specialization = 0;
3636 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003637 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003638 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003639 CandidateSet.push_back(OverloadCandidate());
3640 OverloadCandidate &Candidate = CandidateSet.back();
3641 Candidate.FoundDecl = FoundDecl;
3642 Candidate.Function = MethodTmpl->getTemplatedDecl();
3643 Candidate.Viable = false;
3644 Candidate.FailureKind = ovl_fail_bad_deduction;
3645 Candidate.IsSurrogate = false;
3646 Candidate.IgnoreObjectArgument = false;
3647 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3648 Info);
3649 return;
3650 }
Mike Stump11289f42009-09-09 15:08:12 +00003651
Douglas Gregor97628d62009-08-21 00:16:32 +00003652 // Add the function template specialization produced by template argument
3653 // deduction as a candidate.
3654 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003655 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003656 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003657 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003658 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003659 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003660}
3661
Douglas Gregor05155d82009-08-21 23:19:43 +00003662/// \brief Add a C++ function template specialization as a candidate
3663/// in the candidate set, using template argument deduction to produce
3664/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003665void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003666Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003667 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003668 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003669 Expr **Args, unsigned NumArgs,
3670 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003671 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003672 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3673 return;
3674
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003675 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003676 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003677 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003678 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003679 // candidate functions in the usual way.113) A given name can refer to one
3680 // or more function templates and also to a set of overloaded non-template
3681 // functions. In such a case, the candidate functions generated from each
3682 // function template are combined with the set of non-template candidate
3683 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003684 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003685 FunctionDecl *Specialization = 0;
3686 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003687 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003688 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003689 CandidateSet.push_back(OverloadCandidate());
3690 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003691 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003692 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3693 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003694 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003695 Candidate.IsSurrogate = false;
3696 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003697 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3698 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003699 return;
3700 }
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003702 // Add the function template specialization produced by template argument
3703 // deduction as a candidate.
3704 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003705 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003706 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003707}
Mike Stump11289f42009-09-09 15:08:12 +00003708
Douglas Gregora1f013e2008-11-07 22:36:19 +00003709/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003710/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003711/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003712/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003713/// (which may or may not be the same type as the type that the
3714/// conversion function produces).
3715void
3716Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003717 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003718 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003719 Expr *From, QualType ToType,
3720 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003721 assert(!Conversion->getDescribedFunctionTemplate() &&
3722 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003723 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003724 if (!CandidateSet.isNewCandidate(Conversion))
3725 return;
3726
Douglas Gregor27381f32009-11-23 12:27:39 +00003727 // Overload resolution is always an unevaluated context.
3728 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3729
Douglas Gregora1f013e2008-11-07 22:36:19 +00003730 // Add this candidate
3731 CandidateSet.push_back(OverloadCandidate());
3732 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003733 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003734 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003735 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003736 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003737 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003738 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003739 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003740 Candidate.Viable = true;
3741 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003742
Douglas Gregor6affc782010-08-19 15:37:02 +00003743 // C++ [over.match.funcs]p4:
3744 // For conversion functions, the function is considered to be a member of
3745 // the class of the implicit implied object argument for the purpose of
3746 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003747 //
3748 // Determine the implicit conversion sequence for the implicit
3749 // object parameter.
3750 QualType ImplicitParamType = From->getType();
3751 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3752 ImplicitParamType = FromPtrType->getPointeeType();
3753 CXXRecordDecl *ConversionContext
3754 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3755
3756 Candidate.Conversions[0]
3757 = TryObjectArgumentInitialization(From->getType(), Conversion,
3758 ConversionContext);
3759
John McCall0d1da222010-01-12 00:44:57 +00003760 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003761 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003762 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003763 return;
3764 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003765
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003766 // We won't go through a user-define type conversion function to convert a
3767 // derived to base as such conversions are given Conversion Rank. They only
3768 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3769 QualType FromCanon
3770 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3771 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3772 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3773 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003774 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003775 return;
3776 }
3777
Douglas Gregora1f013e2008-11-07 22:36:19 +00003778 // To determine what the conversion from the result of calling the
3779 // conversion function to the type we're eventually trying to
3780 // convert to (ToType), we need to synthesize a call to the
3781 // conversion function and attempt copy initialization from it. This
3782 // makes sure that we get the right semantics with respect to
3783 // lvalues/rvalues and the type. Fortunately, we can allocate this
3784 // call on the stack and we don't need its arguments to be
3785 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003786 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003787 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003788 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3789 Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003790 CastExpr::CK_FunctionToPointerDecay,
John McCallcf142162010-08-07 06:22:56 +00003791 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003792
3793 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003794 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3795 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003796 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003797 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003798 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003799 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003800 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003801 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003802 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003803
John McCall0d1da222010-01-12 00:44:57 +00003804 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003805 case ImplicitConversionSequence::StandardConversion:
3806 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003807
3808 // C++ [over.ics.user]p3:
3809 // If the user-defined conversion is specified by a specialization of a
3810 // conversion function template, the second standard conversion sequence
3811 // shall have exact match rank.
3812 if (Conversion->getPrimaryTemplate() &&
3813 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3814 Candidate.Viable = false;
3815 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3816 }
3817
Douglas Gregora1f013e2008-11-07 22:36:19 +00003818 break;
3819
3820 case ImplicitConversionSequence::BadConversion:
3821 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003822 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003823 break;
3824
3825 default:
Mike Stump11289f42009-09-09 15:08:12 +00003826 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003827 "Can only end up with a standard conversion sequence or failure");
3828 }
3829}
3830
Douglas Gregor05155d82009-08-21 23:19:43 +00003831/// \brief Adds a conversion function template specialization
3832/// candidate to the overload set, using template argument deduction
3833/// to deduce the template arguments of the conversion function
3834/// template from the type that we are converting to (C++
3835/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003836void
Douglas Gregor05155d82009-08-21 23:19:43 +00003837Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003838 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003839 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003840 Expr *From, QualType ToType,
3841 OverloadCandidateSet &CandidateSet) {
3842 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3843 "Only conversion function templates permitted here");
3844
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003845 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3846 return;
3847
John McCallbc077cf2010-02-08 23:07:23 +00003848 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003849 CXXConversionDecl *Specialization = 0;
3850 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003851 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003852 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003853 CandidateSet.push_back(OverloadCandidate());
3854 OverloadCandidate &Candidate = CandidateSet.back();
3855 Candidate.FoundDecl = FoundDecl;
3856 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3857 Candidate.Viable = false;
3858 Candidate.FailureKind = ovl_fail_bad_deduction;
3859 Candidate.IsSurrogate = false;
3860 Candidate.IgnoreObjectArgument = false;
3861 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3862 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003863 return;
3864 }
Mike Stump11289f42009-09-09 15:08:12 +00003865
Douglas Gregor05155d82009-08-21 23:19:43 +00003866 // Add the conversion function template specialization produced by
3867 // template argument deduction as a candidate.
3868 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003869 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003870 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003871}
3872
Douglas Gregorab7897a2008-11-19 22:57:39 +00003873/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3874/// converts the given @c Object to a function pointer via the
3875/// conversion function @c Conversion, and then attempts to call it
3876/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3877/// the type of function that we'll eventually be calling.
3878void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003879 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003880 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003881 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003882 QualType ObjectType,
3883 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003884 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003885 if (!CandidateSet.isNewCandidate(Conversion))
3886 return;
3887
Douglas Gregor27381f32009-11-23 12:27:39 +00003888 // Overload resolution is always an unevaluated context.
3889 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3890
Douglas Gregorab7897a2008-11-19 22:57:39 +00003891 CandidateSet.push_back(OverloadCandidate());
3892 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003893 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003894 Candidate.Function = 0;
3895 Candidate.Surrogate = Conversion;
3896 Candidate.Viable = true;
3897 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003898 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003899 Candidate.Conversions.resize(NumArgs + 1);
3900
3901 // Determine the implicit conversion sequence for the implicit
3902 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003903 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003904 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003905 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003906 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003907 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003908 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003909 return;
3910 }
3911
3912 // The first conversion is actually a user-defined conversion whose
3913 // first conversion is ObjectInit's standard conversion (which is
3914 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003915 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003916 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003917 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003918 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003919 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003920 = Candidate.Conversions[0].UserDefined.Before;
3921 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3922
Mike Stump11289f42009-09-09 15:08:12 +00003923 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003924 unsigned NumArgsInProto = Proto->getNumArgs();
3925
3926 // (C++ 13.3.2p2): A candidate function having fewer than m
3927 // parameters is viable only if it has an ellipsis in its parameter
3928 // list (8.3.5).
3929 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3930 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003931 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003932 return;
3933 }
3934
3935 // Function types don't have any default arguments, so just check if
3936 // we have enough arguments.
3937 if (NumArgs < NumArgsInProto) {
3938 // Not enough arguments.
3939 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003940 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003941 return;
3942 }
3943
3944 // Determine the implicit conversion sequences for each of the
3945 // arguments.
3946 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3947 if (ArgIdx < NumArgsInProto) {
3948 // (C++ 13.3.2p3): for F to be a viable function, there shall
3949 // exist for each argument an implicit conversion sequence
3950 // (13.3.3.1) that converts that argument to the corresponding
3951 // parameter of F.
3952 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003953 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003954 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003955 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003956 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003957 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003958 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003959 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003960 break;
3961 }
3962 } else {
3963 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3964 // argument for which there is no corresponding parameter is
3965 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003966 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003967 }
3968 }
3969}
3970
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003971/// \brief Add overload candidates for overloaded operators that are
3972/// member functions.
3973///
3974/// Add the overloaded operator candidates that are member functions
3975/// for the operator Op that was used in an operator expression such
3976/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3977/// CandidateSet will store the added overload candidates. (C++
3978/// [over.match.oper]).
3979void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3980 SourceLocation OpLoc,
3981 Expr **Args, unsigned NumArgs,
3982 OverloadCandidateSet& CandidateSet,
3983 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003984 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3985
3986 // C++ [over.match.oper]p3:
3987 // For a unary operator @ with an operand of a type whose
3988 // cv-unqualified version is T1, and for a binary operator @ with
3989 // a left operand of a type whose cv-unqualified version is T1 and
3990 // a right operand of a type whose cv-unqualified version is T2,
3991 // three sets of candidate functions, designated member
3992 // candidates, non-member candidates and built-in candidates, are
3993 // constructed as follows:
3994 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00003995
3996 // -- If T1 is a class type, the set of member candidates is the
3997 // result of the qualified lookup of T1::operator@
3998 // (13.3.1.1.1); otherwise, the set of member candidates is
3999 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004000 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004001 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004002 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004003 return;
Mike Stump11289f42009-09-09 15:08:12 +00004004
John McCall27b18f82009-11-17 02:14:36 +00004005 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4006 LookupQualifiedName(Operators, T1Rec->getDecl());
4007 Operators.suppressDiagnostics();
4008
Mike Stump11289f42009-09-09 15:08:12 +00004009 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004010 OperEnd = Operators.end();
4011 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004012 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004013 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004014 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004015 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004016 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004017}
4018
Douglas Gregora11693b2008-11-12 17:17:38 +00004019/// AddBuiltinCandidate - Add a candidate for a built-in
4020/// operator. ResultTy and ParamTys are the result and parameter types
4021/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004022/// arguments being passed to the candidate. IsAssignmentOperator
4023/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004024/// operator. NumContextualBoolArguments is the number of arguments
4025/// (at the beginning of the argument list) that will be contextually
4026/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004027void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004028 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004029 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004030 bool IsAssignmentOperator,
4031 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004032 // Overload resolution is always an unevaluated context.
4033 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4034
Douglas Gregora11693b2008-11-12 17:17:38 +00004035 // Add this candidate
4036 CandidateSet.push_back(OverloadCandidate());
4037 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004038 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004039 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004040 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004041 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004042 Candidate.BuiltinTypes.ResultTy = ResultTy;
4043 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4044 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4045
4046 // Determine the implicit conversion sequences for each of the
4047 // arguments.
4048 Candidate.Viable = true;
4049 Candidate.Conversions.resize(NumArgs);
4050 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004051 // C++ [over.match.oper]p4:
4052 // For the built-in assignment operators, conversions of the
4053 // left operand are restricted as follows:
4054 // -- no temporaries are introduced to hold the left operand, and
4055 // -- no user-defined conversions are applied to the left
4056 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004057 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004058 //
4059 // We block these conversions by turning off user-defined
4060 // conversions, since that is the only way that initialization of
4061 // a reference to a non-class type can occur from something that
4062 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004063 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004064 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004065 "Contextual conversion to bool requires bool type");
4066 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4067 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004068 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004069 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004070 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004071 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004072 }
John McCall0d1da222010-01-12 00:44:57 +00004073 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004074 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004075 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004076 break;
4077 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004078 }
4079}
4080
4081/// BuiltinCandidateTypeSet - A set of types that will be used for the
4082/// candidate operator functions for built-in operators (C++
4083/// [over.built]). The types are separated into pointer types and
4084/// enumeration types.
4085class BuiltinCandidateTypeSet {
4086 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004087 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004088
4089 /// PointerTypes - The set of pointer types that will be used in the
4090 /// built-in candidates.
4091 TypeSet PointerTypes;
4092
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004093 /// MemberPointerTypes - The set of member pointer types that will be
4094 /// used in the built-in candidates.
4095 TypeSet MemberPointerTypes;
4096
Douglas Gregora11693b2008-11-12 17:17:38 +00004097 /// EnumerationTypes - The set of enumeration types that will be
4098 /// used in the built-in candidates.
4099 TypeSet EnumerationTypes;
4100
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004101 /// \brief The set of vector types that will be used in the built-in
4102 /// candidates.
4103 TypeSet VectorTypes;
4104
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004105 /// Sema - The semantic analysis instance where we are building the
4106 /// candidate type set.
4107 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004108
Douglas Gregora11693b2008-11-12 17:17:38 +00004109 /// Context - The AST context in which we will build the type sets.
4110 ASTContext &Context;
4111
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004112 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4113 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004114 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004115
4116public:
4117 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004118 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004119
Mike Stump11289f42009-09-09 15:08:12 +00004120 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004121 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004122
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004123 void AddTypesConvertedFrom(QualType Ty,
4124 SourceLocation Loc,
4125 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004126 bool AllowExplicitConversions,
4127 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004128
4129 /// pointer_begin - First pointer type found;
4130 iterator pointer_begin() { return PointerTypes.begin(); }
4131
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004132 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004133 iterator pointer_end() { return PointerTypes.end(); }
4134
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004135 /// member_pointer_begin - First member pointer type found;
4136 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4137
4138 /// member_pointer_end - Past the last member pointer type found;
4139 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4140
Douglas Gregora11693b2008-11-12 17:17:38 +00004141 /// enumeration_begin - First enumeration type found;
4142 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4143
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004144 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004145 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004146
4147 iterator vector_begin() { return VectorTypes.begin(); }
4148 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004149};
4150
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004151/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004152/// the set of pointer types along with any more-qualified variants of
4153/// that type. For example, if @p Ty is "int const *", this routine
4154/// will add "int const *", "int const volatile *", "int const
4155/// restrict *", and "int const volatile restrict *" to the set of
4156/// pointer types. Returns true if the add of @p Ty itself succeeded,
4157/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004158///
4159/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004160bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004161BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4162 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004163
Douglas Gregora11693b2008-11-12 17:17:38 +00004164 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004165 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004166 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004167
4168 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004169 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004170 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004171 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004172 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004173 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004174 buildObjCPtr = true;
4175 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004176 else
4177 assert(false && "type was not a pointer type!");
4178 }
4179 else
4180 PointeeTy = PointerTy->getPointeeType();
4181
Sebastian Redl4990a632009-11-18 20:39:26 +00004182 // Don't add qualified variants of arrays. For one, they're not allowed
4183 // (the qualifier would sink to the element type), and for another, the
4184 // only overload situation where it matters is subscript or pointer +- int,
4185 // and those shouldn't have qualifier variants anyway.
4186 if (PointeeTy->isArrayType())
4187 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004188 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004189 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004190 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004191 bool hasVolatile = VisibleQuals.hasVolatile();
4192 bool hasRestrict = VisibleQuals.hasRestrict();
4193
John McCall8ccfcb52009-09-24 19:53:00 +00004194 // Iterate through all strict supersets of BaseCVR.
4195 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4196 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004197 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4198 // in the types.
4199 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4200 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004201 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004202 if (!buildObjCPtr)
4203 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4204 else
4205 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004206 }
4207
4208 return true;
4209}
4210
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004211/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4212/// to the set of pointer types along with any more-qualified variants of
4213/// that type. For example, if @p Ty is "int const *", this routine
4214/// will add "int const *", "int const volatile *", "int const
4215/// restrict *", and "int const volatile restrict *" to the set of
4216/// pointer types. Returns true if the add of @p Ty itself succeeded,
4217/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004218///
4219/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004220bool
4221BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4222 QualType Ty) {
4223 // Insert this type.
4224 if (!MemberPointerTypes.insert(Ty))
4225 return false;
4226
John McCall8ccfcb52009-09-24 19:53:00 +00004227 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4228 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004229
John McCall8ccfcb52009-09-24 19:53:00 +00004230 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004231 // Don't add qualified variants of arrays. For one, they're not allowed
4232 // (the qualifier would sink to the element type), and for another, the
4233 // only overload situation where it matters is subscript or pointer +- int,
4234 // and those shouldn't have qualifier variants anyway.
4235 if (PointeeTy->isArrayType())
4236 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004237 const Type *ClassTy = PointerTy->getClass();
4238
4239 // Iterate through all strict supersets of the pointee type's CVR
4240 // qualifiers.
4241 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4242 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4243 if ((CVR | BaseCVR) != CVR) continue;
4244
4245 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4246 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004247 }
4248
4249 return true;
4250}
4251
Douglas Gregora11693b2008-11-12 17:17:38 +00004252/// AddTypesConvertedFrom - Add each of the types to which the type @p
4253/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004254/// primarily interested in pointer types and enumeration types. We also
4255/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004256/// AllowUserConversions is true if we should look at the conversion
4257/// functions of a class type, and AllowExplicitConversions if we
4258/// should also include the explicit conversion functions of a class
4259/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004260void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004261BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004262 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004263 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004264 bool AllowExplicitConversions,
4265 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004266 // Only deal with canonical types.
4267 Ty = Context.getCanonicalType(Ty);
4268
4269 // Look through reference types; they aren't part of the type of an
4270 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004271 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004272 Ty = RefTy->getPointeeType();
4273
4274 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004275 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004276
Sebastian Redl65ae2002009-11-05 16:36:20 +00004277 // If we're dealing with an array type, decay to the pointer.
4278 if (Ty->isArrayType())
4279 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004280 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4281 PointerTypes.insert(Ty);
4282 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004283 // Insert our type, and its more-qualified variants, into the set
4284 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004285 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004286 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004287 } else if (Ty->isMemberPointerType()) {
4288 // Member pointers are far easier, since the pointee can't be converted.
4289 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4290 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004291 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004292 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004293 } else if (Ty->isVectorType()) {
4294 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004295 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004296 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004297 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004298 // No conversion functions in incomplete types.
4299 return;
4300 }
Mike Stump11289f42009-09-09 15:08:12 +00004301
Douglas Gregora11693b2008-11-12 17:17:38 +00004302 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004303 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004304 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004305 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004306 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004307 NamedDecl *D = I.getDecl();
4308 if (isa<UsingShadowDecl>(D))
4309 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004310
Mike Stump11289f42009-09-09 15:08:12 +00004311 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004312 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004313 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004314 continue;
4315
John McCallda4458e2010-03-31 01:36:47 +00004316 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004317 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004318 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004319 VisibleQuals);
4320 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004321 }
4322 }
4323 }
4324}
4325
Douglas Gregor84605ae2009-08-24 13:43:27 +00004326/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4327/// the volatile- and non-volatile-qualified assignment operators for the
4328/// given type to the candidate set.
4329static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4330 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004331 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004332 unsigned NumArgs,
4333 OverloadCandidateSet &CandidateSet) {
4334 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004335
Douglas Gregor84605ae2009-08-24 13:43:27 +00004336 // T& operator=(T&, T)
4337 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4338 ParamTypes[1] = T;
4339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4340 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004341
Douglas Gregor84605ae2009-08-24 13:43:27 +00004342 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4343 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004344 ParamTypes[0]
4345 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004346 ParamTypes[1] = T;
4347 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004348 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004349 }
4350}
Mike Stump11289f42009-09-09 15:08:12 +00004351
Sebastian Redl1054fae2009-10-25 17:03:50 +00004352/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4353/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004354static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4355 Qualifiers VRQuals;
4356 const RecordType *TyRec;
4357 if (const MemberPointerType *RHSMPType =
4358 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004359 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004360 else
4361 TyRec = ArgExpr->getType()->getAs<RecordType>();
4362 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004363 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004364 VRQuals.addVolatile();
4365 VRQuals.addRestrict();
4366 return VRQuals;
4367 }
4368
4369 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004370 if (!ClassDecl->hasDefinition())
4371 return VRQuals;
4372
John McCallad371252010-01-20 00:46:10 +00004373 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004374 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004375
John McCallad371252010-01-20 00:46:10 +00004376 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004377 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004378 NamedDecl *D = I.getDecl();
4379 if (isa<UsingShadowDecl>(D))
4380 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4381 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004382 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4383 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4384 CanTy = ResTypeRef->getPointeeType();
4385 // Need to go down the pointer/mempointer chain and add qualifiers
4386 // as see them.
4387 bool done = false;
4388 while (!done) {
4389 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4390 CanTy = ResTypePtr->getPointeeType();
4391 else if (const MemberPointerType *ResTypeMPtr =
4392 CanTy->getAs<MemberPointerType>())
4393 CanTy = ResTypeMPtr->getPointeeType();
4394 else
4395 done = true;
4396 if (CanTy.isVolatileQualified())
4397 VRQuals.addVolatile();
4398 if (CanTy.isRestrictQualified())
4399 VRQuals.addRestrict();
4400 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4401 return VRQuals;
4402 }
4403 }
4404 }
4405 return VRQuals;
4406}
4407
Douglas Gregord08452f2008-11-19 15:42:04 +00004408/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4409/// operator overloads to the candidate set (C++ [over.built]), based
4410/// on the operator @p Op and the arguments given. For example, if the
4411/// operator is a binary '+', this routine might add "int
4412/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004413void
Mike Stump11289f42009-09-09 15:08:12 +00004414Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004415 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004416 Expr **Args, unsigned NumArgs,
4417 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004418 // The set of "promoted arithmetic types", which are the arithmetic
4419 // types are that preserved by promotion (C++ [over.built]p2). Note
4420 // that the first few of these types are the promoted integral
4421 // types; these types need to be first.
4422 // FIXME: What about complex?
4423 const unsigned FirstIntegralType = 0;
4424 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004425 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004426 LastPromotedIntegralType = 13;
4427 const unsigned FirstPromotedArithmeticType = 7,
4428 LastPromotedArithmeticType = 16;
4429 const unsigned NumArithmeticTypes = 16;
4430 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004431 Context.BoolTy, Context.CharTy, Context.WCharTy,
4432// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004433 Context.SignedCharTy, Context.ShortTy,
4434 Context.UnsignedCharTy, Context.UnsignedShortTy,
4435 Context.IntTy, Context.LongTy, Context.LongLongTy,
4436 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4437 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4438 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004439 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4440 "Invalid first promoted integral type");
4441 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4442 == Context.UnsignedLongLongTy &&
4443 "Invalid last promoted integral type");
4444 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4445 "Invalid first promoted arithmetic type");
4446 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4447 == Context.LongDoubleTy &&
4448 "Invalid last promoted arithmetic type");
4449
Douglas Gregora11693b2008-11-12 17:17:38 +00004450 // Find all of the types that the arguments can convert to, but only
4451 // if the operator we're looking at has built-in operator candidates
4452 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004453 Qualifiers VisibleTypeConversionsQuals;
4454 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004455 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4456 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4457
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004458 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004459 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4460 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4461 OpLoc,
4462 true,
4463 (Op == OO_Exclaim ||
4464 Op == OO_AmpAmp ||
4465 Op == OO_PipePipe),
4466 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004467
4468 bool isComparison = false;
4469 switch (Op) {
4470 case OO_None:
4471 case NUM_OVERLOADED_OPERATORS:
4472 assert(false && "Expected an overloaded operator");
4473 break;
4474
Douglas Gregord08452f2008-11-19 15:42:04 +00004475 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004476 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004477 goto UnaryStar;
4478 else
4479 goto BinaryStar;
4480 break;
4481
4482 case OO_Plus: // '+' is either unary or binary
4483 if (NumArgs == 1)
4484 goto UnaryPlus;
4485 else
4486 goto BinaryPlus;
4487 break;
4488
4489 case OO_Minus: // '-' is either unary or binary
4490 if (NumArgs == 1)
4491 goto UnaryMinus;
4492 else
4493 goto BinaryMinus;
4494 break;
4495
4496 case OO_Amp: // '&' is either unary or binary
4497 if (NumArgs == 1)
4498 goto UnaryAmp;
4499 else
4500 goto BinaryAmp;
4501
4502 case OO_PlusPlus:
4503 case OO_MinusMinus:
4504 // C++ [over.built]p3:
4505 //
4506 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4507 // is either volatile or empty, there exist candidate operator
4508 // functions of the form
4509 //
4510 // VQ T& operator++(VQ T&);
4511 // T operator++(VQ T&, int);
4512 //
4513 // C++ [over.built]p4:
4514 //
4515 // For every pair (T, VQ), where T is an arithmetic type other
4516 // than bool, and VQ is either volatile or empty, there exist
4517 // candidate operator functions of the form
4518 //
4519 // VQ T& operator--(VQ T&);
4520 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004521 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004522 Arith < NumArithmeticTypes; ++Arith) {
4523 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004524 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004525 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004526
4527 // Non-volatile version.
4528 if (NumArgs == 1)
4529 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4530 else
4531 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004532 // heuristic to reduce number of builtin candidates in the set.
4533 // Add volatile version only if there are conversions to a volatile type.
4534 if (VisibleTypeConversionsQuals.hasVolatile()) {
4535 // Volatile version
4536 ParamTypes[0]
4537 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4538 if (NumArgs == 1)
4539 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4540 else
4541 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4542 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004543 }
4544
4545 // C++ [over.built]p5:
4546 //
4547 // For every pair (T, VQ), where T is a cv-qualified or
4548 // cv-unqualified object type, and VQ is either volatile or
4549 // empty, there exist candidate operator functions of the form
4550 //
4551 // T*VQ& operator++(T*VQ&);
4552 // T*VQ& operator--(T*VQ&);
4553 // T* operator++(T*VQ&, int);
4554 // T* operator--(T*VQ&, int);
4555 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4556 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4557 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004558 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004559 continue;
4560
Mike Stump11289f42009-09-09 15:08:12 +00004561 QualType ParamTypes[2] = {
4562 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004563 };
Mike Stump11289f42009-09-09 15:08:12 +00004564
Douglas Gregord08452f2008-11-19 15:42:04 +00004565 // Without volatile
4566 if (NumArgs == 1)
4567 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4568 else
4569 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4570
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004571 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4572 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004573 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004574 ParamTypes[0]
4575 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004576 if (NumArgs == 1)
4577 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4578 else
4579 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4580 }
4581 }
4582 break;
4583
4584 UnaryStar:
4585 // C++ [over.built]p6:
4586 // For every cv-qualified or cv-unqualified object type T, there
4587 // exist candidate operator functions of the form
4588 //
4589 // T& operator*(T*);
4590 //
4591 // C++ [over.built]p7:
4592 // For every function type T, there exist candidate operator
4593 // functions of the form
4594 // T& operator*(T*);
4595 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4596 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4597 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004598 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004599 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004600 &ParamTy, Args, 1, CandidateSet);
4601 }
4602 break;
4603
4604 UnaryPlus:
4605 // C++ [over.built]p8:
4606 // For every type T, there exist candidate operator functions of
4607 // the form
4608 //
4609 // T* operator+(T*);
4610 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4611 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4612 QualType ParamTy = *Ptr;
4613 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4614 }
Mike Stump11289f42009-09-09 15:08:12 +00004615
Douglas Gregord08452f2008-11-19 15:42:04 +00004616 // Fall through
4617
4618 UnaryMinus:
4619 // C++ [over.built]p9:
4620 // For every promoted arithmetic type T, there exist candidate
4621 // operator functions of the form
4622 //
4623 // T operator+(T);
4624 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004625 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004626 Arith < LastPromotedArithmeticType; ++Arith) {
4627 QualType ArithTy = ArithmeticTypes[Arith];
4628 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4629 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004630
4631 // Extension: We also add these operators for vector types.
4632 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4633 VecEnd = CandidateTypes.vector_end();
4634 Vec != VecEnd; ++Vec) {
4635 QualType VecTy = *Vec;
4636 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4637 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004638 break;
4639
4640 case OO_Tilde:
4641 // C++ [over.built]p10:
4642 // For every promoted integral type T, there exist candidate
4643 // operator functions of the form
4644 //
4645 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004646 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004647 Int < LastPromotedIntegralType; ++Int) {
4648 QualType IntTy = ArithmeticTypes[Int];
4649 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4650 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004651
4652 // Extension: We also add this operator for vector types.
4653 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4654 VecEnd = CandidateTypes.vector_end();
4655 Vec != VecEnd; ++Vec) {
4656 QualType VecTy = *Vec;
4657 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4658 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004659 break;
4660
Douglas Gregora11693b2008-11-12 17:17:38 +00004661 case OO_New:
4662 case OO_Delete:
4663 case OO_Array_New:
4664 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004665 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004666 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004667 break;
4668
4669 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004670 UnaryAmp:
4671 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004672 // C++ [over.match.oper]p3:
4673 // -- For the operator ',', the unary operator '&', or the
4674 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004675 break;
4676
Douglas Gregor84605ae2009-08-24 13:43:27 +00004677 case OO_EqualEqual:
4678 case OO_ExclaimEqual:
4679 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004680 // For every pointer to member type T, there exist candidate operator
4681 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004682 //
4683 // bool operator==(T,T);
4684 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004685 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004686 MemPtr = CandidateTypes.member_pointer_begin(),
4687 MemPtrEnd = CandidateTypes.member_pointer_end();
4688 MemPtr != MemPtrEnd;
4689 ++MemPtr) {
4690 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4691 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4692 }
Mike Stump11289f42009-09-09 15:08:12 +00004693
Douglas Gregor84605ae2009-08-24 13:43:27 +00004694 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004695
Douglas Gregora11693b2008-11-12 17:17:38 +00004696 case OO_Less:
4697 case OO_Greater:
4698 case OO_LessEqual:
4699 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004700 // C++ [over.built]p15:
4701 //
4702 // For every pointer or enumeration type T, there exist
4703 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004704 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004705 // bool operator<(T, T);
4706 // bool operator>(T, T);
4707 // bool operator<=(T, T);
4708 // bool operator>=(T, T);
4709 // bool operator==(T, T);
4710 // bool operator!=(T, T);
4711 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4712 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4713 QualType ParamTypes[2] = { *Ptr, *Ptr };
4714 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4715 }
Mike Stump11289f42009-09-09 15:08:12 +00004716 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004717 = CandidateTypes.enumeration_begin();
4718 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4719 QualType ParamTypes[2] = { *Enum, *Enum };
4720 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4721 }
4722
4723 // Fall through.
4724 isComparison = true;
4725
Douglas Gregord08452f2008-11-19 15:42:04 +00004726 BinaryPlus:
4727 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004728 if (!isComparison) {
4729 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4730
4731 // C++ [over.built]p13:
4732 //
4733 // For every cv-qualified or cv-unqualified object type T
4734 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004735 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004736 // T* operator+(T*, ptrdiff_t);
4737 // T& operator[](T*, ptrdiff_t); [BELOW]
4738 // T* operator-(T*, ptrdiff_t);
4739 // T* operator+(ptrdiff_t, T*);
4740 // T& operator[](ptrdiff_t, T*); [BELOW]
4741 //
4742 // C++ [over.built]p14:
4743 //
4744 // For every T, where T is a pointer to object type, there
4745 // exist candidate operator functions of the form
4746 //
4747 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004748 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004749 = CandidateTypes.pointer_begin();
4750 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4751 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4752
4753 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4754 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4755
4756 if (Op == OO_Plus) {
4757 // T* operator+(ptrdiff_t, T*);
4758 ParamTypes[0] = ParamTypes[1];
4759 ParamTypes[1] = *Ptr;
4760 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4761 } else {
4762 // ptrdiff_t operator-(T, T);
4763 ParamTypes[1] = *Ptr;
4764 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4765 Args, 2, CandidateSet);
4766 }
4767 }
4768 }
4769 // Fall through
4770
Douglas Gregora11693b2008-11-12 17:17:38 +00004771 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004772 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004773 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004774 // C++ [over.built]p12:
4775 //
4776 // For every pair of promoted arithmetic types L and R, there
4777 // exist candidate operator functions of the form
4778 //
4779 // LR operator*(L, R);
4780 // LR operator/(L, R);
4781 // LR operator+(L, R);
4782 // LR operator-(L, R);
4783 // bool operator<(L, R);
4784 // bool operator>(L, R);
4785 // bool operator<=(L, R);
4786 // bool operator>=(L, R);
4787 // bool operator==(L, R);
4788 // bool operator!=(L, R);
4789 //
4790 // where LR is the result of the usual arithmetic conversions
4791 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004792 //
4793 // C++ [over.built]p24:
4794 //
4795 // For every pair of promoted arithmetic types L and R, there exist
4796 // candidate operator functions of the form
4797 //
4798 // LR operator?(bool, L, R);
4799 //
4800 // where LR is the result of the usual arithmetic conversions
4801 // between types L and R.
4802 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004803 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004804 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004805 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004806 Right < LastPromotedArithmeticType; ++Right) {
4807 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004808 QualType Result
4809 = isComparison
4810 ? Context.BoolTy
4811 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004812 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4813 }
4814 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004815
4816 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4817 // conditional operator for vector types.
4818 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4819 Vec1End = CandidateTypes.vector_end();
4820 Vec1 != Vec1End; ++Vec1)
4821 for (BuiltinCandidateTypeSet::iterator
4822 Vec2 = CandidateTypes.vector_begin(),
4823 Vec2End = CandidateTypes.vector_end();
4824 Vec2 != Vec2End; ++Vec2) {
4825 QualType LandR[2] = { *Vec1, *Vec2 };
4826 QualType Result;
4827 if (isComparison)
4828 Result = Context.BoolTy;
4829 else {
4830 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4831 Result = *Vec1;
4832 else
4833 Result = *Vec2;
4834 }
4835
4836 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4837 }
4838
Douglas Gregora11693b2008-11-12 17:17:38 +00004839 break;
4840
4841 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004842 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004843 case OO_Caret:
4844 case OO_Pipe:
4845 case OO_LessLess:
4846 case OO_GreaterGreater:
4847 // C++ [over.built]p17:
4848 //
4849 // For every pair of promoted integral types L and R, there
4850 // exist candidate operator functions of the form
4851 //
4852 // LR operator%(L, R);
4853 // LR operator&(L, R);
4854 // LR operator^(L, R);
4855 // LR operator|(L, R);
4856 // L operator<<(L, R);
4857 // L operator>>(L, R);
4858 //
4859 // where LR is the result of the usual arithmetic conversions
4860 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004861 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004862 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004863 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004864 Right < LastPromotedIntegralType; ++Right) {
4865 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4866 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4867 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004868 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004869 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4870 }
4871 }
4872 break;
4873
4874 case OO_Equal:
4875 // C++ [over.built]p20:
4876 //
4877 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004878 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004879 // empty, there exist candidate operator functions of the form
4880 //
4881 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004882 for (BuiltinCandidateTypeSet::iterator
4883 Enum = CandidateTypes.enumeration_begin(),
4884 EnumEnd = CandidateTypes.enumeration_end();
4885 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004886 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004887 CandidateSet);
4888 for (BuiltinCandidateTypeSet::iterator
4889 MemPtr = CandidateTypes.member_pointer_begin(),
4890 MemPtrEnd = CandidateTypes.member_pointer_end();
4891 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004892 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004893 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004894
4895 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004896
4897 case OO_PlusEqual:
4898 case OO_MinusEqual:
4899 // C++ [over.built]p19:
4900 //
4901 // For every pair (T, VQ), where T is any type and VQ is either
4902 // volatile or empty, there exist candidate operator functions
4903 // of the form
4904 //
4905 // T*VQ& operator=(T*VQ&, T*);
4906 //
4907 // C++ [over.built]p21:
4908 //
4909 // For every pair (T, VQ), where T is a cv-qualified or
4910 // cv-unqualified object type and VQ is either volatile or
4911 // empty, there exist candidate operator functions of the form
4912 //
4913 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4914 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4915 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4916 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4917 QualType ParamTypes[2];
4918 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4919
4920 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004921 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004922 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4923 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004924
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004925 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4926 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004927 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004928 ParamTypes[0]
4929 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004930 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4931 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004932 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004933 }
4934 // Fall through.
4935
4936 case OO_StarEqual:
4937 case OO_SlashEqual:
4938 // C++ [over.built]p18:
4939 //
4940 // For every triple (L, VQ, R), where L is an arithmetic type,
4941 // VQ is either volatile or empty, and R is a promoted
4942 // arithmetic type, there exist candidate operator functions of
4943 // the form
4944 //
4945 // VQ L& operator=(VQ L&, R);
4946 // VQ L& operator*=(VQ L&, R);
4947 // VQ L& operator/=(VQ L&, R);
4948 // VQ L& operator+=(VQ L&, R);
4949 // VQ L& operator-=(VQ L&, R);
4950 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004951 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004952 Right < LastPromotedArithmeticType; ++Right) {
4953 QualType ParamTypes[2];
4954 ParamTypes[1] = ArithmeticTypes[Right];
4955
4956 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004957 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004958 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4959 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004960
4961 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004962 if (VisibleTypeConversionsQuals.hasVolatile()) {
4963 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4964 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4965 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4966 /*IsAssigmentOperator=*/Op == OO_Equal);
4967 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004968 }
4969 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004970
4971 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4972 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4973 Vec1End = CandidateTypes.vector_end();
4974 Vec1 != Vec1End; ++Vec1)
4975 for (BuiltinCandidateTypeSet::iterator
4976 Vec2 = CandidateTypes.vector_begin(),
4977 Vec2End = CandidateTypes.vector_end();
4978 Vec2 != Vec2End; ++Vec2) {
4979 QualType ParamTypes[2];
4980 ParamTypes[1] = *Vec2;
4981 // Add this built-in operator as a candidate (VQ is empty).
4982 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4983 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4984 /*IsAssigmentOperator=*/Op == OO_Equal);
4985
4986 // Add this built-in operator as a candidate (VQ is 'volatile').
4987 if (VisibleTypeConversionsQuals.hasVolatile()) {
4988 ParamTypes[0] = Context.getVolatileType(*Vec1);
4989 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4990 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4991 /*IsAssigmentOperator=*/Op == OO_Equal);
4992 }
4993 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004994 break;
4995
4996 case OO_PercentEqual:
4997 case OO_LessLessEqual:
4998 case OO_GreaterGreaterEqual:
4999 case OO_AmpEqual:
5000 case OO_CaretEqual:
5001 case OO_PipeEqual:
5002 // C++ [over.built]p22:
5003 //
5004 // For every triple (L, VQ, R), where L is an integral type, VQ
5005 // is either volatile or empty, and R is a promoted integral
5006 // type, there exist candidate operator functions of the form
5007 //
5008 // VQ L& operator%=(VQ L&, R);
5009 // VQ L& operator<<=(VQ L&, R);
5010 // VQ L& operator>>=(VQ L&, R);
5011 // VQ L& operator&=(VQ L&, R);
5012 // VQ L& operator^=(VQ L&, R);
5013 // VQ L& operator|=(VQ L&, R);
5014 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005015 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005016 Right < LastPromotedIntegralType; ++Right) {
5017 QualType ParamTypes[2];
5018 ParamTypes[1] = ArithmeticTypes[Right];
5019
5020 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005021 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005022 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005023 if (VisibleTypeConversionsQuals.hasVolatile()) {
5024 // Add this built-in operator as a candidate (VQ is 'volatile').
5025 ParamTypes[0] = ArithmeticTypes[Left];
5026 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5027 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5028 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5029 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005030 }
5031 }
5032 break;
5033
Douglas Gregord08452f2008-11-19 15:42:04 +00005034 case OO_Exclaim: {
5035 // C++ [over.operator]p23:
5036 //
5037 // There also exist candidate operator functions of the form
5038 //
Mike Stump11289f42009-09-09 15:08:12 +00005039 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005040 // bool operator&&(bool, bool); [BELOW]
5041 // bool operator||(bool, bool); [BELOW]
5042 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005043 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5044 /*IsAssignmentOperator=*/false,
5045 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005046 break;
5047 }
5048
Douglas Gregora11693b2008-11-12 17:17:38 +00005049 case OO_AmpAmp:
5050 case OO_PipePipe: {
5051 // C++ [over.operator]p23:
5052 //
5053 // There also exist candidate operator functions of the form
5054 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005055 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005056 // bool operator&&(bool, bool);
5057 // bool operator||(bool, bool);
5058 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005059 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5060 /*IsAssignmentOperator=*/false,
5061 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005062 break;
5063 }
5064
5065 case OO_Subscript:
5066 // C++ [over.built]p13:
5067 //
5068 // For every cv-qualified or cv-unqualified object type T there
5069 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005070 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005071 // T* operator+(T*, ptrdiff_t); [ABOVE]
5072 // T& operator[](T*, ptrdiff_t);
5073 // T* operator-(T*, ptrdiff_t); [ABOVE]
5074 // T* operator+(ptrdiff_t, T*); [ABOVE]
5075 // T& operator[](ptrdiff_t, T*);
5076 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5077 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5078 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005079 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005080 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005081
5082 // T& operator[](T*, ptrdiff_t)
5083 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5084
5085 // T& operator[](ptrdiff_t, T*);
5086 ParamTypes[0] = ParamTypes[1];
5087 ParamTypes[1] = *Ptr;
5088 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005089 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005090 break;
5091
5092 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005093 // C++ [over.built]p11:
5094 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5095 // C1 is the same type as C2 or is a derived class of C2, T is an object
5096 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5097 // there exist candidate operator functions of the form
5098 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5099 // where CV12 is the union of CV1 and CV2.
5100 {
5101 for (BuiltinCandidateTypeSet::iterator Ptr =
5102 CandidateTypes.pointer_begin();
5103 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5104 QualType C1Ty = (*Ptr);
5105 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005106 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005107 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5108 if (!isa<RecordType>(C1))
5109 continue;
5110 // heuristic to reduce number of builtin candidates in the set.
5111 // Add volatile/restrict version only if there are conversions to a
5112 // volatile/restrict type.
5113 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5114 continue;
5115 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5116 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005117 for (BuiltinCandidateTypeSet::iterator
5118 MemPtr = CandidateTypes.member_pointer_begin(),
5119 MemPtrEnd = CandidateTypes.member_pointer_end();
5120 MemPtr != MemPtrEnd; ++MemPtr) {
5121 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5122 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005123 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005124 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5125 break;
5126 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5127 // build CV12 T&
5128 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005129 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5130 T.isVolatileQualified())
5131 continue;
5132 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5133 T.isRestrictQualified())
5134 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005135 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005136 QualType ResultTy = Context.getLValueReferenceType(T);
5137 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5138 }
5139 }
5140 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005141 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005142
5143 case OO_Conditional:
5144 // Note that we don't consider the first argument, since it has been
5145 // contextually converted to bool long ago. The candidates below are
5146 // therefore added as binary.
5147 //
5148 // C++ [over.built]p24:
5149 // For every type T, where T is a pointer or pointer-to-member type,
5150 // there exist candidate operator functions of the form
5151 //
5152 // T operator?(bool, T, T);
5153 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005154 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5155 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5156 QualType ParamTypes[2] = { *Ptr, *Ptr };
5157 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5158 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005159 for (BuiltinCandidateTypeSet::iterator Ptr =
5160 CandidateTypes.member_pointer_begin(),
5161 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5162 QualType ParamTypes[2] = { *Ptr, *Ptr };
5163 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5164 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005165 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005166 }
5167}
5168
Douglas Gregore254f902009-02-04 00:32:51 +00005169/// \brief Add function candidates found via argument-dependent lookup
5170/// to the set of overloading candidates.
5171///
5172/// This routine performs argument-dependent name lookup based on the
5173/// given function name (which may also be an operator name) and adds
5174/// all of the overload candidates found by ADL to the overload
5175/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005176void
Douglas Gregore254f902009-02-04 00:32:51 +00005177Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005178 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005179 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005180 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005181 OverloadCandidateSet& CandidateSet,
5182 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005183 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005184
John McCall91f61fc2010-01-26 06:04:06 +00005185 // FIXME: This approach for uniquing ADL results (and removing
5186 // redundant candidates from the set) relies on pointer-equality,
5187 // which means we need to key off the canonical decl. However,
5188 // always going back to the canonical decl might not get us the
5189 // right set of default arguments. What default arguments are
5190 // we supposed to consider on ADL candidates, anyway?
5191
Douglas Gregorcabea402009-09-22 15:41:20 +00005192 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005193 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005194
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005195 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005196 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5197 CandEnd = CandidateSet.end();
5198 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005199 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005200 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005201 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005202 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005203 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005204
5205 // For each of the ADL candidates we found, add it to the overload
5206 // set.
John McCall8fe68082010-01-26 07:16:45 +00005207 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005208 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005209 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005210 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005211 continue;
5212
John McCalla0296f72010-03-19 07:35:19 +00005213 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005214 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005215 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005216 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005217 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005218 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005219 }
Douglas Gregore254f902009-02-04 00:32:51 +00005220}
5221
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005222/// isBetterOverloadCandidate - Determines whether the first overload
5223/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005224bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005225Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00005226 const OverloadCandidate& Cand2,
5227 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005228 // Define viable functions to be better candidates than non-viable
5229 // functions.
5230 if (!Cand2.Viable)
5231 return Cand1.Viable;
5232 else if (!Cand1.Viable)
5233 return false;
5234
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005235 // C++ [over.match.best]p1:
5236 //
5237 // -- if F is a static member function, ICS1(F) is defined such
5238 // that ICS1(F) is neither better nor worse than ICS1(G) for
5239 // any function G, and, symmetrically, ICS1(G) is neither
5240 // better nor worse than ICS1(F).
5241 unsigned StartArg = 0;
5242 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5243 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005244
Douglas Gregord3cb3562009-07-07 23:38:56 +00005245 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005246 // A viable function F1 is defined to be a better function than another
5247 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005248 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005249 unsigned NumArgs = Cand1.Conversions.size();
5250 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5251 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005252 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005253 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5254 Cand2.Conversions[ArgIdx])) {
5255 case ImplicitConversionSequence::Better:
5256 // Cand1 has a better conversion sequence.
5257 HasBetterConversion = true;
5258 break;
5259
5260 case ImplicitConversionSequence::Worse:
5261 // Cand1 can't be better than Cand2.
5262 return false;
5263
5264 case ImplicitConversionSequence::Indistinguishable:
5265 // Do nothing.
5266 break;
5267 }
5268 }
5269
Mike Stump11289f42009-09-09 15:08:12 +00005270 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005271 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005272 if (HasBetterConversion)
5273 return true;
5274
Mike Stump11289f42009-09-09 15:08:12 +00005275 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005276 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005277 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005278 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5279 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005280
5281 // -- F1 and F2 are function template specializations, and the function
5282 // template for F1 is more specialized than the template for F2
5283 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005284 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005285 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5286 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005287 if (FunctionTemplateDecl *BetterTemplate
5288 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5289 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005290 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005291 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5292 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005293 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005294
Douglas Gregora1f013e2008-11-07 22:36:19 +00005295 // -- the context is an initialization by user-defined conversion
5296 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5297 // from the return type of F1 to the destination type (i.e.,
5298 // the type of the entity being initialized) is a better
5299 // conversion sequence than the standard conversion sequence
5300 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005301 if (Cand1.Function && Cand2.Function &&
5302 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005303 isa<CXXConversionDecl>(Cand2.Function)) {
5304 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5305 Cand2.FinalConversion)) {
5306 case ImplicitConversionSequence::Better:
5307 // Cand1 has a better conversion sequence.
5308 return true;
5309
5310 case ImplicitConversionSequence::Worse:
5311 // Cand1 can't be better than Cand2.
5312 return false;
5313
5314 case ImplicitConversionSequence::Indistinguishable:
5315 // Do nothing
5316 break;
5317 }
5318 }
5319
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005320 return false;
5321}
5322
Mike Stump11289f42009-09-09 15:08:12 +00005323/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005324/// within an overload candidate set.
5325///
5326/// \param CandidateSet the set of candidate functions.
5327///
5328/// \param Loc the location of the function name (or operator symbol) for
5329/// which overload resolution occurs.
5330///
Mike Stump11289f42009-09-09 15:08:12 +00005331/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005332/// function, Best points to the candidate function found.
5333///
5334/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005335OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5336 SourceLocation Loc,
5337 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005338 // Find the best viable function.
5339 Best = CandidateSet.end();
5340 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5341 Cand != CandidateSet.end(); ++Cand) {
5342 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005343 if (Best == CandidateSet.end() ||
5344 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005345 Best = Cand;
5346 }
5347 }
5348
5349 // If we didn't find any viable functions, abort.
5350 if (Best == CandidateSet.end())
5351 return OR_No_Viable_Function;
5352
5353 // Make sure that this function is better than every other viable
5354 // function. If not, we have an ambiguity.
5355 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5356 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005357 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005358 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005359 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005360 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005361 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005362 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005363 }
Mike Stump11289f42009-09-09 15:08:12 +00005364
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005365 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005366 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005367 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005368 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005369 return OR_Deleted;
5370
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005371 // C++ [basic.def.odr]p2:
5372 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005373 // when referred to from a potentially-evaluated expression. [Note: this
5374 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005375 // (clause 13), user-defined conversions (12.3.2), allocation function for
5376 // placement new (5.3.4), as well as non-default initialization (8.5).
5377 if (Best->Function)
5378 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005379 return OR_Success;
5380}
5381
John McCall53262c92010-01-12 02:15:36 +00005382namespace {
5383
5384enum OverloadCandidateKind {
5385 oc_function,
5386 oc_method,
5387 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005388 oc_function_template,
5389 oc_method_template,
5390 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005391 oc_implicit_default_constructor,
5392 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005393 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005394};
5395
John McCalle1ac8d12010-01-13 00:25:19 +00005396OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5397 FunctionDecl *Fn,
5398 std::string &Description) {
5399 bool isTemplate = false;
5400
5401 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5402 isTemplate = true;
5403 Description = S.getTemplateArgumentBindingsText(
5404 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5405 }
John McCallfd0b2f82010-01-06 09:43:14 +00005406
5407 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005408 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005409 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005410
John McCall53262c92010-01-12 02:15:36 +00005411 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5412 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005413 }
5414
5415 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5416 // This actually gets spelled 'candidate function' for now, but
5417 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005418 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005419 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005420
5421 assert(Meth->isCopyAssignment()
5422 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005423 return oc_implicit_copy_assignment;
5424 }
5425
John McCalle1ac8d12010-01-13 00:25:19 +00005426 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005427}
5428
5429} // end anonymous namespace
5430
5431// Notes the location of an overload candidate.
5432void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005433 std::string FnDesc;
5434 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5435 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5436 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005437}
5438
John McCall0d1da222010-01-12 00:44:57 +00005439/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5440/// "lead" diagnostic; it will be given two arguments, the source and
5441/// target types of the conversion.
5442void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5443 SourceLocation CaretLoc,
5444 const PartialDiagnostic &PDiag) {
5445 Diag(CaretLoc, PDiag)
5446 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5447 for (AmbiguousConversionSequence::const_iterator
5448 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5449 NoteOverloadCandidate(*I);
5450 }
John McCall12f97bc2010-01-08 04:41:39 +00005451}
5452
John McCall0d1da222010-01-12 00:44:57 +00005453namespace {
5454
John McCall6a61b522010-01-13 09:16:55 +00005455void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5456 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5457 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005458 assert(Cand->Function && "for now, candidate must be a function");
5459 FunctionDecl *Fn = Cand->Function;
5460
5461 // There's a conversion slot for the object argument if this is a
5462 // non-constructor method. Note that 'I' corresponds the
5463 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005464 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005465 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005466 if (I == 0)
5467 isObjectArgument = true;
5468 else
5469 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005470 }
5471
John McCalle1ac8d12010-01-13 00:25:19 +00005472 std::string FnDesc;
5473 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5474
John McCall6a61b522010-01-13 09:16:55 +00005475 Expr *FromExpr = Conv.Bad.FromExpr;
5476 QualType FromTy = Conv.Bad.getFromType();
5477 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005478
John McCallfb7ad0f2010-02-02 02:42:52 +00005479 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005480 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005481 Expr *E = FromExpr->IgnoreParens();
5482 if (isa<UnaryOperator>(E))
5483 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005484 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005485
5486 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5487 << (unsigned) FnKind << FnDesc
5488 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5489 << ToTy << Name << I+1;
5490 return;
5491 }
5492
John McCall6d174642010-01-23 08:10:49 +00005493 // Do some hand-waving analysis to see if the non-viability is due
5494 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005495 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5496 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5497 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5498 CToTy = RT->getPointeeType();
5499 else {
5500 // TODO: detect and diagnose the full richness of const mismatches.
5501 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5502 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5503 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5504 }
5505
5506 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5507 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5508 // It is dumb that we have to do this here.
5509 while (isa<ArrayType>(CFromTy))
5510 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5511 while (isa<ArrayType>(CToTy))
5512 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5513
5514 Qualifiers FromQs = CFromTy.getQualifiers();
5515 Qualifiers ToQs = CToTy.getQualifiers();
5516
5517 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5519 << (unsigned) FnKind << FnDesc
5520 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5521 << FromTy
5522 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5523 << (unsigned) isObjectArgument << I+1;
5524 return;
5525 }
5526
5527 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5528 assert(CVR && "unexpected qualifiers mismatch");
5529
5530 if (isObjectArgument) {
5531 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5532 << (unsigned) FnKind << FnDesc
5533 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5534 << FromTy << (CVR - 1);
5535 } else {
5536 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5537 << (unsigned) FnKind << FnDesc
5538 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5539 << FromTy << (CVR - 1) << I+1;
5540 }
5541 return;
5542 }
5543
John McCall6d174642010-01-23 08:10:49 +00005544 // Diagnose references or pointers to incomplete types differently,
5545 // since it's far from impossible that the incompleteness triggered
5546 // the failure.
5547 QualType TempFromTy = FromTy.getNonReferenceType();
5548 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5549 TempFromTy = PTy->getPointeeType();
5550 if (TempFromTy->isIncompleteType()) {
5551 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5552 << (unsigned) FnKind << FnDesc
5553 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5554 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5555 return;
5556 }
5557
Douglas Gregor56f2e342010-06-30 23:01:39 +00005558 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005559 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005560 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5561 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5562 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5563 FromPtrTy->getPointeeType()) &&
5564 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5565 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5566 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5567 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005568 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005569 }
5570 } else if (const ObjCObjectPointerType *FromPtrTy
5571 = FromTy->getAs<ObjCObjectPointerType>()) {
5572 if (const ObjCObjectPointerType *ToPtrTy
5573 = ToTy->getAs<ObjCObjectPointerType>())
5574 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5575 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5576 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5577 FromPtrTy->getPointeeType()) &&
5578 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005579 BaseToDerivedConversion = 2;
5580 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5581 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5582 !FromTy->isIncompleteType() &&
5583 !ToRefTy->getPointeeType()->isIncompleteType() &&
5584 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5585 BaseToDerivedConversion = 3;
5586 }
5587
5588 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005589 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005590 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005591 << (unsigned) FnKind << FnDesc
5592 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005593 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005594 << FromTy << ToTy << I+1;
5595 return;
5596 }
5597
John McCall47000992010-01-14 03:28:57 +00005598 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005599 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5600 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005601 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005602 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005603}
5604
5605void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5606 unsigned NumFormalArgs) {
5607 // TODO: treat calls to a missing default constructor as a special case
5608
5609 FunctionDecl *Fn = Cand->Function;
5610 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5611
5612 unsigned MinParams = Fn->getMinRequiredArguments();
5613
5614 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005615 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005616 unsigned mode, modeCount;
5617 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005618 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5619 (Cand->FailureKind == ovl_fail_bad_deduction &&
5620 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005621 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5622 mode = 0; // "at least"
5623 else
5624 mode = 2; // "exactly"
5625 modeCount = MinParams;
5626 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005627 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5628 (Cand->FailureKind == ovl_fail_bad_deduction &&
5629 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005630 if (MinParams != FnTy->getNumArgs())
5631 mode = 1; // "at most"
5632 else
5633 mode = 2; // "exactly"
5634 modeCount = FnTy->getNumArgs();
5635 }
5636
5637 std::string Description;
5638 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5639
5640 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005641 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5642 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005643}
5644
John McCall8b9ed552010-02-01 18:53:26 +00005645/// Diagnose a failed template-argument deduction.
5646void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5647 Expr **Args, unsigned NumArgs) {
5648 FunctionDecl *Fn = Cand->Function; // pattern
5649
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005650 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005651 NamedDecl *ParamD;
5652 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5653 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5654 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005655 switch (Cand->DeductionFailure.Result) {
5656 case Sema::TDK_Success:
5657 llvm_unreachable("TDK_success while diagnosing bad deduction");
5658
5659 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005660 assert(ParamD && "no parameter found for incomplete deduction result");
5661 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5662 << ParamD->getDeclName();
5663 return;
5664 }
5665
John McCall42d7d192010-08-05 09:05:08 +00005666 case Sema::TDK_Underqualified: {
5667 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5668 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5669
5670 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5671
5672 // Param will have been canonicalized, but it should just be a
5673 // qualified version of ParamD, so move the qualifiers to that.
5674 QualifierCollector Qs(S.Context);
5675 Qs.strip(Param);
5676 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5677 assert(S.Context.hasSameType(Param, NonCanonParam));
5678
5679 // Arg has also been canonicalized, but there's nothing we can do
5680 // about that. It also doesn't matter as much, because it won't
5681 // have any template parameters in it (because deduction isn't
5682 // done on dependent types).
5683 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5684
5685 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5686 << ParamD->getDeclName() << Arg << NonCanonParam;
5687 return;
5688 }
5689
5690 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005691 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005692 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005693 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005694 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005695 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005696 which = 1;
5697 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005698 which = 2;
5699 }
5700
5701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5702 << which << ParamD->getDeclName()
5703 << *Cand->DeductionFailure.getFirstArg()
5704 << *Cand->DeductionFailure.getSecondArg();
5705 return;
5706 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005707
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005708 case Sema::TDK_InvalidExplicitArguments:
5709 assert(ParamD && "no parameter found for invalid explicit arguments");
5710 if (ParamD->getDeclName())
5711 S.Diag(Fn->getLocation(),
5712 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5713 << ParamD->getDeclName();
5714 else {
5715 int index = 0;
5716 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5717 index = TTP->getIndex();
5718 else if (NonTypeTemplateParmDecl *NTTP
5719 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5720 index = NTTP->getIndex();
5721 else
5722 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5723 S.Diag(Fn->getLocation(),
5724 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5725 << (index + 1);
5726 }
5727 return;
5728
Douglas Gregor02eb4832010-05-08 18:13:28 +00005729 case Sema::TDK_TooManyArguments:
5730 case Sema::TDK_TooFewArguments:
5731 DiagnoseArityMismatch(S, Cand, NumArgs);
5732 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005733
5734 case Sema::TDK_InstantiationDepth:
5735 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5736 return;
5737
5738 case Sema::TDK_SubstitutionFailure: {
5739 std::string ArgString;
5740 if (TemplateArgumentList *Args
5741 = Cand->DeductionFailure.getTemplateArgumentList())
5742 ArgString = S.getTemplateArgumentBindingsText(
5743 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5744 *Args);
5745 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5746 << ArgString;
5747 return;
5748 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005749
John McCall8b9ed552010-02-01 18:53:26 +00005750 // TODO: diagnose these individually, then kill off
5751 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005752 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005753 case Sema::TDK_FailedOverloadResolution:
5754 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5755 return;
5756 }
5757}
5758
5759/// Generates a 'note' diagnostic for an overload candidate. We've
5760/// already generated a primary error at the call site.
5761///
5762/// It really does need to be a single diagnostic with its caret
5763/// pointed at the candidate declaration. Yes, this creates some
5764/// major challenges of technical writing. Yes, this makes pointing
5765/// out problems with specific arguments quite awkward. It's still
5766/// better than generating twenty screens of text for every failed
5767/// overload.
5768///
5769/// It would be great to be able to express per-candidate problems
5770/// more richly for those diagnostic clients that cared, but we'd
5771/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005772void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5773 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005774 FunctionDecl *Fn = Cand->Function;
5775
John McCall12f97bc2010-01-08 04:41:39 +00005776 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005777 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005778 std::string FnDesc;
5779 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005780
5781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005782 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005783 return;
John McCall12f97bc2010-01-08 04:41:39 +00005784 }
5785
John McCalle1ac8d12010-01-13 00:25:19 +00005786 // We don't really have anything else to say about viable candidates.
5787 if (Cand->Viable) {
5788 S.NoteOverloadCandidate(Fn);
5789 return;
5790 }
John McCall0d1da222010-01-12 00:44:57 +00005791
John McCall6a61b522010-01-13 09:16:55 +00005792 switch (Cand->FailureKind) {
5793 case ovl_fail_too_many_arguments:
5794 case ovl_fail_too_few_arguments:
5795 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005796
John McCall6a61b522010-01-13 09:16:55 +00005797 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005798 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5799
John McCallfe796dd2010-01-23 05:17:32 +00005800 case ovl_fail_trivial_conversion:
5801 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005802 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005803 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005804
John McCall65eb8792010-02-25 01:37:24 +00005805 case ovl_fail_bad_conversion: {
5806 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5807 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005808 if (Cand->Conversions[I].isBad())
5809 return DiagnoseBadConversion(S, Cand, I);
5810
5811 // FIXME: this currently happens when we're called from SemaInit
5812 // when user-conversion overload fails. Figure out how to handle
5813 // those conditions and diagnose them well.
5814 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005815 }
John McCall65eb8792010-02-25 01:37:24 +00005816 }
John McCalld3224162010-01-08 00:58:21 +00005817}
5818
5819void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5820 // Desugar the type of the surrogate down to a function type,
5821 // retaining as many typedefs as possible while still showing
5822 // the function type (and, therefore, its parameter types).
5823 QualType FnType = Cand->Surrogate->getConversionType();
5824 bool isLValueReference = false;
5825 bool isRValueReference = false;
5826 bool isPointer = false;
5827 if (const LValueReferenceType *FnTypeRef =
5828 FnType->getAs<LValueReferenceType>()) {
5829 FnType = FnTypeRef->getPointeeType();
5830 isLValueReference = true;
5831 } else if (const RValueReferenceType *FnTypeRef =
5832 FnType->getAs<RValueReferenceType>()) {
5833 FnType = FnTypeRef->getPointeeType();
5834 isRValueReference = true;
5835 }
5836 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5837 FnType = FnTypePtr->getPointeeType();
5838 isPointer = true;
5839 }
5840 // Desugar down to a function type.
5841 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5842 // Reconstruct the pointer/reference as appropriate.
5843 if (isPointer) FnType = S.Context.getPointerType(FnType);
5844 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5845 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5846
5847 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5848 << FnType;
5849}
5850
5851void NoteBuiltinOperatorCandidate(Sema &S,
5852 const char *Opc,
5853 SourceLocation OpLoc,
5854 OverloadCandidate *Cand) {
5855 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5856 std::string TypeStr("operator");
5857 TypeStr += Opc;
5858 TypeStr += "(";
5859 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5860 if (Cand->Conversions.size() == 1) {
5861 TypeStr += ")";
5862 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5863 } else {
5864 TypeStr += ", ";
5865 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5866 TypeStr += ")";
5867 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5868 }
5869}
5870
5871void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5872 OverloadCandidate *Cand) {
5873 unsigned NoOperands = Cand->Conversions.size();
5874 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5875 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005876 if (ICS.isBad()) break; // all meaningless after first invalid
5877 if (!ICS.isAmbiguous()) continue;
5878
5879 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005880 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005881 }
5882}
5883
John McCall3712d9e2010-01-15 23:32:50 +00005884SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5885 if (Cand->Function)
5886 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005887 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005888 return Cand->Surrogate->getLocation();
5889 return SourceLocation();
5890}
5891
John McCallad2587a2010-01-12 00:48:53 +00005892struct CompareOverloadCandidatesForDisplay {
5893 Sema &S;
5894 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005895
5896 bool operator()(const OverloadCandidate *L,
5897 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005898 // Fast-path this check.
5899 if (L == R) return false;
5900
John McCall12f97bc2010-01-08 04:41:39 +00005901 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005902 if (L->Viable) {
5903 if (!R->Viable) return true;
5904
5905 // TODO: introduce a tri-valued comparison for overload
5906 // candidates. Would be more worthwhile if we had a sort
5907 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005908 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5909 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005910 } else if (R->Viable)
5911 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005912
John McCall3712d9e2010-01-15 23:32:50 +00005913 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005914
John McCall3712d9e2010-01-15 23:32:50 +00005915 // Criteria by which we can sort non-viable candidates:
5916 if (!L->Viable) {
5917 // 1. Arity mismatches come after other candidates.
5918 if (L->FailureKind == ovl_fail_too_many_arguments ||
5919 L->FailureKind == ovl_fail_too_few_arguments)
5920 return false;
5921 if (R->FailureKind == ovl_fail_too_many_arguments ||
5922 R->FailureKind == ovl_fail_too_few_arguments)
5923 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005924
John McCallfe796dd2010-01-23 05:17:32 +00005925 // 2. Bad conversions come first and are ordered by the number
5926 // of bad conversions and quality of good conversions.
5927 if (L->FailureKind == ovl_fail_bad_conversion) {
5928 if (R->FailureKind != ovl_fail_bad_conversion)
5929 return true;
5930
5931 // If there's any ordering between the defined conversions...
5932 // FIXME: this might not be transitive.
5933 assert(L->Conversions.size() == R->Conversions.size());
5934
5935 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005936 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5937 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005938 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5939 R->Conversions[I])) {
5940 case ImplicitConversionSequence::Better:
5941 leftBetter++;
5942 break;
5943
5944 case ImplicitConversionSequence::Worse:
5945 leftBetter--;
5946 break;
5947
5948 case ImplicitConversionSequence::Indistinguishable:
5949 break;
5950 }
5951 }
5952 if (leftBetter > 0) return true;
5953 if (leftBetter < 0) return false;
5954
5955 } else if (R->FailureKind == ovl_fail_bad_conversion)
5956 return false;
5957
John McCall3712d9e2010-01-15 23:32:50 +00005958 // TODO: others?
5959 }
5960
5961 // Sort everything else by location.
5962 SourceLocation LLoc = GetLocationForCandidate(L);
5963 SourceLocation RLoc = GetLocationForCandidate(R);
5964
5965 // Put candidates without locations (e.g. builtins) at the end.
5966 if (LLoc.isInvalid()) return false;
5967 if (RLoc.isInvalid()) return true;
5968
5969 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005970 }
5971};
5972
John McCallfe796dd2010-01-23 05:17:32 +00005973/// CompleteNonViableCandidate - Normally, overload resolution only
5974/// computes up to the first
5975void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5976 Expr **Args, unsigned NumArgs) {
5977 assert(!Cand->Viable);
5978
5979 // Don't do anything on failures other than bad conversion.
5980 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5981
5982 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005983 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005984 unsigned ConvCount = Cand->Conversions.size();
5985 while (true) {
5986 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5987 ConvIdx++;
5988 if (Cand->Conversions[ConvIdx - 1].isBad())
5989 break;
5990 }
5991
5992 if (ConvIdx == ConvCount)
5993 return;
5994
John McCall65eb8792010-02-25 01:37:24 +00005995 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5996 "remaining conversion is initialized?");
5997
Douglas Gregoradc7a702010-04-16 17:45:54 +00005998 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005999 // operation somehow.
6000 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006001
6002 const FunctionProtoType* Proto;
6003 unsigned ArgIdx = ConvIdx;
6004
6005 if (Cand->IsSurrogate) {
6006 QualType ConvType
6007 = Cand->Surrogate->getConversionType().getNonReferenceType();
6008 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6009 ConvType = ConvPtrType->getPointeeType();
6010 Proto = ConvType->getAs<FunctionProtoType>();
6011 ArgIdx--;
6012 } else if (Cand->Function) {
6013 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6014 if (isa<CXXMethodDecl>(Cand->Function) &&
6015 !isa<CXXConstructorDecl>(Cand->Function))
6016 ArgIdx--;
6017 } else {
6018 // Builtin binary operator with a bad first conversion.
6019 assert(ConvCount <= 3);
6020 for (; ConvIdx != ConvCount; ++ConvIdx)
6021 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006022 = TryCopyInitialization(S, Args[ConvIdx],
6023 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6024 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006025 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006026 return;
6027 }
6028
6029 // Fill in the rest of the conversions.
6030 unsigned NumArgsInProto = Proto->getNumArgs();
6031 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6032 if (ArgIdx < NumArgsInProto)
6033 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006034 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6035 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006036 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006037 else
6038 Cand->Conversions[ConvIdx].setEllipsis();
6039 }
6040}
6041
John McCalld3224162010-01-08 00:58:21 +00006042} // end anonymous namespace
6043
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006044/// PrintOverloadCandidates - When overload resolution fails, prints
6045/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006046/// set.
Mike Stump11289f42009-09-09 15:08:12 +00006047void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006048Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00006049 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00006050 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006051 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00006052 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006053 // Sort the candidates by viability and position. Sorting directly would
6054 // be prohibitive, so we make a set of pointers and sort those.
6055 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6056 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
6057 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6058 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00006059 Cand != LastCand; ++Cand) {
6060 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006061 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006062 else if (OCD == OCD_AllCandidates) {
6063 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006064 if (Cand->Function || Cand->IsSurrogate)
6065 Cands.push_back(Cand);
6066 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6067 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006068 }
6069 }
6070
John McCallad2587a2010-01-12 00:48:53 +00006071 std::sort(Cands.begin(), Cands.end(),
6072 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00006073
John McCall0d1da222010-01-12 00:44:57 +00006074 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006075
John McCall12f97bc2010-01-08 04:41:39 +00006076 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006077 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6078 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006079 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6080 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006081
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006082 // Set an arbitrary limit on the number of candidate functions we'll spam
6083 // the user with. FIXME: This limit should depend on details of the
6084 // candidate list.
6085 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6086 break;
6087 }
6088 ++CandsShown;
6089
John McCalld3224162010-01-08 00:58:21 +00006090 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00006091 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006092 else if (Cand->IsSurrogate)
6093 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006094 else {
6095 assert(Cand->Viable &&
6096 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006097 // Generally we only see ambiguities including viable builtin
6098 // operators if overload resolution got screwed up by an
6099 // ambiguous user-defined conversion.
6100 //
6101 // FIXME: It's quite possible for different conversions to see
6102 // different ambiguities, though.
6103 if (!ReportedAmbiguousConversions) {
6104 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6105 ReportedAmbiguousConversions = true;
6106 }
John McCalld3224162010-01-08 00:58:21 +00006107
John McCall0d1da222010-01-12 00:44:57 +00006108 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00006109 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006110 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006111 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006112
6113 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00006114 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006115}
6116
John McCalla0296f72010-03-19 07:35:19 +00006117static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006118 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006119 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006120
John McCalla0296f72010-03-19 07:35:19 +00006121 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006122}
6123
Douglas Gregorcd695e52008-11-10 20:40:00 +00006124/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6125/// an overloaded function (C++ [over.over]), where @p From is an
6126/// expression with overloaded function type and @p ToType is the type
6127/// we're trying to resolve to. For example:
6128///
6129/// @code
6130/// int f(double);
6131/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006132///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006133/// int (*pfd)(double) = f; // selects f(double)
6134/// @endcode
6135///
6136/// This routine returns the resulting FunctionDecl if it could be
6137/// resolved, and NULL otherwise. When @p Complain is true, this
6138/// routine will emit diagnostics if there is an error.
6139FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006140Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006141 bool Complain,
6142 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006143 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006144 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006145 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006146 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006147 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006148 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006149 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006150 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006151 FunctionType = MemTypePtr->getPointeeType();
6152 IsMember = true;
6153 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006154
Douglas Gregorcd695e52008-11-10 20:40:00 +00006155 // C++ [over.over]p1:
6156 // [...] [Note: any redundant set of parentheses surrounding the
6157 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006158 // C++ [over.over]p1:
6159 // [...] The overloaded function name can be preceded by the &
6160 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006161 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6162 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6163 if (OvlExpr->hasExplicitTemplateArgs()) {
6164 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6165 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006166 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00006167
6168 // We expect a pointer or reference to function, or a function pointer.
6169 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6170 if (!FunctionType->isFunctionType()) {
6171 if (Complain)
6172 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6173 << OvlExpr->getName() << ToType;
6174
6175 return 0;
6176 }
6177
6178 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006179
Douglas Gregorcd695e52008-11-10 20:40:00 +00006180 // Look through all of the overloaded functions, searching for one
6181 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006182 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006183 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6184
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006185 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006186 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6187 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006188 // Look through any using declarations to find the underlying function.
6189 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6190
Douglas Gregorcd695e52008-11-10 20:40:00 +00006191 // C++ [over.over]p3:
6192 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006193 // targets of type "pointer-to-function" or "reference-to-function."
6194 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006195 // type "pointer-to-member-function."
6196 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006197
Mike Stump11289f42009-09-09 15:08:12 +00006198 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006199 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006200 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006201 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006202 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006203 // static when converting to member pointer.
6204 if (Method->isStatic() == IsMember)
6205 continue;
6206 } else if (IsMember)
6207 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006208
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006209 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006210 // If the name is a function template, template argument deduction is
6211 // done (14.8.2.2), and if the argument deduction succeeds, the
6212 // resulting template argument list is used to generate a single
6213 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006214 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006215 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006216 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006217 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006218 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006219 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006220 FunctionType, Specialization, Info)) {
6221 // FIXME: make a note of the failed deduction for diagnostics.
6222 (void)Result;
6223 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006224 // FIXME: If the match isn't exact, shouldn't we just drop this as
6225 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006226 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006227 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006228 Matches.push_back(std::make_pair(I.getPair(),
6229 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006230 }
John McCalld14a8642009-11-21 08:51:07 +00006231
6232 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006233 }
Mike Stump11289f42009-09-09 15:08:12 +00006234
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006235 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006236 // Skip non-static functions when converting to pointer, and static
6237 // when converting to member pointer.
6238 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006239 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006240
6241 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006242 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006243 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006244 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006245 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006246
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006247 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006248 QualType ResultTy;
6249 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6250 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6251 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006252 Matches.push_back(std::make_pair(I.getPair(),
6253 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006254 FoundNonTemplateFunction = true;
6255 }
Mike Stump11289f42009-09-09 15:08:12 +00006256 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006257 }
6258
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006259 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006260 if (Matches.empty()) {
6261 if (Complain) {
6262 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6263 << OvlExpr->getName() << FunctionType;
6264 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6265 E = OvlExpr->decls_end();
6266 I != E; ++I)
6267 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6268 NoteOverloadCandidate(F);
6269 }
6270
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006271 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006272 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006273 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006274 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006275 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006276 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006277 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006278 return Result;
6279 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006280
6281 // C++ [over.over]p4:
6282 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006283 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006284 // [...] and any given function template specialization F1 is
6285 // eliminated if the set contains a second function template
6286 // specialization whose function template is more specialized
6287 // than the function template of F1 according to the partial
6288 // ordering rules of 14.5.5.2.
6289
6290 // The algorithm specified above is quadratic. We instead use a
6291 // two-pass algorithm (similar to the one used to identify the
6292 // best viable function in an overload set) that identifies the
6293 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006294
6295 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6296 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6297 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006298
6299 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006300 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006301 TPOC_Other, From->getLocStart(),
6302 PDiag(),
6303 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006304 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006305 PDiag(diag::note_ovl_candidate)
6306 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006307 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006308 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006309 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006310 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006311 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006312 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6313 }
John McCall58cc69d2010-01-27 01:50:18 +00006314 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006315 }
Mike Stump11289f42009-09-09 15:08:12 +00006316
Douglas Gregorfae1d712009-09-26 03:56:17 +00006317 // [...] any function template specializations in the set are
6318 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006319 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006320 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006321 ++I;
6322 else {
John McCalla0296f72010-03-19 07:35:19 +00006323 Matches[I] = Matches[--N];
6324 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006325 }
6326 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006327
Mike Stump11289f42009-09-09 15:08:12 +00006328 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006329 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006330 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006331 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006332 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006333 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006334 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006335 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6336 }
John McCalla0296f72010-03-19 07:35:19 +00006337 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006338 }
Mike Stump11289f42009-09-09 15:08:12 +00006339
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006340 // FIXME: We should probably return the same thing that BestViableFunction
6341 // returns (even if we issue the diagnostics here).
6342 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006343 << Matches[0].second->getDeclName();
6344 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6345 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006346 return 0;
6347}
6348
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006349/// \brief Given an expression that refers to an overloaded function, try to
6350/// resolve that overloaded function expression down to a single function.
6351///
6352/// This routine can only resolve template-ids that refer to a single function
6353/// template, where that template-id refers to a single template whose template
6354/// arguments are either provided by the template-id or have defaults,
6355/// as described in C++0x [temp.arg.explicit]p3.
6356FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6357 // C++ [over.over]p1:
6358 // [...] [Note: any redundant set of parentheses surrounding the
6359 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006360 // C++ [over.over]p1:
6361 // [...] The overloaded function name can be preceded by the &
6362 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006363
6364 if (From->getType() != Context.OverloadTy)
6365 return 0;
6366
6367 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006368
6369 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006370 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006371 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006372
6373 TemplateArgumentListInfo ExplicitTemplateArgs;
6374 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006375
6376 // Look through all of the overloaded functions, searching for one
6377 // whose type matches exactly.
6378 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006379 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6380 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006381 // C++0x [temp.arg.explicit]p3:
6382 // [...] In contexts where deduction is done and fails, or in contexts
6383 // where deduction is not done, if a template argument list is
6384 // specified and it, along with any default template arguments,
6385 // identifies a single function template specialization, then the
6386 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006387 FunctionTemplateDecl *FunctionTemplate
6388 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006389
6390 // C++ [over.over]p2:
6391 // If the name is a function template, template argument deduction is
6392 // done (14.8.2.2), and if the argument deduction succeeds, the
6393 // resulting template argument list is used to generate a single
6394 // function template specialization, which is added to the set of
6395 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006396 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006397 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006398 if (TemplateDeductionResult Result
6399 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6400 Specialization, Info)) {
6401 // FIXME: make a note of the failed deduction for diagnostics.
6402 (void)Result;
6403 continue;
6404 }
6405
6406 // Multiple matches; we can't resolve to a single declaration.
6407 if (Matched)
6408 return 0;
6409
6410 Matched = Specialization;
6411 }
6412
6413 return Matched;
6414}
6415
Douglas Gregorcabea402009-09-22 15:41:20 +00006416/// \brief Add a single candidate to the overload set.
6417static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006418 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006419 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006420 Expr **Args, unsigned NumArgs,
6421 OverloadCandidateSet &CandidateSet,
6422 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006423 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006424 if (isa<UsingShadowDecl>(Callee))
6425 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6426
Douglas Gregorcabea402009-09-22 15:41:20 +00006427 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006428 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006429 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006430 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006431 return;
John McCalld14a8642009-11-21 08:51:07 +00006432 }
6433
6434 if (FunctionTemplateDecl *FuncTemplate
6435 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006436 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6437 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006438 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006439 return;
6440 }
6441
6442 assert(false && "unhandled case in overloaded call candidate");
6443
6444 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006445}
6446
6447/// \brief Add the overload candidates named by callee and/or found by argument
6448/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006449void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006450 Expr **Args, unsigned NumArgs,
6451 OverloadCandidateSet &CandidateSet,
6452 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006453
6454#ifndef NDEBUG
6455 // Verify that ArgumentDependentLookup is consistent with the rules
6456 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006457 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006458 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6459 // and let Y be the lookup set produced by argument dependent
6460 // lookup (defined as follows). If X contains
6461 //
6462 // -- a declaration of a class member, or
6463 //
6464 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006465 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006466 //
6467 // -- a declaration that is neither a function or a function
6468 // template
6469 //
6470 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006471
John McCall57500772009-12-16 12:17:52 +00006472 if (ULE->requiresADL()) {
6473 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6474 E = ULE->decls_end(); I != E; ++I) {
6475 assert(!(*I)->getDeclContext()->isRecord());
6476 assert(isa<UsingShadowDecl>(*I) ||
6477 !(*I)->getDeclContext()->isFunctionOrMethod());
6478 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006479 }
6480 }
6481#endif
6482
John McCall57500772009-12-16 12:17:52 +00006483 // It would be nice to avoid this copy.
6484 TemplateArgumentListInfo TABuffer;
6485 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6486 if (ULE->hasExplicitTemplateArgs()) {
6487 ULE->copyTemplateArgumentsInto(TABuffer);
6488 ExplicitTemplateArgs = &TABuffer;
6489 }
6490
6491 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6492 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006493 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006494 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006495 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006496
John McCall57500772009-12-16 12:17:52 +00006497 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006498 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6499 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006500 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006501 CandidateSet,
6502 PartialOverloading);
6503}
John McCalld681c392009-12-16 08:11:27 +00006504
6505/// Attempts to recover from a call where no functions were found.
6506///
6507/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006508static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006509BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006510 UnresolvedLookupExpr *ULE,
6511 SourceLocation LParenLoc,
6512 Expr **Args, unsigned NumArgs,
6513 SourceLocation *CommaLocs,
6514 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006515
6516 CXXScopeSpec SS;
6517 if (ULE->getQualifier()) {
6518 SS.setScopeRep(ULE->getQualifier());
6519 SS.setRange(ULE->getQualifierRange());
6520 }
6521
John McCall57500772009-12-16 12:17:52 +00006522 TemplateArgumentListInfo TABuffer;
6523 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6524 if (ULE->hasExplicitTemplateArgs()) {
6525 ULE->copyTemplateArgumentsInto(TABuffer);
6526 ExplicitTemplateArgs = &TABuffer;
6527 }
6528
John McCalld681c392009-12-16 08:11:27 +00006529 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6530 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006531 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorb412e172010-07-25 18:17:45 +00006532 return SemaRef.ExprError();
John McCalld681c392009-12-16 08:11:27 +00006533
John McCall57500772009-12-16 12:17:52 +00006534 assert(!R.empty() && "lookup results empty despite recovery");
6535
6536 // Build an implicit member call if appropriate. Just drop the
6537 // casts and such from the call, we don't really care.
6538 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6539 if ((*R.begin())->isCXXClassMember())
6540 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6541 else if (ExplicitTemplateArgs)
6542 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6543 else
6544 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6545
6546 if (NewFn.isInvalid())
Douglas Gregorb412e172010-07-25 18:17:45 +00006547 return SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006548
6549 // This shouldn't cause an infinite loop because we're giving it
6550 // an expression with non-empty lookup results, which should never
6551 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006552 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
John McCall37ad5512010-08-23 06:44:23 +00006553 Sema::MultiExprArg(SemaRef, Args, NumArgs),
John McCall57500772009-12-16 12:17:52 +00006554 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006555}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006556
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006557/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006558/// (which eventually refers to the declaration Func) and the call
6559/// arguments Args/NumArgs, attempt to resolve the function call down
6560/// to a specific function. If overload resolution succeeds, returns
6561/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006562/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006563/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006564Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006565Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006566 SourceLocation LParenLoc,
6567 Expr **Args, unsigned NumArgs,
6568 SourceLocation *CommaLocs,
6569 SourceLocation RParenLoc) {
6570#ifndef NDEBUG
6571 if (ULE->requiresADL()) {
6572 // To do ADL, we must have found an unqualified name.
6573 assert(!ULE->getQualifier() && "qualified name with ADL");
6574
6575 // We don't perform ADL for implicit declarations of builtins.
6576 // Verify that this was correctly set up.
6577 FunctionDecl *F;
6578 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6579 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6580 F->getBuiltinID() && F->isImplicit())
6581 assert(0 && "performing ADL for builtin");
6582
6583 // We don't perform ADL in C.
6584 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6585 }
6586#endif
6587
John McCallbc077cf2010-02-08 23:07:23 +00006588 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006589
John McCall57500772009-12-16 12:17:52 +00006590 // Add the functions denoted by the callee to the set of candidate
6591 // functions, including those from argument-dependent lookup.
6592 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006593
6594 // If we found nothing, try to recover.
6595 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6596 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006597 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006598 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006599 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006600
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006601 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006602 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006603 case OR_Success: {
6604 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006605 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006606 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006607 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006608 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6609 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006610
6611 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006612 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006613 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006614 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006615 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006616 break;
6617
6618 case OR_Ambiguous:
6619 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006620 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006621 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006622 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006623
6624 case OR_Deleted:
6625 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6626 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006627 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006628 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006629 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006630 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006631 }
6632
Douglas Gregorb412e172010-07-25 18:17:45 +00006633 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006634 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006635}
6636
John McCall4c4c1df2010-01-26 03:27:55 +00006637static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006638 return Functions.size() > 1 ||
6639 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6640}
6641
Douglas Gregor084d8552009-03-13 23:49:33 +00006642/// \brief Create a unary operation that may resolve to an overloaded
6643/// operator.
6644///
6645/// \param OpLoc The location of the operator itself (e.g., '*').
6646///
6647/// \param OpcIn The UnaryOperator::Opcode that describes this
6648/// operator.
6649///
6650/// \param Functions The set of non-member functions that will be
6651/// considered by overload resolution. The caller needs to build this
6652/// set based on the context using, e.g.,
6653/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6654/// set should not contain any member functions; those will be added
6655/// by CreateOverloadedUnaryOp().
6656///
6657/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006658Sema::OwningExprResult
6659Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6660 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00006661 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006662 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00006663
6664 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6665 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6666 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006667 // TODO: provide better source location info.
6668 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006669
6670 Expr *Args[2] = { Input, 0 };
6671 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006672
Douglas Gregor084d8552009-03-13 23:49:33 +00006673 // For post-increment and post-decrement, add the implicit '0' as
6674 // the second argument, so that we know this is a post-increment or
6675 // post-decrement.
6676 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6677 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006678 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006679 SourceLocation());
6680 NumArgs = 2;
6681 }
6682
6683 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006684 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00006685 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00006686 Opc,
6687 Context.DependentTy,
6688 OpLoc));
6689
John McCall58cc69d2010-01-27 01:50:18 +00006690 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006691 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006692 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006693 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006694 /*ADL*/ true, IsOverloaded(Fns),
6695 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006696 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6697 &Args[0], NumArgs,
6698 Context.DependentTy,
6699 OpLoc));
6700 }
6701
6702 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006703 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006704
6705 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006706 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006707
6708 // Add operator candidates that are member functions.
6709 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6710
John McCall4c4c1df2010-01-26 03:27:55 +00006711 // Add candidates from ADL.
6712 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006713 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006714 /*ExplicitTemplateArgs*/ 0,
6715 CandidateSet);
6716
Douglas Gregor084d8552009-03-13 23:49:33 +00006717 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006718 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006719
6720 // Perform overload resolution.
6721 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006722 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006723 case OR_Success: {
6724 // We found a built-in operator or an overloaded operator.
6725 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006726
Douglas Gregor084d8552009-03-13 23:49:33 +00006727 if (FnDecl) {
6728 // We matched an overloaded operator. Build a call to that
6729 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006730
Douglas Gregor084d8552009-03-13 23:49:33 +00006731 // Convert the arguments.
6732 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006733 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006734
John McCall16df1e52010-03-30 21:47:33 +00006735 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6736 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006737 return ExprError();
6738 } else {
6739 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006740 OwningExprResult InputInit
6741 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006742 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006743 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00006744 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00006745 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006746 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00006747 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00006748 }
6749
John McCall4fa0d5f2010-05-06 18:15:07 +00006750 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6751
Douglas Gregor084d8552009-03-13 23:49:33 +00006752 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006753 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006754
Douglas Gregor084d8552009-03-13 23:49:33 +00006755 // Build the actual expression node.
6756 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6757 SourceLocation());
6758 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006759
Eli Friedman030eee42009-11-18 03:58:17 +00006760 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00006761 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006762 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallb268a282010-08-23 23:25:46 +00006763 Args, NumArgs, ResultTy, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00006764
John McCallb268a282010-08-23 23:25:46 +00006765 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006766 FnDecl))
6767 return ExprError();
6768
John McCallb268a282010-08-23 23:25:46 +00006769 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00006770 } else {
6771 // We matched a built-in operator. Convert the arguments, then
6772 // break out so that we will build the appropriate built-in
6773 // operator node.
6774 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006775 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006776 return ExprError();
6777
6778 break;
6779 }
6780 }
6781
6782 case OR_No_Viable_Function:
6783 // No viable function; fall through to handling this as a
6784 // built-in operator, which will produce an error message for us.
6785 break;
6786
6787 case OR_Ambiguous:
6788 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6789 << UnaryOperator::getOpcodeStr(Opc)
6790 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006791 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006792 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006793 return ExprError();
6794
6795 case OR_Deleted:
6796 Diag(OpLoc, diag::err_ovl_deleted_oper)
6797 << Best->Function->isDeleted()
6798 << UnaryOperator::getOpcodeStr(Opc)
6799 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006800 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006801 return ExprError();
6802 }
6803
6804 // Either we found no viable overloaded operator or we matched a
6805 // built-in operator. In either case, fall through to trying to
6806 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00006807 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006808}
6809
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006810/// \brief Create a binary operation that may resolve to an overloaded
6811/// operator.
6812///
6813/// \param OpLoc The location of the operator itself (e.g., '+').
6814///
6815/// \param OpcIn The BinaryOperator::Opcode that describes this
6816/// operator.
6817///
6818/// \param Functions The set of non-member functions that will be
6819/// considered by overload resolution. The caller needs to build this
6820/// set based on the context using, e.g.,
6821/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6822/// set should not contain any member functions; those will be added
6823/// by CreateOverloadedBinOp().
6824///
6825/// \param LHS Left-hand argument.
6826/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006827Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006828Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006829 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006830 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006831 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006832 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006833 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006834
6835 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6836 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6837 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6838
6839 // If either side is type-dependent, create an appropriate dependent
6840 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006841 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006842 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006843 // If there are no functions to store, just build a dependent
6844 // BinaryOperator or CompoundAssignment.
6845 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6846 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6847 Context.DependentTy, OpLoc));
6848
6849 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6850 Context.DependentTy,
6851 Context.DependentTy,
6852 Context.DependentTy,
6853 OpLoc));
6854 }
John McCall4c4c1df2010-01-26 03:27:55 +00006855
6856 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006857 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006858 // TODO: provide better source location info in DNLoc component.
6859 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006860 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006861 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006862 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006863 /*ADL*/ true, IsOverloaded(Fns),
6864 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006865 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006866 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006867 Context.DependentTy,
6868 OpLoc));
6869 }
6870
6871 // If this is the .* operator, which is not overloadable, just
6872 // create a built-in binary operator.
6873 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006874 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006875
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006876 // If this is the assignment operator, we only perform overload resolution
6877 // if the left-hand side is a class or enumeration type. This is actually
6878 // a hack. The standard requires that we do overload resolution between the
6879 // various built-in candidates, but as DR507 points out, this can lead to
6880 // problems. So we do it this way, which pretty much follows what GCC does.
6881 // Note that we go the traditional code path for compound assignment forms.
6882 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006883 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006884
Douglas Gregor084d8552009-03-13 23:49:33 +00006885 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006886 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006887
6888 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006889 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006890
6891 // Add operator candidates that are member functions.
6892 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6893
John McCall4c4c1df2010-01-26 03:27:55 +00006894 // Add candidates from ADL.
6895 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6896 Args, 2,
6897 /*ExplicitTemplateArgs*/ 0,
6898 CandidateSet);
6899
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006900 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006901 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006902
6903 // Perform overload resolution.
6904 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006905 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006906 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006907 // We found a built-in operator or an overloaded operator.
6908 FunctionDecl *FnDecl = Best->Function;
6909
6910 if (FnDecl) {
6911 // We matched an overloaded operator. Build a call to that
6912 // operator.
6913
6914 // Convert the arguments.
6915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006916 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006917 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006918
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006919 OwningExprResult Arg1
6920 = PerformCopyInitialization(
6921 InitializedEntity::InitializeParameter(
6922 FnDecl->getParamDecl(0)),
6923 SourceLocation(),
6924 Owned(Args[1]));
6925 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006926 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006927
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006928 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006929 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006930 return ExprError();
6931
6932 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006933 } else {
6934 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006935 OwningExprResult Arg0
6936 = PerformCopyInitialization(
6937 InitializedEntity::InitializeParameter(
6938 FnDecl->getParamDecl(0)),
6939 SourceLocation(),
6940 Owned(Args[0]));
6941 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006942 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006943
6944 OwningExprResult Arg1
6945 = PerformCopyInitialization(
6946 InitializedEntity::InitializeParameter(
6947 FnDecl->getParamDecl(1)),
6948 SourceLocation(),
6949 Owned(Args[1]));
6950 if (Arg1.isInvalid())
6951 return ExprError();
6952 Args[0] = LHS = Arg0.takeAs<Expr>();
6953 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006954 }
6955
John McCall4fa0d5f2010-05-06 18:15:07 +00006956 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6957
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006958 // Determine the result type
6959 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00006960 = FnDecl->getType()->getAs<FunctionType>()
6961 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006962
6963 // Build the actual expression node.
6964 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006965 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006966 UsualUnaryConversions(FnExpr);
6967
John McCallb268a282010-08-23 23:25:46 +00006968 CXXOperatorCallExpr *TheCall =
6969 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6970 Args, 2, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006971
John McCallb268a282010-08-23 23:25:46 +00006972 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006973 FnDecl))
6974 return ExprError();
6975
John McCallb268a282010-08-23 23:25:46 +00006976 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006977 } else {
6978 // We matched a built-in operator. Convert the arguments, then
6979 // break out so that we will build the appropriate built-in
6980 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006981 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006982 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006983 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006984 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006985 return ExprError();
6986
6987 break;
6988 }
6989 }
6990
Douglas Gregor66950a32009-09-30 21:46:01 +00006991 case OR_No_Viable_Function: {
6992 // C++ [over.match.oper]p9:
6993 // If the operator is the operator , [...] and there are no
6994 // viable functions, then the operator is assumed to be the
6995 // built-in operator and interpreted according to clause 5.
6996 if (Opc == BinaryOperator::Comma)
6997 break;
6998
Sebastian Redl027de2a2009-05-21 11:50:50 +00006999 // For class as left operand for assignment or compound assigment operator
7000 // do not fall through to handling in built-in, but report that no overloaded
7001 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00007002 OwningExprResult Result = ExprError();
7003 if (Args[0]->getType()->isRecordType() &&
7004 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007005 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7006 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007007 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007008 } else {
7009 // No viable function; try to create a built-in operation, which will
7010 // produce an error. Then, show the non-viable candidates.
7011 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007012 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007013 assert(Result.isInvalid() &&
7014 "C++ binary operator overloading is missing candidates!");
7015 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00007016 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007017 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007018 return move(Result);
7019 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007020
7021 case OR_Ambiguous:
7022 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7023 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007024 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007025 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007026 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007027 return ExprError();
7028
7029 case OR_Deleted:
7030 Diag(OpLoc, diag::err_ovl_deleted_oper)
7031 << Best->Function->isDeleted()
7032 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007033 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007034 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007035 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007036 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007037
Douglas Gregor66950a32009-09-30 21:46:01 +00007038 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007039 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007040}
7041
Sebastian Redladba46e2009-10-29 20:17:01 +00007042Action::OwningExprResult
7043Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7044 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007045 Expr *Base, Expr *Idx) {
7046 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007047 DeclarationName OpName =
7048 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7049
7050 // If either side is type-dependent, create an appropriate dependent
7051 // expression.
7052 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7053
John McCall58cc69d2010-01-27 01:50:18 +00007054 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007055 // CHECKME: no 'operator' keyword?
7056 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7057 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007058 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007059 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007060 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007061 /*ADL*/ true, /*Overloaded*/ false,
7062 UnresolvedSetIterator(),
7063 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007064 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007065
Sebastian Redladba46e2009-10-29 20:17:01 +00007066 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7067 Args, 2,
7068 Context.DependentTy,
7069 RLoc));
7070 }
7071
7072 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007073 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007074
7075 // Subscript can only be overloaded as a member function.
7076
7077 // Add operator candidates that are member functions.
7078 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7079
7080 // Add builtin operator candidates.
7081 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7082
7083 // Perform overload resolution.
7084 OverloadCandidateSet::iterator Best;
7085 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7086 case OR_Success: {
7087 // We found a built-in operator or an overloaded operator.
7088 FunctionDecl *FnDecl = Best->Function;
7089
7090 if (FnDecl) {
7091 // We matched an overloaded operator. Build a call to that
7092 // operator.
7093
John McCalla0296f72010-03-19 07:35:19 +00007094 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007095 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007096
Sebastian Redladba46e2009-10-29 20:17:01 +00007097 // Convert the arguments.
7098 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007099 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007100 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007101 return ExprError();
7102
Anders Carlssona68e51e2010-01-29 18:37:50 +00007103 // Convert the arguments.
7104 OwningExprResult InputInit
7105 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7106 FnDecl->getParamDecl(0)),
7107 SourceLocation(),
7108 Owned(Args[1]));
7109 if (InputInit.isInvalid())
7110 return ExprError();
7111
7112 Args[1] = InputInit.takeAs<Expr>();
7113
Sebastian Redladba46e2009-10-29 20:17:01 +00007114 // Determine the result type
7115 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007116 = FnDecl->getType()->getAs<FunctionType>()
7117 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007118
7119 // Build the actual expression node.
7120 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7121 LLoc);
7122 UsualUnaryConversions(FnExpr);
7123
John McCallb268a282010-08-23 23:25:46 +00007124 CXXOperatorCallExpr *TheCall =
7125 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7126 FnExpr, Args, 2,
7127 ResultTy, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007128
John McCallb268a282010-08-23 23:25:46 +00007129 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007130 FnDecl))
7131 return ExprError();
7132
John McCallb268a282010-08-23 23:25:46 +00007133 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007134 } else {
7135 // We matched a built-in operator. Convert the arguments, then
7136 // break out so that we will build the appropriate built-in
7137 // operator node.
7138 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007139 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007140 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007141 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007142 return ExprError();
7143
7144 break;
7145 }
7146 }
7147
7148 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007149 if (CandidateSet.empty())
7150 Diag(LLoc, diag::err_ovl_no_oper)
7151 << Args[0]->getType() << /*subscript*/ 0
7152 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7153 else
7154 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7155 << Args[0]->getType()
7156 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007157 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00007158 "[]", LLoc);
7159 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007160 }
7161
7162 case OR_Ambiguous:
7163 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7164 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007165 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00007166 "[]", LLoc);
7167 return ExprError();
7168
7169 case OR_Deleted:
7170 Diag(LLoc, diag::err_ovl_deleted_oper)
7171 << Best->Function->isDeleted() << "[]"
7172 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007173 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00007174 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007175 return ExprError();
7176 }
7177
7178 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007179 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007180}
7181
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007182/// BuildCallToMemberFunction - Build a call to a member
7183/// function. MemExpr is the expression that refers to the member
7184/// function (and includes the object parameter), Args/NumArgs are the
7185/// arguments to the function call (not including the object
7186/// parameter). The caller needs to validate that the member
7187/// expression refers to a member function or an overloaded member
7188/// function.
John McCall2d74de92009-12-01 22:10:20 +00007189Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007190Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7191 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007192 unsigned NumArgs, SourceLocation *CommaLocs,
7193 SourceLocation RParenLoc) {
7194 // Dig out the member expression. This holds both the object
7195 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007196 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7197
John McCall10eae182009-11-30 22:42:35 +00007198 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007199 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007200 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007201 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007202 if (isa<MemberExpr>(NakedMemExpr)) {
7203 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007204 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007205 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007206 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007207 } else {
7208 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007209 Qualifier = UnresExpr->getQualifier();
7210
John McCall6e9f8f62009-12-03 04:06:58 +00007211 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007212
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007213 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007214 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007215
John McCall2d74de92009-12-01 22:10:20 +00007216 // FIXME: avoid copy.
7217 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7218 if (UnresExpr->hasExplicitTemplateArgs()) {
7219 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7220 TemplateArgs = &TemplateArgsBuffer;
7221 }
7222
John McCall10eae182009-11-30 22:42:35 +00007223 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7224 E = UnresExpr->decls_end(); I != E; ++I) {
7225
John McCall6e9f8f62009-12-03 04:06:58 +00007226 NamedDecl *Func = *I;
7227 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7228 if (isa<UsingShadowDecl>(Func))
7229 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7230
John McCall10eae182009-11-30 22:42:35 +00007231 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007232 // If explicit template arguments were provided, we can't call a
7233 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007234 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007235 continue;
7236
John McCalla0296f72010-03-19 07:35:19 +00007237 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007238 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007239 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007240 } else {
John McCall10eae182009-11-30 22:42:35 +00007241 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007242 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007243 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007244 CandidateSet,
7245 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007246 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007247 }
Mike Stump11289f42009-09-09 15:08:12 +00007248
John McCall10eae182009-11-30 22:42:35 +00007249 DeclarationName DeclName = UnresExpr->getMemberName();
7250
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007251 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00007252 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007253 case OR_Success:
7254 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007255 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007256 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007257 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007258 break;
7259
7260 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007261 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007262 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007263 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007264 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007265 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007266 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007267
7268 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007269 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007270 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007271 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007272 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007273 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007274
7275 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007276 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007277 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007278 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007279 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007280 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007281 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007282 }
7283
John McCall16df1e52010-03-30 21:47:33 +00007284 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007285
John McCall2d74de92009-12-01 22:10:20 +00007286 // If overload resolution picked a static member, build a
7287 // non-member call based on that function.
7288 if (Method->isStatic()) {
7289 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7290 Args, NumArgs, RParenLoc);
7291 }
7292
John McCall10eae182009-11-30 22:42:35 +00007293 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007294 }
7295
7296 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007297 CXXMemberCallExpr *TheCall =
7298 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7299 Method->getCallResultType(),
7300 RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007301
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007302 // Check for a valid return type.
7303 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007304 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007305 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007306
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007307 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007308 // We only need to do this if there was actually an overload; otherwise
7309 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007310 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007311 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007312 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7313 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007314 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007315 MemExpr->setBase(ObjectArg);
7316
7317 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007318 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007319 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007320 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007321 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007322
John McCallb268a282010-08-23 23:25:46 +00007323 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007324 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007325
John McCallb268a282010-08-23 23:25:46 +00007326 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007327}
7328
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007329/// BuildCallToObjectOfClassType - Build a call to an object of class
7330/// type (C++ [over.call.object]), which can end up invoking an
7331/// overloaded function call operator (@c operator()) or performing a
7332/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007333Sema::ExprResult
7334Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007335 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007336 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007337 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007338 SourceLocation RParenLoc) {
7339 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007340 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007341
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007342 // C++ [over.call.object]p1:
7343 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007344 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007345 // candidate functions includes at least the function call
7346 // operators of T. The function call operators of T are obtained by
7347 // ordinary lookup of the name operator() in the context of
7348 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007349 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007350 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007351
7352 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007353 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007354 << Object->getSourceRange()))
7355 return true;
7356
John McCall27b18f82009-11-17 02:14:36 +00007357 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7358 LookupQualifiedName(R, Record->getDecl());
7359 R.suppressDiagnostics();
7360
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007361 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007362 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007363 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007364 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007365 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007366 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007367
Douglas Gregorab7897a2008-11-19 22:57:39 +00007368 // C++ [over.call.object]p2:
7369 // In addition, for each conversion function declared in T of the
7370 // form
7371 //
7372 // operator conversion-type-id () cv-qualifier;
7373 //
7374 // where cv-qualifier is the same cv-qualification as, or a
7375 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007376 // denotes the type "pointer to function of (P1,...,Pn) returning
7377 // R", or the type "reference to pointer to function of
7378 // (P1,...,Pn) returning R", or the type "reference to function
7379 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007380 // is also considered as a candidate function. Similarly,
7381 // surrogate call functions are added to the set of candidate
7382 // functions for each conversion function declared in an
7383 // accessible base class provided the function is not hidden
7384 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007385 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007386 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007387 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007388 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007389 NamedDecl *D = *I;
7390 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7391 if (isa<UsingShadowDecl>(D))
7392 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7393
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007394 // Skip over templated conversion functions; they aren't
7395 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007396 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007397 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007398
John McCall6e9f8f62009-12-03 04:06:58 +00007399 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007400
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007401 // Strip the reference type (if any) and then the pointer type (if
7402 // any) to get down to what might be a function type.
7403 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7404 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7405 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007406
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007407 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007408 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007409 Object->getType(), Args, NumArgs,
7410 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007411 }
Mike Stump11289f42009-09-09 15:08:12 +00007412
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007413 // Perform overload resolution.
7414 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007415 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007416 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007417 // Overload resolution succeeded; we'll build the appropriate call
7418 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007419 break;
7420
7421 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007422 if (CandidateSet.empty())
7423 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7424 << Object->getType() << /*call*/ 1
7425 << Object->getSourceRange();
7426 else
7427 Diag(Object->getSourceRange().getBegin(),
7428 diag::err_ovl_no_viable_object_call)
7429 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007430 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007431 break;
7432
7433 case OR_Ambiguous:
7434 Diag(Object->getSourceRange().getBegin(),
7435 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007436 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007437 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007438 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007439
7440 case OR_Deleted:
7441 Diag(Object->getSourceRange().getBegin(),
7442 diag::err_ovl_deleted_object_call)
7443 << Best->Function->isDeleted()
7444 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007445 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007446 break;
Mike Stump11289f42009-09-09 15:08:12 +00007447 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007448
Douglas Gregorb412e172010-07-25 18:17:45 +00007449 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007450 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007451
Douglas Gregorab7897a2008-11-19 22:57:39 +00007452 if (Best->Function == 0) {
7453 // Since there is no function declaration, this is one of the
7454 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007455 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007456 = cast<CXXConversionDecl>(
7457 Best->Conversions[0].UserDefined.ConversionFunction);
7458
John McCalla0296f72010-03-19 07:35:19 +00007459 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007460 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007461
Douglas Gregorab7897a2008-11-19 22:57:39 +00007462 // We selected one of the surrogate functions that converts the
7463 // object parameter to a function pointer. Perform the conversion
7464 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007465
7466 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007467 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007468 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7469 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007470
John McCallb268a282010-08-23 23:25:46 +00007471 return ActOnCallExpr(S, CE, LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007472 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
John McCalle172be52010-08-24 06:09:16 +00007473 CommaLocs, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007474 }
7475
John McCalla0296f72010-03-19 07:35:19 +00007476 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007477 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007478
Douglas Gregorab7897a2008-11-19 22:57:39 +00007479 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7480 // that calls this method, using Object for the implicit object
7481 // parameter and passing along the remaining arguments.
7482 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007483 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007484
7485 unsigned NumArgsInProto = Proto->getNumArgs();
7486 unsigned NumArgsToCheck = NumArgs;
7487
7488 // Build the full argument list for the method call (the
7489 // implicit object parameter is placed at the beginning of the
7490 // list).
7491 Expr **MethodArgs;
7492 if (NumArgs < NumArgsInProto) {
7493 NumArgsToCheck = NumArgsInProto;
7494 MethodArgs = new Expr*[NumArgsInProto + 1];
7495 } else {
7496 MethodArgs = new Expr*[NumArgs + 1];
7497 }
7498 MethodArgs[0] = Object;
7499 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7500 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007501
7502 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007503 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007504 UsualUnaryConversions(NewFn);
7505
7506 // Once we've built TheCall, all of the expressions are properly
7507 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007508 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007509 CXXOperatorCallExpr *TheCall =
7510 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7511 MethodArgs, NumArgs + 1,
7512 ResultTy, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007513 delete [] MethodArgs;
7514
John McCallb268a282010-08-23 23:25:46 +00007515 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007516 Method))
7517 return true;
7518
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007519 // We may have default arguments. If so, we need to allocate more
7520 // slots in the call for them.
7521 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007522 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007523 else if (NumArgs > NumArgsInProto)
7524 NumArgsToCheck = NumArgsInProto;
7525
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007526 bool IsError = false;
7527
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007528 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007529 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007530 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007531 TheCall->setArg(0, Object);
7532
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007533
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007534 // Check the argument types.
7535 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007536 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007537 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007538 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007539
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007540 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007541
7542 OwningExprResult InputInit
7543 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7544 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007545 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007546
7547 IsError |= InputInit.isInvalid();
7548 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007549 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007550 OwningExprResult DefArg
7551 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7552 if (DefArg.isInvalid()) {
7553 IsError = true;
7554 break;
7555 }
7556
7557 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007558 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007559
7560 TheCall->setArg(i + 1, Arg);
7561 }
7562
7563 // If this is a variadic call, handle args passed through "...".
7564 if (Proto->isVariadic()) {
7565 // Promote the arguments (C99 6.5.2.2p7).
7566 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7567 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007568 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007569 TheCall->setArg(i + 1, Arg);
7570 }
7571 }
7572
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007573 if (IsError) return true;
7574
John McCallb268a282010-08-23 23:25:46 +00007575 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007576 return true;
7577
John McCalle172be52010-08-24 06:09:16 +00007578 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007579}
7580
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007581/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007582/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007583/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007584Sema::OwningExprResult
John McCallb268a282010-08-23 23:25:46 +00007585Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007586 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007587
John McCallbc077cf2010-02-08 23:07:23 +00007588 SourceLocation Loc = Base->getExprLoc();
7589
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007590 // C++ [over.ref]p1:
7591 //
7592 // [...] An expression x->m is interpreted as (x.operator->())->m
7593 // for a class object x of type T if T::operator->() exists and if
7594 // the operator is selected as the best match function by the
7595 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007596 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007597 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007598 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007599
John McCallbc077cf2010-02-08 23:07:23 +00007600 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007601 PDiag(diag::err_typecheck_incomplete_tag)
7602 << Base->getSourceRange()))
7603 return ExprError();
7604
John McCall27b18f82009-11-17 02:14:36 +00007605 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7606 LookupQualifiedName(R, BaseRecord->getDecl());
7607 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007608
7609 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007610 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007611 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007612 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007613 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007614
7615 // Perform overload resolution.
7616 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007617 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007618 case OR_Success:
7619 // Overload resolution succeeded; we'll build the call below.
7620 break;
7621
7622 case OR_No_Viable_Function:
7623 if (CandidateSet.empty())
7624 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007625 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007626 else
7627 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007628 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007629 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007630 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007631
7632 case OR_Ambiguous:
7633 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007634 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007635 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007636 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007637
7638 case OR_Deleted:
7639 Diag(OpLoc, diag::err_ovl_deleted_oper)
7640 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007641 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007642 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007643 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007644 }
7645
John McCalla0296f72010-03-19 07:35:19 +00007646 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007647 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007648
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007649 // Convert the object parameter.
7650 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007651 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7652 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007653 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007654
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007655 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007656 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7657 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007658 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007659
Douglas Gregor603d81b2010-07-13 08:18:22 +00007660 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007661 CXXOperatorCallExpr *TheCall =
7662 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7663 &Base, 1, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007664
John McCallb268a282010-08-23 23:25:46 +00007665 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007666 Method))
7667 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007668 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007669}
7670
Douglas Gregorcd695e52008-11-10 20:40:00 +00007671/// FixOverloadedFunctionReference - E is an expression that refers to
7672/// a C++ overloaded function (possibly with some parentheses and
7673/// perhaps a '&' around it). We have resolved the overloaded function
7674/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007675/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007676Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007677 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007678 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007679 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7680 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007681 if (SubExpr == PE->getSubExpr())
7682 return PE->Retain();
7683
7684 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7685 }
7686
7687 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007688 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7689 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007690 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007691 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007692 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007693 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007694 if (SubExpr == ICE->getSubExpr())
7695 return ICE->Retain();
7696
John McCallcf142162010-08-07 06:22:56 +00007697 return ImplicitCastExpr::Create(Context, ICE->getType(),
7698 ICE->getCastKind(),
7699 SubExpr, 0,
7700 ICE->getCategory());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007701 }
7702
7703 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007704 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007705 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007706 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7707 if (Method->isStatic()) {
7708 // Do nothing: static member functions aren't any different
7709 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007710 } else {
John McCalle66edc12009-11-24 19:00:30 +00007711 // Fix the sub expression, which really has to be an
7712 // UnresolvedLookupExpr holding an overloaded member function
7713 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007714 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7715 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007716 if (SubExpr == UnOp->getSubExpr())
7717 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007718
John McCalld14a8642009-11-21 08:51:07 +00007719 assert(isa<DeclRefExpr>(SubExpr)
7720 && "fixed to something other than a decl ref");
7721 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7722 && "fixed to a member ref with no nested name qualifier");
7723
7724 // We have taken the address of a pointer to member
7725 // function. Perform the computation here so that we get the
7726 // appropriate pointer to member type.
7727 QualType ClassType
7728 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7729 QualType MemPtrType
7730 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7731
7732 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7733 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007734 }
7735 }
John McCall16df1e52010-03-30 21:47:33 +00007736 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7737 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007738 if (SubExpr == UnOp->getSubExpr())
7739 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007740
Douglas Gregor51c538b2009-11-20 19:42:02 +00007741 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7742 Context.getPointerType(SubExpr->getType()),
7743 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007744 }
John McCalld14a8642009-11-21 08:51:07 +00007745
7746 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007747 // FIXME: avoid copy.
7748 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007749 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007750 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7751 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007752 }
7753
John McCalld14a8642009-11-21 08:51:07 +00007754 return DeclRefExpr::Create(Context,
7755 ULE->getQualifier(),
7756 ULE->getQualifierRange(),
7757 Fn,
7758 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007759 Fn->getType(),
7760 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007761 }
7762
John McCall10eae182009-11-30 22:42:35 +00007763 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007764 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007765 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7766 if (MemExpr->hasExplicitTemplateArgs()) {
7767 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7768 TemplateArgs = &TemplateArgsBuffer;
7769 }
John McCall6b51f282009-11-23 01:53:49 +00007770
John McCall2d74de92009-12-01 22:10:20 +00007771 Expr *Base;
7772
7773 // If we're filling in
7774 if (MemExpr->isImplicitAccess()) {
7775 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7776 return DeclRefExpr::Create(Context,
7777 MemExpr->getQualifier(),
7778 MemExpr->getQualifierRange(),
7779 Fn,
7780 MemExpr->getMemberLoc(),
7781 Fn->getType(),
7782 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007783 } else {
7784 SourceLocation Loc = MemExpr->getMemberLoc();
7785 if (MemExpr->getQualifier())
7786 Loc = MemExpr->getQualifierRange().getBegin();
7787 Base = new (Context) CXXThisExpr(Loc,
7788 MemExpr->getBaseType(),
7789 /*isImplicit=*/true);
7790 }
John McCall2d74de92009-12-01 22:10:20 +00007791 } else
7792 Base = MemExpr->getBase()->Retain();
7793
7794 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007795 MemExpr->isArrow(),
7796 MemExpr->getQualifier(),
7797 MemExpr->getQualifierRange(),
7798 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007799 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007800 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00007801 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007802 Fn->getType());
7803 }
7804
Douglas Gregor51c538b2009-11-20 19:42:02 +00007805 assert(false && "Invalid reference to overloaded function");
7806 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007807}
7808
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007809Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007810 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007811 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007812 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007813}
7814
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007815} // end namespace clang