blob: e50a06057ae23eb0add9197689d2be555e7dfacf [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
3195Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3196 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 Expr *From = static_cast<Expr *>(FromE.get());
3204
3205 // We can't perform any more checking for type-dependent expressions.
3206 if (From->isTypeDependent())
3207 return move(FromE);
3208
3209 // If the expression already has integral or enumeration type, we're golden.
3210 QualType T = From->getType();
3211 if (T->isIntegralOrEnumerationType())
3212 return move(FromE);
3213
3214 // FIXME: Check for missing '()' if T is a function type?
3215
3216 // If we don't have a class type in C++, there's no way we can get an
3217 // expression of integral or enumeration type.
3218 const RecordType *RecordTy = T->getAs<RecordType>();
3219 if (!RecordTy || !getLangOptions().CPlusPlus) {
3220 Diag(Loc, NotIntDiag)
3221 << T << From->getSourceRange();
Douglas Gregor5823da32010-06-29 23:25:20 +00003222 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003223 }
3224
3225 // We must have a complete class type.
3226 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor4799d032010-06-30 00:20:43 +00003227 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003228
3229 // Look for a conversion to an integral or enumeration type.
3230 UnresolvedSet<4> ViableConversions;
3231 UnresolvedSet<4> ExplicitConversions;
3232 const UnresolvedSetImpl *Conversions
3233 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3234
3235 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3236 E = Conversions->end();
3237 I != E;
3238 ++I) {
3239 if (CXXConversionDecl *Conversion
3240 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3241 if (Conversion->getConversionType().getNonReferenceType()
3242 ->isIntegralOrEnumerationType()) {
3243 if (Conversion->isExplicit())
3244 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3245 else
3246 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3247 }
3248 }
3249
3250 switch (ViableConversions.size()) {
3251 case 0:
3252 if (ExplicitConversions.size() == 1) {
3253 DeclAccessPair Found = ExplicitConversions[0];
3254 CXXConversionDecl *Conversion
3255 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3256
3257 // The user probably meant to invoke the given explicit
3258 // conversion; use it.
3259 QualType ConvTy
3260 = Conversion->getConversionType().getNonReferenceType();
3261 std::string TypeStr;
3262 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3263
3264 Diag(Loc, ExplicitConvDiag)
3265 << T << ConvTy
3266 << FixItHint::CreateInsertion(From->getLocStart(),
3267 "static_cast<" + TypeStr + ">(")
3268 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3269 ")");
3270 Diag(Conversion->getLocation(), ExplicitConvNote)
3271 << ConvTy->isEnumeralType() << ConvTy;
3272
3273 // If we aren't in a SFINAE context, build a call to the
3274 // explicit conversion function.
3275 if (isSFINAEContext())
3276 return ExprError();
3277
3278 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3279 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3280 FromE = Owned(From);
3281 }
3282
3283 // We'll complain below about a non-integral condition type.
3284 break;
3285
3286 case 1: {
3287 // Apply this conversion.
3288 DeclAccessPair Found = ViableConversions[0];
3289 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003290
3291 CXXConversionDecl *Conversion
3292 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3293 QualType ConvTy
3294 = Conversion->getConversionType().getNonReferenceType();
3295 if (ConvDiag.getDiagID()) {
3296 if (isSFINAEContext())
3297 return ExprError();
3298
3299 Diag(Loc, ConvDiag)
3300 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3301 }
3302
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003303 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3304 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3305 FromE = Owned(From);
3306 break;
3307 }
3308
3309 default:
3310 Diag(Loc, AmbigDiag)
3311 << T << From->getSourceRange();
3312 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3313 CXXConversionDecl *Conv
3314 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3315 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3316 Diag(Conv->getLocation(), AmbigNote)
3317 << ConvTy->isEnumeralType() << ConvTy;
3318 }
Douglas Gregor5823da32010-06-29 23:25:20 +00003319 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003320 }
3321
Douglas Gregor5823da32010-06-29 23:25:20 +00003322 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003323 Diag(Loc, NotIntDiag)
3324 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003325
3326 return move(FromE);
3327}
3328
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003329/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003330/// candidate functions, using the given function call arguments. If
3331/// @p SuppressUserConversions, then don't allow user-defined
3332/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003333///
3334/// \para PartialOverloading true if we are performing "partial" overloading
3335/// based on an incomplete set of function arguments. This feature is used by
3336/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003337void
3338Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003339 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003340 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003341 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003342 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003343 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003344 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003345 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003346 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003347 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003348 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003349
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003350 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003351 if (!isa<CXXConstructorDecl>(Method)) {
3352 // If we get here, it's because we're calling a member function
3353 // that is named without a member access expression (e.g.,
3354 // "this->f") that was either written explicitly or created
3355 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003356 // function, e.g., X::f(). We use an empty type for the implied
3357 // object argument (C++ [over.call.func]p3), and the acting context
3358 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003359 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003360 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003361 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003362 return;
3363 }
3364 // We treat a constructor like a non-member function, since its object
3365 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003366 }
3367
Douglas Gregorff7028a2009-11-13 23:59:09 +00003368 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003369 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003370
Douglas Gregor27381f32009-11-23 12:27:39 +00003371 // Overload resolution is always an unevaluated context.
3372 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3373
Douglas Gregorffe14e32009-11-14 01:20:54 +00003374 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3375 // C++ [class.copy]p3:
3376 // A member function template is never instantiated to perform the copy
3377 // of a class object to an object of its class type.
3378 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3379 if (NumArgs == 1 &&
3380 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003381 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3382 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003383 return;
3384 }
3385
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003386 // Add this candidate
3387 CandidateSet.push_back(OverloadCandidate());
3388 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003389 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003390 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003391 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003392 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003393 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003394
3395 unsigned NumArgsInProto = Proto->getNumArgs();
3396
3397 // (C++ 13.3.2p2): A candidate function having fewer than m
3398 // parameters is viable only if it has an ellipsis in its parameter
3399 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003400 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3401 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003402 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003403 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003404 return;
3405 }
3406
3407 // (C++ 13.3.2p2): A candidate function having more than m parameters
3408 // is viable only if the (m+1)st parameter has a default argument
3409 // (8.3.6). For the purposes of overload resolution, the
3410 // parameter list is truncated on the right, so that there are
3411 // exactly m parameters.
3412 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003413 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003414 // Not enough arguments.
3415 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003416 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003417 return;
3418 }
3419
3420 // Determine the implicit conversion sequences for each of the
3421 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003422 Candidate.Conversions.resize(NumArgs);
3423 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3424 if (ArgIdx < NumArgsInProto) {
3425 // (C++ 13.3.2p3): for F to be a viable function, there shall
3426 // exist for each argument an implicit conversion sequence
3427 // (13.3.3.1) that converts that argument to the corresponding
3428 // parameter of F.
3429 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003430 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003431 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003432 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003433 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003434 if (Candidate.Conversions[ArgIdx].isBad()) {
3435 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003436 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003437 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003438 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003439 } else {
3440 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3441 // argument for which there is no corresponding parameter is
3442 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003443 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003444 }
3445 }
3446}
3447
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003448/// \brief Add all of the function declarations in the given function set to
3449/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003450void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003451 Expr **Args, unsigned NumArgs,
3452 OverloadCandidateSet& CandidateSet,
3453 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003454 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003455 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3456 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003457 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003458 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003459 cast<CXXMethodDecl>(FD)->getParent(),
3460 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003461 CandidateSet, SuppressUserConversions);
3462 else
John McCalla0296f72010-03-19 07:35:19 +00003463 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003464 SuppressUserConversions);
3465 } else {
John McCalla0296f72010-03-19 07:35:19 +00003466 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003467 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3468 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003469 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003470 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003471 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003472 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003473 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003474 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003475 else
John McCalla0296f72010-03-19 07:35:19 +00003476 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003477 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003478 Args, NumArgs, CandidateSet,
3479 SuppressUserConversions);
3480 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003481 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003482}
3483
John McCallf0f1cf02009-11-17 07:50:12 +00003484/// AddMethodCandidate - Adds a named decl (which is some kind of
3485/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003486void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003487 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003488 Expr **Args, unsigned NumArgs,
3489 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003490 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003491 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003492 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003493
3494 if (isa<UsingShadowDecl>(Decl))
3495 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3496
3497 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3498 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3499 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003500 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3501 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003502 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003503 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003504 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003505 } else {
John McCalla0296f72010-03-19 07:35:19 +00003506 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003507 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003508 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003509 }
3510}
3511
Douglas Gregor436424c2008-11-18 23:14:02 +00003512/// AddMethodCandidate - Adds the given C++ member function to the set
3513/// of candidate functions, using the given function call arguments
3514/// and the object argument (@c Object). For example, in a call
3515/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3516/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3517/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003518/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003519void
John McCalla0296f72010-03-19 07:35:19 +00003520Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003521 CXXRecordDecl *ActingContext, QualType ObjectType,
3522 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003523 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003524 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003525 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003526 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003527 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003528 assert(!isa<CXXConstructorDecl>(Method) &&
3529 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003530
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003531 if (!CandidateSet.isNewCandidate(Method))
3532 return;
3533
Douglas Gregor27381f32009-11-23 12:27:39 +00003534 // Overload resolution is always an unevaluated context.
3535 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3536
Douglas Gregor436424c2008-11-18 23:14:02 +00003537 // Add this candidate
3538 CandidateSet.push_back(OverloadCandidate());
3539 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003540 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003541 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003542 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003543 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003544
3545 unsigned NumArgsInProto = Proto->getNumArgs();
3546
3547 // (C++ 13.3.2p2): A candidate function having fewer than m
3548 // parameters is viable only if it has an ellipsis in its parameter
3549 // list (8.3.5).
3550 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3551 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003552 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003553 return;
3554 }
3555
3556 // (C++ 13.3.2p2): A candidate function having more than m parameters
3557 // is viable only if the (m+1)st parameter has a default argument
3558 // (8.3.6). For the purposes of overload resolution, the
3559 // parameter list is truncated on the right, so that there are
3560 // exactly m parameters.
3561 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3562 if (NumArgs < MinRequiredArgs) {
3563 // Not enough arguments.
3564 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003565 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003566 return;
3567 }
3568
3569 Candidate.Viable = true;
3570 Candidate.Conversions.resize(NumArgs + 1);
3571
John McCall6e9f8f62009-12-03 04:06:58 +00003572 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003573 // The implicit object argument is ignored.
3574 Candidate.IgnoreObjectArgument = true;
3575 else {
3576 // Determine the implicit conversion sequence for the object
3577 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003578 Candidate.Conversions[0]
3579 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003580 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003581 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003582 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003583 return;
3584 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003585 }
3586
3587 // Determine the implicit conversion sequences for each of the
3588 // arguments.
3589 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3590 if (ArgIdx < NumArgsInProto) {
3591 // (C++ 13.3.2p3): for F to be a viable function, there shall
3592 // exist for each argument an implicit conversion sequence
3593 // (13.3.3.1) that converts that argument to the corresponding
3594 // parameter of F.
3595 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003596 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003597 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003598 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003599 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003600 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003601 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003602 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003603 break;
3604 }
3605 } else {
3606 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3607 // argument for which there is no corresponding parameter is
3608 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003609 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003610 }
3611 }
3612}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003613
Douglas Gregor97628d62009-08-21 00:16:32 +00003614/// \brief Add a C++ member function template as a candidate to the candidate
3615/// set, using template argument deduction to produce an appropriate member
3616/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003617void
Douglas Gregor97628d62009-08-21 00:16:32 +00003618Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003619 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003620 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003621 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003622 QualType ObjectType,
3623 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003624 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003625 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003626 if (!CandidateSet.isNewCandidate(MethodTmpl))
3627 return;
3628
Douglas Gregor97628d62009-08-21 00:16:32 +00003629 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003630 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003631 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003632 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003633 // candidate functions in the usual way.113) A given name can refer to one
3634 // or more function templates and also to a set of overloaded non-template
3635 // functions. In such a case, the candidate functions generated from each
3636 // function template are combined with the set of non-template candidate
3637 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003638 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003639 FunctionDecl *Specialization = 0;
3640 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003641 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003642 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003643 CandidateSet.push_back(OverloadCandidate());
3644 OverloadCandidate &Candidate = CandidateSet.back();
3645 Candidate.FoundDecl = FoundDecl;
3646 Candidate.Function = MethodTmpl->getTemplatedDecl();
3647 Candidate.Viable = false;
3648 Candidate.FailureKind = ovl_fail_bad_deduction;
3649 Candidate.IsSurrogate = false;
3650 Candidate.IgnoreObjectArgument = false;
3651 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3652 Info);
3653 return;
3654 }
Mike Stump11289f42009-09-09 15:08:12 +00003655
Douglas Gregor97628d62009-08-21 00:16:32 +00003656 // Add the function template specialization produced by template argument
3657 // deduction as a candidate.
3658 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003659 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003660 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003661 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003662 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003663 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003664}
3665
Douglas Gregor05155d82009-08-21 23:19:43 +00003666/// \brief Add a C++ function template specialization as a candidate
3667/// in the candidate set, using template argument deduction to produce
3668/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003669void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003670Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003671 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003672 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003673 Expr **Args, unsigned NumArgs,
3674 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003675 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003676 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3677 return;
3678
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003679 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003680 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003681 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003682 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003683 // candidate functions in the usual way.113) A given name can refer to one
3684 // or more function templates and also to a set of overloaded non-template
3685 // functions. In such a case, the candidate functions generated from each
3686 // function template are combined with the set of non-template candidate
3687 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003688 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003689 FunctionDecl *Specialization = 0;
3690 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003691 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003692 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003693 CandidateSet.push_back(OverloadCandidate());
3694 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003695 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003696 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3697 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003698 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003699 Candidate.IsSurrogate = false;
3700 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003701 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3702 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003703 return;
3704 }
Mike Stump11289f42009-09-09 15:08:12 +00003705
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003706 // Add the function template specialization produced by template argument
3707 // deduction as a candidate.
3708 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003709 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003710 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003711}
Mike Stump11289f42009-09-09 15:08:12 +00003712
Douglas Gregora1f013e2008-11-07 22:36:19 +00003713/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003714/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003715/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003716/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003717/// (which may or may not be the same type as the type that the
3718/// conversion function produces).
3719void
3720Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003721 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003722 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003723 Expr *From, QualType ToType,
3724 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003725 assert(!Conversion->getDescribedFunctionTemplate() &&
3726 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003727 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003728 if (!CandidateSet.isNewCandidate(Conversion))
3729 return;
3730
Douglas Gregor27381f32009-11-23 12:27:39 +00003731 // Overload resolution is always an unevaluated context.
3732 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3733
Douglas Gregora1f013e2008-11-07 22:36:19 +00003734 // Add this candidate
3735 CandidateSet.push_back(OverloadCandidate());
3736 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003737 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003738 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003739 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003740 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003741 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003742 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003743 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003744 Candidate.Viable = true;
3745 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003746
Douglas Gregor6affc782010-08-19 15:37:02 +00003747 // C++ [over.match.funcs]p4:
3748 // For conversion functions, the function is considered to be a member of
3749 // the class of the implicit implied object argument for the purpose of
3750 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003751 //
3752 // Determine the implicit conversion sequence for the implicit
3753 // object parameter.
3754 QualType ImplicitParamType = From->getType();
3755 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3756 ImplicitParamType = FromPtrType->getPointeeType();
3757 CXXRecordDecl *ConversionContext
3758 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3759
3760 Candidate.Conversions[0]
3761 = TryObjectArgumentInitialization(From->getType(), Conversion,
3762 ConversionContext);
3763
John McCall0d1da222010-01-12 00:44:57 +00003764 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003765 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003766 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003767 return;
3768 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003769
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003770 // We won't go through a user-define type conversion function to convert a
3771 // derived to base as such conversions are given Conversion Rank. They only
3772 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3773 QualType FromCanon
3774 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3775 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3776 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3777 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003778 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003779 return;
3780 }
3781
Douglas Gregora1f013e2008-11-07 22:36:19 +00003782 // To determine what the conversion from the result of calling the
3783 // conversion function to the type we're eventually trying to
3784 // convert to (ToType), we need to synthesize a call to the
3785 // conversion function and attempt copy initialization from it. This
3786 // makes sure that we get the right semantics with respect to
3787 // lvalues/rvalues and the type. Fortunately, we can allocate this
3788 // call on the stack and we don't need its arguments to be
3789 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003790 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003791 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003792 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3793 Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003794 CastExpr::CK_FunctionToPointerDecay,
John McCallcf142162010-08-07 06:22:56 +00003795 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003796
3797 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003798 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3799 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003800 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003801 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003802 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003803 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003804 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003805 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003806 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003807
John McCall0d1da222010-01-12 00:44:57 +00003808 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003809 case ImplicitConversionSequence::StandardConversion:
3810 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003811
3812 // C++ [over.ics.user]p3:
3813 // If the user-defined conversion is specified by a specialization of a
3814 // conversion function template, the second standard conversion sequence
3815 // shall have exact match rank.
3816 if (Conversion->getPrimaryTemplate() &&
3817 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3818 Candidate.Viable = false;
3819 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3820 }
3821
Douglas Gregora1f013e2008-11-07 22:36:19 +00003822 break;
3823
3824 case ImplicitConversionSequence::BadConversion:
3825 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003826 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003827 break;
3828
3829 default:
Mike Stump11289f42009-09-09 15:08:12 +00003830 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003831 "Can only end up with a standard conversion sequence or failure");
3832 }
3833}
3834
Douglas Gregor05155d82009-08-21 23:19:43 +00003835/// \brief Adds a conversion function template specialization
3836/// candidate to the overload set, using template argument deduction
3837/// to deduce the template arguments of the conversion function
3838/// template from the type that we are converting to (C++
3839/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003840void
Douglas Gregor05155d82009-08-21 23:19:43 +00003841Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003842 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003843 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003844 Expr *From, QualType ToType,
3845 OverloadCandidateSet &CandidateSet) {
3846 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3847 "Only conversion function templates permitted here");
3848
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003849 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3850 return;
3851
John McCallbc077cf2010-02-08 23:07:23 +00003852 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003853 CXXConversionDecl *Specialization = 0;
3854 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003855 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003856 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003857 CandidateSet.push_back(OverloadCandidate());
3858 OverloadCandidate &Candidate = CandidateSet.back();
3859 Candidate.FoundDecl = FoundDecl;
3860 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3861 Candidate.Viable = false;
3862 Candidate.FailureKind = ovl_fail_bad_deduction;
3863 Candidate.IsSurrogate = false;
3864 Candidate.IgnoreObjectArgument = false;
3865 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3866 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003867 return;
3868 }
Mike Stump11289f42009-09-09 15:08:12 +00003869
Douglas Gregor05155d82009-08-21 23:19:43 +00003870 // Add the conversion function template specialization produced by
3871 // template argument deduction as a candidate.
3872 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003873 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003874 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003875}
3876
Douglas Gregorab7897a2008-11-19 22:57:39 +00003877/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3878/// converts the given @c Object to a function pointer via the
3879/// conversion function @c Conversion, and then attempts to call it
3880/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3881/// the type of function that we'll eventually be calling.
3882void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003883 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003884 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003885 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003886 QualType ObjectType,
3887 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003888 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003889 if (!CandidateSet.isNewCandidate(Conversion))
3890 return;
3891
Douglas Gregor27381f32009-11-23 12:27:39 +00003892 // Overload resolution is always an unevaluated context.
3893 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3894
Douglas Gregorab7897a2008-11-19 22:57:39 +00003895 CandidateSet.push_back(OverloadCandidate());
3896 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003897 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003898 Candidate.Function = 0;
3899 Candidate.Surrogate = Conversion;
3900 Candidate.Viable = true;
3901 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003902 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003903 Candidate.Conversions.resize(NumArgs + 1);
3904
3905 // Determine the implicit conversion sequence for the implicit
3906 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003907 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003908 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003909 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003910 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003911 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003912 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003913 return;
3914 }
3915
3916 // The first conversion is actually a user-defined conversion whose
3917 // first conversion is ObjectInit's standard conversion (which is
3918 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003919 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003920 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003921 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003922 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003923 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003924 = Candidate.Conversions[0].UserDefined.Before;
3925 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3926
Mike Stump11289f42009-09-09 15:08:12 +00003927 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003928 unsigned NumArgsInProto = Proto->getNumArgs();
3929
3930 // (C++ 13.3.2p2): A candidate function having fewer than m
3931 // parameters is viable only if it has an ellipsis in its parameter
3932 // list (8.3.5).
3933 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3934 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003935 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003936 return;
3937 }
3938
3939 // Function types don't have any default arguments, so just check if
3940 // we have enough arguments.
3941 if (NumArgs < NumArgsInProto) {
3942 // Not enough arguments.
3943 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003944 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003945 return;
3946 }
3947
3948 // Determine the implicit conversion sequences for each of the
3949 // arguments.
3950 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3951 if (ArgIdx < NumArgsInProto) {
3952 // (C++ 13.3.2p3): for F to be a viable function, there shall
3953 // exist for each argument an implicit conversion sequence
3954 // (13.3.3.1) that converts that argument to the corresponding
3955 // parameter of F.
3956 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003957 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003958 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003959 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003960 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003961 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003962 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003963 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003964 break;
3965 }
3966 } else {
3967 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3968 // argument for which there is no corresponding parameter is
3969 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003970 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003971 }
3972 }
3973}
3974
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003975/// \brief Add overload candidates for overloaded operators that are
3976/// member functions.
3977///
3978/// Add the overloaded operator candidates that are member functions
3979/// for the operator Op that was used in an operator expression such
3980/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3981/// CandidateSet will store the added overload candidates. (C++
3982/// [over.match.oper]).
3983void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3984 SourceLocation OpLoc,
3985 Expr **Args, unsigned NumArgs,
3986 OverloadCandidateSet& CandidateSet,
3987 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003988 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3989
3990 // C++ [over.match.oper]p3:
3991 // For a unary operator @ with an operand of a type whose
3992 // cv-unqualified version is T1, and for a binary operator @ with
3993 // a left operand of a type whose cv-unqualified version is T1 and
3994 // a right operand of a type whose cv-unqualified version is T2,
3995 // three sets of candidate functions, designated member
3996 // candidates, non-member candidates and built-in candidates, are
3997 // constructed as follows:
3998 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00003999
4000 // -- If T1 is a class type, the set of member candidates is the
4001 // result of the qualified lookup of T1::operator@
4002 // (13.3.1.1.1); otherwise, the set of member candidates is
4003 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004004 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004005 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004006 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004007 return;
Mike Stump11289f42009-09-09 15:08:12 +00004008
John McCall27b18f82009-11-17 02:14:36 +00004009 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4010 LookupQualifiedName(Operators, T1Rec->getDecl());
4011 Operators.suppressDiagnostics();
4012
Mike Stump11289f42009-09-09 15:08:12 +00004013 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004014 OperEnd = Operators.end();
4015 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004016 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004017 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004018 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004019 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004020 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004021}
4022
Douglas Gregora11693b2008-11-12 17:17:38 +00004023/// AddBuiltinCandidate - Add a candidate for a built-in
4024/// operator. ResultTy and ParamTys are the result and parameter types
4025/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004026/// arguments being passed to the candidate. IsAssignmentOperator
4027/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004028/// operator. NumContextualBoolArguments is the number of arguments
4029/// (at the beginning of the argument list) that will be contextually
4030/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004031void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004032 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004033 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004034 bool IsAssignmentOperator,
4035 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004036 // Overload resolution is always an unevaluated context.
4037 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4038
Douglas Gregora11693b2008-11-12 17:17:38 +00004039 // Add this candidate
4040 CandidateSet.push_back(OverloadCandidate());
4041 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004042 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004043 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004044 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004045 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004046 Candidate.BuiltinTypes.ResultTy = ResultTy;
4047 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4048 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4049
4050 // Determine the implicit conversion sequences for each of the
4051 // arguments.
4052 Candidate.Viable = true;
4053 Candidate.Conversions.resize(NumArgs);
4054 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004055 // C++ [over.match.oper]p4:
4056 // For the built-in assignment operators, conversions of the
4057 // left operand are restricted as follows:
4058 // -- no temporaries are introduced to hold the left operand, and
4059 // -- no user-defined conversions are applied to the left
4060 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004061 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004062 //
4063 // We block these conversions by turning off user-defined
4064 // conversions, since that is the only way that initialization of
4065 // a reference to a non-class type can occur from something that
4066 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004067 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004068 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004069 "Contextual conversion to bool requires bool type");
4070 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4071 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004072 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004073 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004074 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004075 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004076 }
John McCall0d1da222010-01-12 00:44:57 +00004077 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004078 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004079 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004080 break;
4081 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004082 }
4083}
4084
4085/// BuiltinCandidateTypeSet - A set of types that will be used for the
4086/// candidate operator functions for built-in operators (C++
4087/// [over.built]). The types are separated into pointer types and
4088/// enumeration types.
4089class BuiltinCandidateTypeSet {
4090 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004091 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004092
4093 /// PointerTypes - The set of pointer types that will be used in the
4094 /// built-in candidates.
4095 TypeSet PointerTypes;
4096
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004097 /// MemberPointerTypes - The set of member pointer types that will be
4098 /// used in the built-in candidates.
4099 TypeSet MemberPointerTypes;
4100
Douglas Gregora11693b2008-11-12 17:17:38 +00004101 /// EnumerationTypes - The set of enumeration types that will be
4102 /// used in the built-in candidates.
4103 TypeSet EnumerationTypes;
4104
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004105 /// \brief The set of vector types that will be used in the built-in
4106 /// candidates.
4107 TypeSet VectorTypes;
4108
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004109 /// Sema - The semantic analysis instance where we are building the
4110 /// candidate type set.
4111 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004112
Douglas Gregora11693b2008-11-12 17:17:38 +00004113 /// Context - The AST context in which we will build the type sets.
4114 ASTContext &Context;
4115
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004116 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4117 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004118 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004119
4120public:
4121 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004122 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004123
Mike Stump11289f42009-09-09 15:08:12 +00004124 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004125 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004126
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004127 void AddTypesConvertedFrom(QualType Ty,
4128 SourceLocation Loc,
4129 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004130 bool AllowExplicitConversions,
4131 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004132
4133 /// pointer_begin - First pointer type found;
4134 iterator pointer_begin() { return PointerTypes.begin(); }
4135
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004136 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004137 iterator pointer_end() { return PointerTypes.end(); }
4138
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004139 /// member_pointer_begin - First member pointer type found;
4140 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4141
4142 /// member_pointer_end - Past the last member pointer type found;
4143 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4144
Douglas Gregora11693b2008-11-12 17:17:38 +00004145 /// enumeration_begin - First enumeration type found;
4146 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4147
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004148 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004149 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004150
4151 iterator vector_begin() { return VectorTypes.begin(); }
4152 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004153};
4154
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004155/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004156/// the set of pointer types along with any more-qualified variants of
4157/// that type. For example, if @p Ty is "int const *", this routine
4158/// will add "int const *", "int const volatile *", "int const
4159/// restrict *", and "int const volatile restrict *" to the set of
4160/// pointer types. Returns true if the add of @p Ty itself succeeded,
4161/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004162///
4163/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004164bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004165BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4166 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004167
Douglas Gregora11693b2008-11-12 17:17:38 +00004168 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004169 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004170 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004171
4172 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004173 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004174 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004175 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004176 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004177 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004178 buildObjCPtr = true;
4179 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004180 else
4181 assert(false && "type was not a pointer type!");
4182 }
4183 else
4184 PointeeTy = PointerTy->getPointeeType();
4185
Sebastian Redl4990a632009-11-18 20:39:26 +00004186 // Don't add qualified variants of arrays. For one, they're not allowed
4187 // (the qualifier would sink to the element type), and for another, the
4188 // only overload situation where it matters is subscript or pointer +- int,
4189 // and those shouldn't have qualifier variants anyway.
4190 if (PointeeTy->isArrayType())
4191 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004192 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004193 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004194 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004195 bool hasVolatile = VisibleQuals.hasVolatile();
4196 bool hasRestrict = VisibleQuals.hasRestrict();
4197
John McCall8ccfcb52009-09-24 19:53:00 +00004198 // Iterate through all strict supersets of BaseCVR.
4199 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4200 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004201 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4202 // in the types.
4203 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4204 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004205 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004206 if (!buildObjCPtr)
4207 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4208 else
4209 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004210 }
4211
4212 return true;
4213}
4214
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004215/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4216/// to the set of pointer types along with any more-qualified variants of
4217/// that type. For example, if @p Ty is "int const *", this routine
4218/// will add "int const *", "int const volatile *", "int const
4219/// restrict *", and "int const volatile restrict *" to the set of
4220/// pointer types. Returns true if the add of @p Ty itself succeeded,
4221/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004222///
4223/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004224bool
4225BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4226 QualType Ty) {
4227 // Insert this type.
4228 if (!MemberPointerTypes.insert(Ty))
4229 return false;
4230
John McCall8ccfcb52009-09-24 19:53:00 +00004231 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4232 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004233
John McCall8ccfcb52009-09-24 19:53:00 +00004234 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004235 // Don't add qualified variants of arrays. For one, they're not allowed
4236 // (the qualifier would sink to the element type), and for another, the
4237 // only overload situation where it matters is subscript or pointer +- int,
4238 // and those shouldn't have qualifier variants anyway.
4239 if (PointeeTy->isArrayType())
4240 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004241 const Type *ClassTy = PointerTy->getClass();
4242
4243 // Iterate through all strict supersets of the pointee type's CVR
4244 // qualifiers.
4245 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4246 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4247 if ((CVR | BaseCVR) != CVR) continue;
4248
4249 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4250 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004251 }
4252
4253 return true;
4254}
4255
Douglas Gregora11693b2008-11-12 17:17:38 +00004256/// AddTypesConvertedFrom - Add each of the types to which the type @p
4257/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004258/// primarily interested in pointer types and enumeration types. We also
4259/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004260/// AllowUserConversions is true if we should look at the conversion
4261/// functions of a class type, and AllowExplicitConversions if we
4262/// should also include the explicit conversion functions of a class
4263/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004264void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004265BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004266 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004267 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004268 bool AllowExplicitConversions,
4269 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004270 // Only deal with canonical types.
4271 Ty = Context.getCanonicalType(Ty);
4272
4273 // Look through reference types; they aren't part of the type of an
4274 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004275 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004276 Ty = RefTy->getPointeeType();
4277
4278 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004279 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004280
Sebastian Redl65ae2002009-11-05 16:36:20 +00004281 // If we're dealing with an array type, decay to the pointer.
4282 if (Ty->isArrayType())
4283 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004284 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4285 PointerTypes.insert(Ty);
4286 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004287 // Insert our type, and its more-qualified variants, into the set
4288 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004289 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004290 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004291 } else if (Ty->isMemberPointerType()) {
4292 // Member pointers are far easier, since the pointee can't be converted.
4293 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4294 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004295 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004296 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004297 } else if (Ty->isVectorType()) {
4298 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004299 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004300 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004301 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004302 // No conversion functions in incomplete types.
4303 return;
4304 }
Mike Stump11289f42009-09-09 15:08:12 +00004305
Douglas Gregora11693b2008-11-12 17:17:38 +00004306 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004307 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004308 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004309 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004310 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004311 NamedDecl *D = I.getDecl();
4312 if (isa<UsingShadowDecl>(D))
4313 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004314
Mike Stump11289f42009-09-09 15:08:12 +00004315 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004316 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004317 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004318 continue;
4319
John McCallda4458e2010-03-31 01:36:47 +00004320 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004321 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004322 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004323 VisibleQuals);
4324 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004325 }
4326 }
4327 }
4328}
4329
Douglas Gregor84605ae2009-08-24 13:43:27 +00004330/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4331/// the volatile- and non-volatile-qualified assignment operators for the
4332/// given type to the candidate set.
4333static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4334 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004335 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004336 unsigned NumArgs,
4337 OverloadCandidateSet &CandidateSet) {
4338 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004339
Douglas Gregor84605ae2009-08-24 13:43:27 +00004340 // T& operator=(T&, T)
4341 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4342 ParamTypes[1] = T;
4343 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4344 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004345
Douglas Gregor84605ae2009-08-24 13:43:27 +00004346 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4347 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004348 ParamTypes[0]
4349 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004350 ParamTypes[1] = T;
4351 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004352 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004353 }
4354}
Mike Stump11289f42009-09-09 15:08:12 +00004355
Sebastian Redl1054fae2009-10-25 17:03:50 +00004356/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4357/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004358static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4359 Qualifiers VRQuals;
4360 const RecordType *TyRec;
4361 if (const MemberPointerType *RHSMPType =
4362 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004363 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004364 else
4365 TyRec = ArgExpr->getType()->getAs<RecordType>();
4366 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004367 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004368 VRQuals.addVolatile();
4369 VRQuals.addRestrict();
4370 return VRQuals;
4371 }
4372
4373 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004374 if (!ClassDecl->hasDefinition())
4375 return VRQuals;
4376
John McCallad371252010-01-20 00:46:10 +00004377 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004378 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004379
John McCallad371252010-01-20 00:46:10 +00004380 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004381 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004382 NamedDecl *D = I.getDecl();
4383 if (isa<UsingShadowDecl>(D))
4384 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4385 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004386 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4387 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4388 CanTy = ResTypeRef->getPointeeType();
4389 // Need to go down the pointer/mempointer chain and add qualifiers
4390 // as see them.
4391 bool done = false;
4392 while (!done) {
4393 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4394 CanTy = ResTypePtr->getPointeeType();
4395 else if (const MemberPointerType *ResTypeMPtr =
4396 CanTy->getAs<MemberPointerType>())
4397 CanTy = ResTypeMPtr->getPointeeType();
4398 else
4399 done = true;
4400 if (CanTy.isVolatileQualified())
4401 VRQuals.addVolatile();
4402 if (CanTy.isRestrictQualified())
4403 VRQuals.addRestrict();
4404 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4405 return VRQuals;
4406 }
4407 }
4408 }
4409 return VRQuals;
4410}
4411
Douglas Gregord08452f2008-11-19 15:42:04 +00004412/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4413/// operator overloads to the candidate set (C++ [over.built]), based
4414/// on the operator @p Op and the arguments given. For example, if the
4415/// operator is a binary '+', this routine might add "int
4416/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004417void
Mike Stump11289f42009-09-09 15:08:12 +00004418Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004419 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004420 Expr **Args, unsigned NumArgs,
4421 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004422 // The set of "promoted arithmetic types", which are the arithmetic
4423 // types are that preserved by promotion (C++ [over.built]p2). Note
4424 // that the first few of these types are the promoted integral
4425 // types; these types need to be first.
4426 // FIXME: What about complex?
4427 const unsigned FirstIntegralType = 0;
4428 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004429 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004430 LastPromotedIntegralType = 13;
4431 const unsigned FirstPromotedArithmeticType = 7,
4432 LastPromotedArithmeticType = 16;
4433 const unsigned NumArithmeticTypes = 16;
4434 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004435 Context.BoolTy, Context.CharTy, Context.WCharTy,
4436// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004437 Context.SignedCharTy, Context.ShortTy,
4438 Context.UnsignedCharTy, Context.UnsignedShortTy,
4439 Context.IntTy, Context.LongTy, Context.LongLongTy,
4440 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4441 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4442 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004443 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4444 "Invalid first promoted integral type");
4445 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4446 == Context.UnsignedLongLongTy &&
4447 "Invalid last promoted integral type");
4448 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4449 "Invalid first promoted arithmetic type");
4450 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4451 == Context.LongDoubleTy &&
4452 "Invalid last promoted arithmetic type");
4453
Douglas Gregora11693b2008-11-12 17:17:38 +00004454 // Find all of the types that the arguments can convert to, but only
4455 // if the operator we're looking at has built-in operator candidates
4456 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004457 Qualifiers VisibleTypeConversionsQuals;
4458 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004459 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4460 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4461
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004462 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004463 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4464 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4465 OpLoc,
4466 true,
4467 (Op == OO_Exclaim ||
4468 Op == OO_AmpAmp ||
4469 Op == OO_PipePipe),
4470 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004471
4472 bool isComparison = false;
4473 switch (Op) {
4474 case OO_None:
4475 case NUM_OVERLOADED_OPERATORS:
4476 assert(false && "Expected an overloaded operator");
4477 break;
4478
Douglas Gregord08452f2008-11-19 15:42:04 +00004479 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004480 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004481 goto UnaryStar;
4482 else
4483 goto BinaryStar;
4484 break;
4485
4486 case OO_Plus: // '+' is either unary or binary
4487 if (NumArgs == 1)
4488 goto UnaryPlus;
4489 else
4490 goto BinaryPlus;
4491 break;
4492
4493 case OO_Minus: // '-' is either unary or binary
4494 if (NumArgs == 1)
4495 goto UnaryMinus;
4496 else
4497 goto BinaryMinus;
4498 break;
4499
4500 case OO_Amp: // '&' is either unary or binary
4501 if (NumArgs == 1)
4502 goto UnaryAmp;
4503 else
4504 goto BinaryAmp;
4505
4506 case OO_PlusPlus:
4507 case OO_MinusMinus:
4508 // C++ [over.built]p3:
4509 //
4510 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4511 // is either volatile or empty, there exist candidate operator
4512 // functions of the form
4513 //
4514 // VQ T& operator++(VQ T&);
4515 // T operator++(VQ T&, int);
4516 //
4517 // C++ [over.built]p4:
4518 //
4519 // For every pair (T, VQ), where T is an arithmetic type other
4520 // than bool, and VQ is either volatile or empty, there exist
4521 // candidate operator functions of the form
4522 //
4523 // VQ T& operator--(VQ T&);
4524 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004525 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004526 Arith < NumArithmeticTypes; ++Arith) {
4527 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004528 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004529 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004530
4531 // Non-volatile version.
4532 if (NumArgs == 1)
4533 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4534 else
4535 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004536 // heuristic to reduce number of builtin candidates in the set.
4537 // Add volatile version only if there are conversions to a volatile type.
4538 if (VisibleTypeConversionsQuals.hasVolatile()) {
4539 // Volatile version
4540 ParamTypes[0]
4541 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4542 if (NumArgs == 1)
4543 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4544 else
4545 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4546 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004547 }
4548
4549 // C++ [over.built]p5:
4550 //
4551 // For every pair (T, VQ), where T is a cv-qualified or
4552 // cv-unqualified object type, and VQ is either volatile or
4553 // empty, there exist candidate operator functions of the form
4554 //
4555 // T*VQ& operator++(T*VQ&);
4556 // T*VQ& operator--(T*VQ&);
4557 // T* operator++(T*VQ&, int);
4558 // T* operator--(T*VQ&, int);
4559 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4560 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4561 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004562 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004563 continue;
4564
Mike Stump11289f42009-09-09 15:08:12 +00004565 QualType ParamTypes[2] = {
4566 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004567 };
Mike Stump11289f42009-09-09 15:08:12 +00004568
Douglas Gregord08452f2008-11-19 15:42:04 +00004569 // Without volatile
4570 if (NumArgs == 1)
4571 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4572 else
4573 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4574
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004575 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4576 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004577 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004578 ParamTypes[0]
4579 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004580 if (NumArgs == 1)
4581 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4582 else
4583 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4584 }
4585 }
4586 break;
4587
4588 UnaryStar:
4589 // C++ [over.built]p6:
4590 // For every cv-qualified or cv-unqualified object type T, there
4591 // exist candidate operator functions of the form
4592 //
4593 // T& operator*(T*);
4594 //
4595 // C++ [over.built]p7:
4596 // For every function type T, there exist candidate operator
4597 // functions of the form
4598 // T& operator*(T*);
4599 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4600 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4601 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004602 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004603 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004604 &ParamTy, Args, 1, CandidateSet);
4605 }
4606 break;
4607
4608 UnaryPlus:
4609 // C++ [over.built]p8:
4610 // For every type T, there exist candidate operator functions of
4611 // the form
4612 //
4613 // T* operator+(T*);
4614 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4615 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4616 QualType ParamTy = *Ptr;
4617 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4618 }
Mike Stump11289f42009-09-09 15:08:12 +00004619
Douglas Gregord08452f2008-11-19 15:42:04 +00004620 // Fall through
4621
4622 UnaryMinus:
4623 // C++ [over.built]p9:
4624 // For every promoted arithmetic type T, there exist candidate
4625 // operator functions of the form
4626 //
4627 // T operator+(T);
4628 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004629 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004630 Arith < LastPromotedArithmeticType; ++Arith) {
4631 QualType ArithTy = ArithmeticTypes[Arith];
4632 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4633 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004634
4635 // Extension: We also add these operators for vector types.
4636 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4637 VecEnd = CandidateTypes.vector_end();
4638 Vec != VecEnd; ++Vec) {
4639 QualType VecTy = *Vec;
4640 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4641 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004642 break;
4643
4644 case OO_Tilde:
4645 // C++ [over.built]p10:
4646 // For every promoted integral type T, there exist candidate
4647 // operator functions of the form
4648 //
4649 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004650 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004651 Int < LastPromotedIntegralType; ++Int) {
4652 QualType IntTy = ArithmeticTypes[Int];
4653 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4654 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004655
4656 // Extension: We also add this operator for vector types.
4657 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4658 VecEnd = CandidateTypes.vector_end();
4659 Vec != VecEnd; ++Vec) {
4660 QualType VecTy = *Vec;
4661 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4662 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004663 break;
4664
Douglas Gregora11693b2008-11-12 17:17:38 +00004665 case OO_New:
4666 case OO_Delete:
4667 case OO_Array_New:
4668 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004669 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004670 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004671 break;
4672
4673 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004674 UnaryAmp:
4675 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004676 // C++ [over.match.oper]p3:
4677 // -- For the operator ',', the unary operator '&', or the
4678 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004679 break;
4680
Douglas Gregor84605ae2009-08-24 13:43:27 +00004681 case OO_EqualEqual:
4682 case OO_ExclaimEqual:
4683 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004684 // For every pointer to member type T, there exist candidate operator
4685 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004686 //
4687 // bool operator==(T,T);
4688 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004689 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004690 MemPtr = CandidateTypes.member_pointer_begin(),
4691 MemPtrEnd = CandidateTypes.member_pointer_end();
4692 MemPtr != MemPtrEnd;
4693 ++MemPtr) {
4694 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4695 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4696 }
Mike Stump11289f42009-09-09 15:08:12 +00004697
Douglas Gregor84605ae2009-08-24 13:43:27 +00004698 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004699
Douglas Gregora11693b2008-11-12 17:17:38 +00004700 case OO_Less:
4701 case OO_Greater:
4702 case OO_LessEqual:
4703 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004704 // C++ [over.built]p15:
4705 //
4706 // For every pointer or enumeration type T, there exist
4707 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004708 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004709 // bool operator<(T, T);
4710 // bool operator>(T, T);
4711 // bool operator<=(T, T);
4712 // bool operator>=(T, T);
4713 // bool operator==(T, T);
4714 // bool operator!=(T, T);
4715 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4716 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4717 QualType ParamTypes[2] = { *Ptr, *Ptr };
4718 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4719 }
Mike Stump11289f42009-09-09 15:08:12 +00004720 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004721 = CandidateTypes.enumeration_begin();
4722 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4723 QualType ParamTypes[2] = { *Enum, *Enum };
4724 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4725 }
4726
4727 // Fall through.
4728 isComparison = true;
4729
Douglas Gregord08452f2008-11-19 15:42:04 +00004730 BinaryPlus:
4731 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004732 if (!isComparison) {
4733 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4734
4735 // C++ [over.built]p13:
4736 //
4737 // For every cv-qualified or cv-unqualified object type T
4738 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004739 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004740 // T* operator+(T*, ptrdiff_t);
4741 // T& operator[](T*, ptrdiff_t); [BELOW]
4742 // T* operator-(T*, ptrdiff_t);
4743 // T* operator+(ptrdiff_t, T*);
4744 // T& operator[](ptrdiff_t, T*); [BELOW]
4745 //
4746 // C++ [over.built]p14:
4747 //
4748 // For every T, where T is a pointer to object type, there
4749 // exist candidate operator functions of the form
4750 //
4751 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004752 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004753 = CandidateTypes.pointer_begin();
4754 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4755 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4756
4757 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4758 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4759
4760 if (Op == OO_Plus) {
4761 // T* operator+(ptrdiff_t, T*);
4762 ParamTypes[0] = ParamTypes[1];
4763 ParamTypes[1] = *Ptr;
4764 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4765 } else {
4766 // ptrdiff_t operator-(T, T);
4767 ParamTypes[1] = *Ptr;
4768 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4769 Args, 2, CandidateSet);
4770 }
4771 }
4772 }
4773 // Fall through
4774
Douglas Gregora11693b2008-11-12 17:17:38 +00004775 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004776 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004777 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004778 // C++ [over.built]p12:
4779 //
4780 // For every pair of promoted arithmetic types L and R, there
4781 // exist candidate operator functions of the form
4782 //
4783 // LR operator*(L, R);
4784 // LR operator/(L, R);
4785 // LR operator+(L, R);
4786 // LR operator-(L, R);
4787 // bool operator<(L, R);
4788 // bool operator>(L, R);
4789 // bool operator<=(L, R);
4790 // bool operator>=(L, R);
4791 // bool operator==(L, R);
4792 // bool operator!=(L, R);
4793 //
4794 // where LR is the result of the usual arithmetic conversions
4795 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004796 //
4797 // C++ [over.built]p24:
4798 //
4799 // For every pair of promoted arithmetic types L and R, there exist
4800 // candidate operator functions of the form
4801 //
4802 // LR operator?(bool, L, R);
4803 //
4804 // where LR is the result of the usual arithmetic conversions
4805 // between types L and R.
4806 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004807 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004808 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004809 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004810 Right < LastPromotedArithmeticType; ++Right) {
4811 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004812 QualType Result
4813 = isComparison
4814 ? Context.BoolTy
4815 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004816 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4817 }
4818 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004819
4820 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4821 // conditional operator for vector types.
4822 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4823 Vec1End = CandidateTypes.vector_end();
4824 Vec1 != Vec1End; ++Vec1)
4825 for (BuiltinCandidateTypeSet::iterator
4826 Vec2 = CandidateTypes.vector_begin(),
4827 Vec2End = CandidateTypes.vector_end();
4828 Vec2 != Vec2End; ++Vec2) {
4829 QualType LandR[2] = { *Vec1, *Vec2 };
4830 QualType Result;
4831 if (isComparison)
4832 Result = Context.BoolTy;
4833 else {
4834 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4835 Result = *Vec1;
4836 else
4837 Result = *Vec2;
4838 }
4839
4840 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4841 }
4842
Douglas Gregora11693b2008-11-12 17:17:38 +00004843 break;
4844
4845 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004846 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004847 case OO_Caret:
4848 case OO_Pipe:
4849 case OO_LessLess:
4850 case OO_GreaterGreater:
4851 // C++ [over.built]p17:
4852 //
4853 // For every pair of promoted integral types L and R, there
4854 // exist candidate operator functions of the form
4855 //
4856 // LR operator%(L, R);
4857 // LR operator&(L, R);
4858 // LR operator^(L, R);
4859 // LR operator|(L, R);
4860 // L operator<<(L, R);
4861 // L operator>>(L, R);
4862 //
4863 // where LR is the result of the usual arithmetic conversions
4864 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004865 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004866 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004867 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004868 Right < LastPromotedIntegralType; ++Right) {
4869 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4870 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4871 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004872 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004873 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4874 }
4875 }
4876 break;
4877
4878 case OO_Equal:
4879 // C++ [over.built]p20:
4880 //
4881 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004882 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004883 // empty, there exist candidate operator functions of the form
4884 //
4885 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004886 for (BuiltinCandidateTypeSet::iterator
4887 Enum = CandidateTypes.enumeration_begin(),
4888 EnumEnd = CandidateTypes.enumeration_end();
4889 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004890 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004891 CandidateSet);
4892 for (BuiltinCandidateTypeSet::iterator
4893 MemPtr = CandidateTypes.member_pointer_begin(),
4894 MemPtrEnd = CandidateTypes.member_pointer_end();
4895 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004896 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004897 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004898
4899 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004900
4901 case OO_PlusEqual:
4902 case OO_MinusEqual:
4903 // C++ [over.built]p19:
4904 //
4905 // For every pair (T, VQ), where T is any type and VQ is either
4906 // volatile or empty, there exist candidate operator functions
4907 // of the form
4908 //
4909 // T*VQ& operator=(T*VQ&, T*);
4910 //
4911 // C++ [over.built]p21:
4912 //
4913 // For every pair (T, VQ), where T is a cv-qualified or
4914 // cv-unqualified object type and VQ is either volatile or
4915 // empty, there exist candidate operator functions of the form
4916 //
4917 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4918 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4919 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4920 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4921 QualType ParamTypes[2];
4922 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4923
4924 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004925 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004926 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4927 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004928
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004929 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4930 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004931 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004932 ParamTypes[0]
4933 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004934 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4935 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004936 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004937 }
4938 // Fall through.
4939
4940 case OO_StarEqual:
4941 case OO_SlashEqual:
4942 // C++ [over.built]p18:
4943 //
4944 // For every triple (L, VQ, R), where L is an arithmetic type,
4945 // VQ is either volatile or empty, and R is a promoted
4946 // arithmetic type, there exist candidate operator functions of
4947 // the form
4948 //
4949 // VQ L& operator=(VQ L&, R);
4950 // VQ L& operator*=(VQ L&, R);
4951 // VQ L& operator/=(VQ L&, R);
4952 // VQ L& operator+=(VQ L&, R);
4953 // VQ L& operator-=(VQ L&, R);
4954 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004955 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004956 Right < LastPromotedArithmeticType; ++Right) {
4957 QualType ParamTypes[2];
4958 ParamTypes[1] = ArithmeticTypes[Right];
4959
4960 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004961 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004962 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4963 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004964
4965 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004966 if (VisibleTypeConversionsQuals.hasVolatile()) {
4967 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4968 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4969 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4970 /*IsAssigmentOperator=*/Op == OO_Equal);
4971 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004972 }
4973 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004974
4975 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4976 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4977 Vec1End = CandidateTypes.vector_end();
4978 Vec1 != Vec1End; ++Vec1)
4979 for (BuiltinCandidateTypeSet::iterator
4980 Vec2 = CandidateTypes.vector_begin(),
4981 Vec2End = CandidateTypes.vector_end();
4982 Vec2 != Vec2End; ++Vec2) {
4983 QualType ParamTypes[2];
4984 ParamTypes[1] = *Vec2;
4985 // Add this built-in operator as a candidate (VQ is empty).
4986 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4987 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4988 /*IsAssigmentOperator=*/Op == OO_Equal);
4989
4990 // Add this built-in operator as a candidate (VQ is 'volatile').
4991 if (VisibleTypeConversionsQuals.hasVolatile()) {
4992 ParamTypes[0] = Context.getVolatileType(*Vec1);
4993 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4994 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4995 /*IsAssigmentOperator=*/Op == OO_Equal);
4996 }
4997 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004998 break;
4999
5000 case OO_PercentEqual:
5001 case OO_LessLessEqual:
5002 case OO_GreaterGreaterEqual:
5003 case OO_AmpEqual:
5004 case OO_CaretEqual:
5005 case OO_PipeEqual:
5006 // C++ [over.built]p22:
5007 //
5008 // For every triple (L, VQ, R), where L is an integral type, VQ
5009 // is either volatile or empty, and R is a promoted integral
5010 // type, there exist candidate operator functions of the form
5011 //
5012 // VQ L& operator%=(VQ L&, R);
5013 // VQ L& operator<<=(VQ L&, R);
5014 // VQ L& operator>>=(VQ L&, R);
5015 // VQ L& operator&=(VQ L&, R);
5016 // VQ L& operator^=(VQ L&, R);
5017 // VQ L& operator|=(VQ L&, R);
5018 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005019 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005020 Right < LastPromotedIntegralType; ++Right) {
5021 QualType ParamTypes[2];
5022 ParamTypes[1] = ArithmeticTypes[Right];
5023
5024 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005025 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005026 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005027 if (VisibleTypeConversionsQuals.hasVolatile()) {
5028 // Add this built-in operator as a candidate (VQ is 'volatile').
5029 ParamTypes[0] = ArithmeticTypes[Left];
5030 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5031 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5032 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5033 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005034 }
5035 }
5036 break;
5037
Douglas Gregord08452f2008-11-19 15:42:04 +00005038 case OO_Exclaim: {
5039 // C++ [over.operator]p23:
5040 //
5041 // There also exist candidate operator functions of the form
5042 //
Mike Stump11289f42009-09-09 15:08:12 +00005043 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005044 // bool operator&&(bool, bool); [BELOW]
5045 // bool operator||(bool, bool); [BELOW]
5046 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005047 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5048 /*IsAssignmentOperator=*/false,
5049 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005050 break;
5051 }
5052
Douglas Gregora11693b2008-11-12 17:17:38 +00005053 case OO_AmpAmp:
5054 case OO_PipePipe: {
5055 // C++ [over.operator]p23:
5056 //
5057 // There also exist candidate operator functions of the form
5058 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005059 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005060 // bool operator&&(bool, bool);
5061 // bool operator||(bool, bool);
5062 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005063 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5064 /*IsAssignmentOperator=*/false,
5065 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005066 break;
5067 }
5068
5069 case OO_Subscript:
5070 // C++ [over.built]p13:
5071 //
5072 // For every cv-qualified or cv-unqualified object type T there
5073 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005074 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005075 // T* operator+(T*, ptrdiff_t); [ABOVE]
5076 // T& operator[](T*, ptrdiff_t);
5077 // T* operator-(T*, ptrdiff_t); [ABOVE]
5078 // T* operator+(ptrdiff_t, T*); [ABOVE]
5079 // T& operator[](ptrdiff_t, T*);
5080 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5081 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5082 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005083 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005084 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005085
5086 // T& operator[](T*, ptrdiff_t)
5087 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5088
5089 // T& operator[](ptrdiff_t, T*);
5090 ParamTypes[0] = ParamTypes[1];
5091 ParamTypes[1] = *Ptr;
5092 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005093 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005094 break;
5095
5096 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005097 // C++ [over.built]p11:
5098 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5099 // C1 is the same type as C2 or is a derived class of C2, T is an object
5100 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5101 // there exist candidate operator functions of the form
5102 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5103 // where CV12 is the union of CV1 and CV2.
5104 {
5105 for (BuiltinCandidateTypeSet::iterator Ptr =
5106 CandidateTypes.pointer_begin();
5107 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5108 QualType C1Ty = (*Ptr);
5109 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005110 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005111 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5112 if (!isa<RecordType>(C1))
5113 continue;
5114 // heuristic to reduce number of builtin candidates in the set.
5115 // Add volatile/restrict version only if there are conversions to a
5116 // volatile/restrict type.
5117 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5118 continue;
5119 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5120 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005121 for (BuiltinCandidateTypeSet::iterator
5122 MemPtr = CandidateTypes.member_pointer_begin(),
5123 MemPtrEnd = CandidateTypes.member_pointer_end();
5124 MemPtr != MemPtrEnd; ++MemPtr) {
5125 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5126 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005127 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005128 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5129 break;
5130 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5131 // build CV12 T&
5132 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005133 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5134 T.isVolatileQualified())
5135 continue;
5136 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5137 T.isRestrictQualified())
5138 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005139 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005140 QualType ResultTy = Context.getLValueReferenceType(T);
5141 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5142 }
5143 }
5144 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005145 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005146
5147 case OO_Conditional:
5148 // Note that we don't consider the first argument, since it has been
5149 // contextually converted to bool long ago. The candidates below are
5150 // therefore added as binary.
5151 //
5152 // C++ [over.built]p24:
5153 // For every type T, where T is a pointer or pointer-to-member type,
5154 // there exist candidate operator functions of the form
5155 //
5156 // T operator?(bool, T, T);
5157 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005158 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5159 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5160 QualType ParamTypes[2] = { *Ptr, *Ptr };
5161 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5162 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005163 for (BuiltinCandidateTypeSet::iterator Ptr =
5164 CandidateTypes.member_pointer_begin(),
5165 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5166 QualType ParamTypes[2] = { *Ptr, *Ptr };
5167 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5168 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005169 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005170 }
5171}
5172
Douglas Gregore254f902009-02-04 00:32:51 +00005173/// \brief Add function candidates found via argument-dependent lookup
5174/// to the set of overloading candidates.
5175///
5176/// This routine performs argument-dependent name lookup based on the
5177/// given function name (which may also be an operator name) and adds
5178/// all of the overload candidates found by ADL to the overload
5179/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005180void
Douglas Gregore254f902009-02-04 00:32:51 +00005181Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005182 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005183 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005184 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005185 OverloadCandidateSet& CandidateSet,
5186 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005187 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005188
John McCall91f61fc2010-01-26 06:04:06 +00005189 // FIXME: This approach for uniquing ADL results (and removing
5190 // redundant candidates from the set) relies on pointer-equality,
5191 // which means we need to key off the canonical decl. However,
5192 // always going back to the canonical decl might not get us the
5193 // right set of default arguments. What default arguments are
5194 // we supposed to consider on ADL candidates, anyway?
5195
Douglas Gregorcabea402009-09-22 15:41:20 +00005196 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005197 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005198
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005199 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005200 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5201 CandEnd = CandidateSet.end();
5202 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005203 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005204 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005205 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005206 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005207 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005208
5209 // For each of the ADL candidates we found, add it to the overload
5210 // set.
John McCall8fe68082010-01-26 07:16:45 +00005211 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005212 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005213 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005214 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005215 continue;
5216
John McCalla0296f72010-03-19 07:35:19 +00005217 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005218 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005219 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005220 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005221 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005222 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005223 }
Douglas Gregore254f902009-02-04 00:32:51 +00005224}
5225
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005226/// isBetterOverloadCandidate - Determines whether the first overload
5227/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005228bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005229Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00005230 const OverloadCandidate& Cand2,
5231 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005232 // Define viable functions to be better candidates than non-viable
5233 // functions.
5234 if (!Cand2.Viable)
5235 return Cand1.Viable;
5236 else if (!Cand1.Viable)
5237 return false;
5238
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005239 // C++ [over.match.best]p1:
5240 //
5241 // -- if F is a static member function, ICS1(F) is defined such
5242 // that ICS1(F) is neither better nor worse than ICS1(G) for
5243 // any function G, and, symmetrically, ICS1(G) is neither
5244 // better nor worse than ICS1(F).
5245 unsigned StartArg = 0;
5246 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5247 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005248
Douglas Gregord3cb3562009-07-07 23:38:56 +00005249 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005250 // A viable function F1 is defined to be a better function than another
5251 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005252 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005253 unsigned NumArgs = Cand1.Conversions.size();
5254 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5255 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005256 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005257 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5258 Cand2.Conversions[ArgIdx])) {
5259 case ImplicitConversionSequence::Better:
5260 // Cand1 has a better conversion sequence.
5261 HasBetterConversion = true;
5262 break;
5263
5264 case ImplicitConversionSequence::Worse:
5265 // Cand1 can't be better than Cand2.
5266 return false;
5267
5268 case ImplicitConversionSequence::Indistinguishable:
5269 // Do nothing.
5270 break;
5271 }
5272 }
5273
Mike Stump11289f42009-09-09 15:08:12 +00005274 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005275 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005276 if (HasBetterConversion)
5277 return true;
5278
Mike Stump11289f42009-09-09 15:08:12 +00005279 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005280 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005281 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005282 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5283 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005284
5285 // -- F1 and F2 are function template specializations, and the function
5286 // template for F1 is more specialized than the template for F2
5287 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005288 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005289 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5290 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005291 if (FunctionTemplateDecl *BetterTemplate
5292 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5293 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005294 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005295 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5296 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005297 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005298
Douglas Gregora1f013e2008-11-07 22:36:19 +00005299 // -- the context is an initialization by user-defined conversion
5300 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5301 // from the return type of F1 to the destination type (i.e.,
5302 // the type of the entity being initialized) is a better
5303 // conversion sequence than the standard conversion sequence
5304 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005305 if (Cand1.Function && Cand2.Function &&
5306 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005307 isa<CXXConversionDecl>(Cand2.Function)) {
5308 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5309 Cand2.FinalConversion)) {
5310 case ImplicitConversionSequence::Better:
5311 // Cand1 has a better conversion sequence.
5312 return true;
5313
5314 case ImplicitConversionSequence::Worse:
5315 // Cand1 can't be better than Cand2.
5316 return false;
5317
5318 case ImplicitConversionSequence::Indistinguishable:
5319 // Do nothing
5320 break;
5321 }
5322 }
5323
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005324 return false;
5325}
5326
Mike Stump11289f42009-09-09 15:08:12 +00005327/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005328/// within an overload candidate set.
5329///
5330/// \param CandidateSet the set of candidate functions.
5331///
5332/// \param Loc the location of the function name (or operator symbol) for
5333/// which overload resolution occurs.
5334///
Mike Stump11289f42009-09-09 15:08:12 +00005335/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005336/// function, Best points to the candidate function found.
5337///
5338/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005339OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5340 SourceLocation Loc,
5341 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005342 // Find the best viable function.
5343 Best = CandidateSet.end();
5344 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5345 Cand != CandidateSet.end(); ++Cand) {
5346 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005347 if (Best == CandidateSet.end() ||
5348 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005349 Best = Cand;
5350 }
5351 }
5352
5353 // If we didn't find any viable functions, abort.
5354 if (Best == CandidateSet.end())
5355 return OR_No_Viable_Function;
5356
5357 // Make sure that this function is better than every other viable
5358 // function. If not, we have an ambiguity.
5359 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5360 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005361 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005362 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005363 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005364 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005365 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005366 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005367 }
Mike Stump11289f42009-09-09 15:08:12 +00005368
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005369 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005370 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005371 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005372 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005373 return OR_Deleted;
5374
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005375 // C++ [basic.def.odr]p2:
5376 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005377 // when referred to from a potentially-evaluated expression. [Note: this
5378 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005379 // (clause 13), user-defined conversions (12.3.2), allocation function for
5380 // placement new (5.3.4), as well as non-default initialization (8.5).
5381 if (Best->Function)
5382 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005383 return OR_Success;
5384}
5385
John McCall53262c92010-01-12 02:15:36 +00005386namespace {
5387
5388enum OverloadCandidateKind {
5389 oc_function,
5390 oc_method,
5391 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005392 oc_function_template,
5393 oc_method_template,
5394 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005395 oc_implicit_default_constructor,
5396 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005397 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005398};
5399
John McCalle1ac8d12010-01-13 00:25:19 +00005400OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5401 FunctionDecl *Fn,
5402 std::string &Description) {
5403 bool isTemplate = false;
5404
5405 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5406 isTemplate = true;
5407 Description = S.getTemplateArgumentBindingsText(
5408 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5409 }
John McCallfd0b2f82010-01-06 09:43:14 +00005410
5411 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005412 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005413 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005414
John McCall53262c92010-01-12 02:15:36 +00005415 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5416 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005417 }
5418
5419 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5420 // This actually gets spelled 'candidate function' for now, but
5421 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005422 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005423 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005424
5425 assert(Meth->isCopyAssignment()
5426 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005427 return oc_implicit_copy_assignment;
5428 }
5429
John McCalle1ac8d12010-01-13 00:25:19 +00005430 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005431}
5432
5433} // end anonymous namespace
5434
5435// Notes the location of an overload candidate.
5436void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005437 std::string FnDesc;
5438 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5439 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5440 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005441}
5442
John McCall0d1da222010-01-12 00:44:57 +00005443/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5444/// "lead" diagnostic; it will be given two arguments, the source and
5445/// target types of the conversion.
5446void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5447 SourceLocation CaretLoc,
5448 const PartialDiagnostic &PDiag) {
5449 Diag(CaretLoc, PDiag)
5450 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5451 for (AmbiguousConversionSequence::const_iterator
5452 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5453 NoteOverloadCandidate(*I);
5454 }
John McCall12f97bc2010-01-08 04:41:39 +00005455}
5456
John McCall0d1da222010-01-12 00:44:57 +00005457namespace {
5458
John McCall6a61b522010-01-13 09:16:55 +00005459void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5460 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5461 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005462 assert(Cand->Function && "for now, candidate must be a function");
5463 FunctionDecl *Fn = Cand->Function;
5464
5465 // There's a conversion slot for the object argument if this is a
5466 // non-constructor method. Note that 'I' corresponds the
5467 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005468 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005469 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005470 if (I == 0)
5471 isObjectArgument = true;
5472 else
5473 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005474 }
5475
John McCalle1ac8d12010-01-13 00:25:19 +00005476 std::string FnDesc;
5477 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5478
John McCall6a61b522010-01-13 09:16:55 +00005479 Expr *FromExpr = Conv.Bad.FromExpr;
5480 QualType FromTy = Conv.Bad.getFromType();
5481 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005482
John McCallfb7ad0f2010-02-02 02:42:52 +00005483 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005484 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005485 Expr *E = FromExpr->IgnoreParens();
5486 if (isa<UnaryOperator>(E))
5487 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005488 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005489
5490 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5491 << (unsigned) FnKind << FnDesc
5492 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5493 << ToTy << Name << I+1;
5494 return;
5495 }
5496
John McCall6d174642010-01-23 08:10:49 +00005497 // Do some hand-waving analysis to see if the non-viability is due
5498 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005499 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5500 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5501 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5502 CToTy = RT->getPointeeType();
5503 else {
5504 // TODO: detect and diagnose the full richness of const mismatches.
5505 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5506 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5507 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5508 }
5509
5510 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5511 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5512 // It is dumb that we have to do this here.
5513 while (isa<ArrayType>(CFromTy))
5514 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5515 while (isa<ArrayType>(CToTy))
5516 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5517
5518 Qualifiers FromQs = CFromTy.getQualifiers();
5519 Qualifiers ToQs = CToTy.getQualifiers();
5520
5521 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5522 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5523 << (unsigned) FnKind << FnDesc
5524 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5525 << FromTy
5526 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5527 << (unsigned) isObjectArgument << I+1;
5528 return;
5529 }
5530
5531 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5532 assert(CVR && "unexpected qualifiers mismatch");
5533
5534 if (isObjectArgument) {
5535 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5536 << (unsigned) FnKind << FnDesc
5537 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5538 << FromTy << (CVR - 1);
5539 } else {
5540 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5541 << (unsigned) FnKind << FnDesc
5542 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5543 << FromTy << (CVR - 1) << I+1;
5544 }
5545 return;
5546 }
5547
John McCall6d174642010-01-23 08:10:49 +00005548 // Diagnose references or pointers to incomplete types differently,
5549 // since it's far from impossible that the incompleteness triggered
5550 // the failure.
5551 QualType TempFromTy = FromTy.getNonReferenceType();
5552 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5553 TempFromTy = PTy->getPointeeType();
5554 if (TempFromTy->isIncompleteType()) {
5555 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5556 << (unsigned) FnKind << FnDesc
5557 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5558 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5559 return;
5560 }
5561
Douglas Gregor56f2e342010-06-30 23:01:39 +00005562 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005563 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005564 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5565 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5566 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5567 FromPtrTy->getPointeeType()) &&
5568 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5569 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5570 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5571 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005572 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005573 }
5574 } else if (const ObjCObjectPointerType *FromPtrTy
5575 = FromTy->getAs<ObjCObjectPointerType>()) {
5576 if (const ObjCObjectPointerType *ToPtrTy
5577 = ToTy->getAs<ObjCObjectPointerType>())
5578 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5579 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5580 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5581 FromPtrTy->getPointeeType()) &&
5582 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005583 BaseToDerivedConversion = 2;
5584 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5585 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5586 !FromTy->isIncompleteType() &&
5587 !ToRefTy->getPointeeType()->isIncompleteType() &&
5588 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5589 BaseToDerivedConversion = 3;
5590 }
5591
5592 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005593 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005594 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005595 << (unsigned) FnKind << FnDesc
5596 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005597 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005598 << FromTy << ToTy << I+1;
5599 return;
5600 }
5601
John McCall47000992010-01-14 03:28:57 +00005602 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005603 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5604 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005605 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005606 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005607}
5608
5609void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5610 unsigned NumFormalArgs) {
5611 // TODO: treat calls to a missing default constructor as a special case
5612
5613 FunctionDecl *Fn = Cand->Function;
5614 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5615
5616 unsigned MinParams = Fn->getMinRequiredArguments();
5617
5618 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005619 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005620 unsigned mode, modeCount;
5621 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005622 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5623 (Cand->FailureKind == ovl_fail_bad_deduction &&
5624 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005625 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5626 mode = 0; // "at least"
5627 else
5628 mode = 2; // "exactly"
5629 modeCount = MinParams;
5630 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005631 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5632 (Cand->FailureKind == ovl_fail_bad_deduction &&
5633 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005634 if (MinParams != FnTy->getNumArgs())
5635 mode = 1; // "at most"
5636 else
5637 mode = 2; // "exactly"
5638 modeCount = FnTy->getNumArgs();
5639 }
5640
5641 std::string Description;
5642 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5643
5644 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005645 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5646 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005647}
5648
John McCall8b9ed552010-02-01 18:53:26 +00005649/// Diagnose a failed template-argument deduction.
5650void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5651 Expr **Args, unsigned NumArgs) {
5652 FunctionDecl *Fn = Cand->Function; // pattern
5653
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005654 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005655 NamedDecl *ParamD;
5656 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5657 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5658 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005659 switch (Cand->DeductionFailure.Result) {
5660 case Sema::TDK_Success:
5661 llvm_unreachable("TDK_success while diagnosing bad deduction");
5662
5663 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005664 assert(ParamD && "no parameter found for incomplete deduction result");
5665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5666 << ParamD->getDeclName();
5667 return;
5668 }
5669
John McCall42d7d192010-08-05 09:05:08 +00005670 case Sema::TDK_Underqualified: {
5671 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5672 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5673
5674 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5675
5676 // Param will have been canonicalized, but it should just be a
5677 // qualified version of ParamD, so move the qualifiers to that.
5678 QualifierCollector Qs(S.Context);
5679 Qs.strip(Param);
5680 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5681 assert(S.Context.hasSameType(Param, NonCanonParam));
5682
5683 // Arg has also been canonicalized, but there's nothing we can do
5684 // about that. It also doesn't matter as much, because it won't
5685 // have any template parameters in it (because deduction isn't
5686 // done on dependent types).
5687 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5688
5689 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5690 << ParamD->getDeclName() << Arg << NonCanonParam;
5691 return;
5692 }
5693
5694 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005695 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005696 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005697 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005698 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005699 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005700 which = 1;
5701 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005702 which = 2;
5703 }
5704
5705 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5706 << which << ParamD->getDeclName()
5707 << *Cand->DeductionFailure.getFirstArg()
5708 << *Cand->DeductionFailure.getSecondArg();
5709 return;
5710 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005711
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005712 case Sema::TDK_InvalidExplicitArguments:
5713 assert(ParamD && "no parameter found for invalid explicit arguments");
5714 if (ParamD->getDeclName())
5715 S.Diag(Fn->getLocation(),
5716 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5717 << ParamD->getDeclName();
5718 else {
5719 int index = 0;
5720 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5721 index = TTP->getIndex();
5722 else if (NonTypeTemplateParmDecl *NTTP
5723 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5724 index = NTTP->getIndex();
5725 else
5726 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5727 S.Diag(Fn->getLocation(),
5728 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5729 << (index + 1);
5730 }
5731 return;
5732
Douglas Gregor02eb4832010-05-08 18:13:28 +00005733 case Sema::TDK_TooManyArguments:
5734 case Sema::TDK_TooFewArguments:
5735 DiagnoseArityMismatch(S, Cand, NumArgs);
5736 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005737
5738 case Sema::TDK_InstantiationDepth:
5739 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5740 return;
5741
5742 case Sema::TDK_SubstitutionFailure: {
5743 std::string ArgString;
5744 if (TemplateArgumentList *Args
5745 = Cand->DeductionFailure.getTemplateArgumentList())
5746 ArgString = S.getTemplateArgumentBindingsText(
5747 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5748 *Args);
5749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5750 << ArgString;
5751 return;
5752 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005753
John McCall8b9ed552010-02-01 18:53:26 +00005754 // TODO: diagnose these individually, then kill off
5755 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005756 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005757 case Sema::TDK_FailedOverloadResolution:
5758 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5759 return;
5760 }
5761}
5762
5763/// Generates a 'note' diagnostic for an overload candidate. We've
5764/// already generated a primary error at the call site.
5765///
5766/// It really does need to be a single diagnostic with its caret
5767/// pointed at the candidate declaration. Yes, this creates some
5768/// major challenges of technical writing. Yes, this makes pointing
5769/// out problems with specific arguments quite awkward. It's still
5770/// better than generating twenty screens of text for every failed
5771/// overload.
5772///
5773/// It would be great to be able to express per-candidate problems
5774/// more richly for those diagnostic clients that cared, but we'd
5775/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005776void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5777 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005778 FunctionDecl *Fn = Cand->Function;
5779
John McCall12f97bc2010-01-08 04:41:39 +00005780 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005781 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005782 std::string FnDesc;
5783 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005784
5785 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005786 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005787 return;
John McCall12f97bc2010-01-08 04:41:39 +00005788 }
5789
John McCalle1ac8d12010-01-13 00:25:19 +00005790 // We don't really have anything else to say about viable candidates.
5791 if (Cand->Viable) {
5792 S.NoteOverloadCandidate(Fn);
5793 return;
5794 }
John McCall0d1da222010-01-12 00:44:57 +00005795
John McCall6a61b522010-01-13 09:16:55 +00005796 switch (Cand->FailureKind) {
5797 case ovl_fail_too_many_arguments:
5798 case ovl_fail_too_few_arguments:
5799 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005800
John McCall6a61b522010-01-13 09:16:55 +00005801 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005802 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5803
John McCallfe796dd2010-01-23 05:17:32 +00005804 case ovl_fail_trivial_conversion:
5805 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005806 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005807 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005808
John McCall65eb8792010-02-25 01:37:24 +00005809 case ovl_fail_bad_conversion: {
5810 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5811 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005812 if (Cand->Conversions[I].isBad())
5813 return DiagnoseBadConversion(S, Cand, I);
5814
5815 // FIXME: this currently happens when we're called from SemaInit
5816 // when user-conversion overload fails. Figure out how to handle
5817 // those conditions and diagnose them well.
5818 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005819 }
John McCall65eb8792010-02-25 01:37:24 +00005820 }
John McCalld3224162010-01-08 00:58:21 +00005821}
5822
5823void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5824 // Desugar the type of the surrogate down to a function type,
5825 // retaining as many typedefs as possible while still showing
5826 // the function type (and, therefore, its parameter types).
5827 QualType FnType = Cand->Surrogate->getConversionType();
5828 bool isLValueReference = false;
5829 bool isRValueReference = false;
5830 bool isPointer = false;
5831 if (const LValueReferenceType *FnTypeRef =
5832 FnType->getAs<LValueReferenceType>()) {
5833 FnType = FnTypeRef->getPointeeType();
5834 isLValueReference = true;
5835 } else if (const RValueReferenceType *FnTypeRef =
5836 FnType->getAs<RValueReferenceType>()) {
5837 FnType = FnTypeRef->getPointeeType();
5838 isRValueReference = true;
5839 }
5840 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5841 FnType = FnTypePtr->getPointeeType();
5842 isPointer = true;
5843 }
5844 // Desugar down to a function type.
5845 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5846 // Reconstruct the pointer/reference as appropriate.
5847 if (isPointer) FnType = S.Context.getPointerType(FnType);
5848 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5849 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5850
5851 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5852 << FnType;
5853}
5854
5855void NoteBuiltinOperatorCandidate(Sema &S,
5856 const char *Opc,
5857 SourceLocation OpLoc,
5858 OverloadCandidate *Cand) {
5859 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5860 std::string TypeStr("operator");
5861 TypeStr += Opc;
5862 TypeStr += "(";
5863 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5864 if (Cand->Conversions.size() == 1) {
5865 TypeStr += ")";
5866 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5867 } else {
5868 TypeStr += ", ";
5869 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5870 TypeStr += ")";
5871 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5872 }
5873}
5874
5875void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5876 OverloadCandidate *Cand) {
5877 unsigned NoOperands = Cand->Conversions.size();
5878 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5879 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005880 if (ICS.isBad()) break; // all meaningless after first invalid
5881 if (!ICS.isAmbiguous()) continue;
5882
5883 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005884 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005885 }
5886}
5887
John McCall3712d9e2010-01-15 23:32:50 +00005888SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5889 if (Cand->Function)
5890 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005891 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005892 return Cand->Surrogate->getLocation();
5893 return SourceLocation();
5894}
5895
John McCallad2587a2010-01-12 00:48:53 +00005896struct CompareOverloadCandidatesForDisplay {
5897 Sema &S;
5898 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005899
5900 bool operator()(const OverloadCandidate *L,
5901 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005902 // Fast-path this check.
5903 if (L == R) return false;
5904
John McCall12f97bc2010-01-08 04:41:39 +00005905 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005906 if (L->Viable) {
5907 if (!R->Viable) return true;
5908
5909 // TODO: introduce a tri-valued comparison for overload
5910 // candidates. Would be more worthwhile if we had a sort
5911 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005912 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5913 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005914 } else if (R->Viable)
5915 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005916
John McCall3712d9e2010-01-15 23:32:50 +00005917 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005918
John McCall3712d9e2010-01-15 23:32:50 +00005919 // Criteria by which we can sort non-viable candidates:
5920 if (!L->Viable) {
5921 // 1. Arity mismatches come after other candidates.
5922 if (L->FailureKind == ovl_fail_too_many_arguments ||
5923 L->FailureKind == ovl_fail_too_few_arguments)
5924 return false;
5925 if (R->FailureKind == ovl_fail_too_many_arguments ||
5926 R->FailureKind == ovl_fail_too_few_arguments)
5927 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005928
John McCallfe796dd2010-01-23 05:17:32 +00005929 // 2. Bad conversions come first and are ordered by the number
5930 // of bad conversions and quality of good conversions.
5931 if (L->FailureKind == ovl_fail_bad_conversion) {
5932 if (R->FailureKind != ovl_fail_bad_conversion)
5933 return true;
5934
5935 // If there's any ordering between the defined conversions...
5936 // FIXME: this might not be transitive.
5937 assert(L->Conversions.size() == R->Conversions.size());
5938
5939 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005940 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5941 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005942 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5943 R->Conversions[I])) {
5944 case ImplicitConversionSequence::Better:
5945 leftBetter++;
5946 break;
5947
5948 case ImplicitConversionSequence::Worse:
5949 leftBetter--;
5950 break;
5951
5952 case ImplicitConversionSequence::Indistinguishable:
5953 break;
5954 }
5955 }
5956 if (leftBetter > 0) return true;
5957 if (leftBetter < 0) return false;
5958
5959 } else if (R->FailureKind == ovl_fail_bad_conversion)
5960 return false;
5961
John McCall3712d9e2010-01-15 23:32:50 +00005962 // TODO: others?
5963 }
5964
5965 // Sort everything else by location.
5966 SourceLocation LLoc = GetLocationForCandidate(L);
5967 SourceLocation RLoc = GetLocationForCandidate(R);
5968
5969 // Put candidates without locations (e.g. builtins) at the end.
5970 if (LLoc.isInvalid()) return false;
5971 if (RLoc.isInvalid()) return true;
5972
5973 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005974 }
5975};
5976
John McCallfe796dd2010-01-23 05:17:32 +00005977/// CompleteNonViableCandidate - Normally, overload resolution only
5978/// computes up to the first
5979void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5980 Expr **Args, unsigned NumArgs) {
5981 assert(!Cand->Viable);
5982
5983 // Don't do anything on failures other than bad conversion.
5984 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5985
5986 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005987 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005988 unsigned ConvCount = Cand->Conversions.size();
5989 while (true) {
5990 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5991 ConvIdx++;
5992 if (Cand->Conversions[ConvIdx - 1].isBad())
5993 break;
5994 }
5995
5996 if (ConvIdx == ConvCount)
5997 return;
5998
John McCall65eb8792010-02-25 01:37:24 +00005999 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6000 "remaining conversion is initialized?");
6001
Douglas Gregoradc7a702010-04-16 17:45:54 +00006002 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006003 // operation somehow.
6004 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006005
6006 const FunctionProtoType* Proto;
6007 unsigned ArgIdx = ConvIdx;
6008
6009 if (Cand->IsSurrogate) {
6010 QualType ConvType
6011 = Cand->Surrogate->getConversionType().getNonReferenceType();
6012 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6013 ConvType = ConvPtrType->getPointeeType();
6014 Proto = ConvType->getAs<FunctionProtoType>();
6015 ArgIdx--;
6016 } else if (Cand->Function) {
6017 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6018 if (isa<CXXMethodDecl>(Cand->Function) &&
6019 !isa<CXXConstructorDecl>(Cand->Function))
6020 ArgIdx--;
6021 } else {
6022 // Builtin binary operator with a bad first conversion.
6023 assert(ConvCount <= 3);
6024 for (; ConvIdx != ConvCount; ++ConvIdx)
6025 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006026 = TryCopyInitialization(S, Args[ConvIdx],
6027 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6028 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006029 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006030 return;
6031 }
6032
6033 // Fill in the rest of the conversions.
6034 unsigned NumArgsInProto = Proto->getNumArgs();
6035 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6036 if (ArgIdx < NumArgsInProto)
6037 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006038 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6039 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006040 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006041 else
6042 Cand->Conversions[ConvIdx].setEllipsis();
6043 }
6044}
6045
John McCalld3224162010-01-08 00:58:21 +00006046} // end anonymous namespace
6047
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006048/// PrintOverloadCandidates - When overload resolution fails, prints
6049/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006050/// set.
Mike Stump11289f42009-09-09 15:08:12 +00006051void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006052Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00006053 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00006054 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006055 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00006056 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006057 // Sort the candidates by viability and position. Sorting directly would
6058 // be prohibitive, so we make a set of pointers and sort those.
6059 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6060 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
6061 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6062 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00006063 Cand != LastCand; ++Cand) {
6064 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006065 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006066 else if (OCD == OCD_AllCandidates) {
6067 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006068 if (Cand->Function || Cand->IsSurrogate)
6069 Cands.push_back(Cand);
6070 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6071 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006072 }
6073 }
6074
John McCallad2587a2010-01-12 00:48:53 +00006075 std::sort(Cands.begin(), Cands.end(),
6076 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00006077
John McCall0d1da222010-01-12 00:44:57 +00006078 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006079
John McCall12f97bc2010-01-08 04:41:39 +00006080 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006081 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6082 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006083 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6084 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006085
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006086 // Set an arbitrary limit on the number of candidate functions we'll spam
6087 // the user with. FIXME: This limit should depend on details of the
6088 // candidate list.
6089 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6090 break;
6091 }
6092 ++CandsShown;
6093
John McCalld3224162010-01-08 00:58:21 +00006094 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00006095 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006096 else if (Cand->IsSurrogate)
6097 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006098 else {
6099 assert(Cand->Viable &&
6100 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006101 // Generally we only see ambiguities including viable builtin
6102 // operators if overload resolution got screwed up by an
6103 // ambiguous user-defined conversion.
6104 //
6105 // FIXME: It's quite possible for different conversions to see
6106 // different ambiguities, though.
6107 if (!ReportedAmbiguousConversions) {
6108 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6109 ReportedAmbiguousConversions = true;
6110 }
John McCalld3224162010-01-08 00:58:21 +00006111
John McCall0d1da222010-01-12 00:44:57 +00006112 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00006113 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006114 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006115 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006116
6117 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00006118 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006119}
6120
John McCalla0296f72010-03-19 07:35:19 +00006121static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006122 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006123 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006124
John McCalla0296f72010-03-19 07:35:19 +00006125 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006126}
6127
Douglas Gregorcd695e52008-11-10 20:40:00 +00006128/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6129/// an overloaded function (C++ [over.over]), where @p From is an
6130/// expression with overloaded function type and @p ToType is the type
6131/// we're trying to resolve to. For example:
6132///
6133/// @code
6134/// int f(double);
6135/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006136///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006137/// int (*pfd)(double) = f; // selects f(double)
6138/// @endcode
6139///
6140/// This routine returns the resulting FunctionDecl if it could be
6141/// resolved, and NULL otherwise. When @p Complain is true, this
6142/// routine will emit diagnostics if there is an error.
6143FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006144Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006145 bool Complain,
6146 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006147 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006148 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006149 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006150 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006151 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006152 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006153 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006154 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006155 FunctionType = MemTypePtr->getPointeeType();
6156 IsMember = true;
6157 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006158
Douglas Gregorcd695e52008-11-10 20:40:00 +00006159 // C++ [over.over]p1:
6160 // [...] [Note: any redundant set of parentheses surrounding the
6161 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006162 // C++ [over.over]p1:
6163 // [...] The overloaded function name can be preceded by the &
6164 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006165 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6166 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6167 if (OvlExpr->hasExplicitTemplateArgs()) {
6168 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6169 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006170 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00006171
6172 // We expect a pointer or reference to function, or a function pointer.
6173 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6174 if (!FunctionType->isFunctionType()) {
6175 if (Complain)
6176 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6177 << OvlExpr->getName() << ToType;
6178
6179 return 0;
6180 }
6181
6182 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006183
Douglas Gregorcd695e52008-11-10 20:40:00 +00006184 // Look through all of the overloaded functions, searching for one
6185 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006186 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006187 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6188
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006189 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006190 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6191 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006192 // Look through any using declarations to find the underlying function.
6193 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6194
Douglas Gregorcd695e52008-11-10 20:40:00 +00006195 // C++ [over.over]p3:
6196 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006197 // targets of type "pointer-to-function" or "reference-to-function."
6198 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006199 // type "pointer-to-member-function."
6200 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006201
Mike Stump11289f42009-09-09 15:08:12 +00006202 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006203 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006204 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006205 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006206 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006207 // static when converting to member pointer.
6208 if (Method->isStatic() == IsMember)
6209 continue;
6210 } else if (IsMember)
6211 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006212
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006213 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006214 // If the name is a function template, template argument deduction is
6215 // done (14.8.2.2), and if the argument deduction succeeds, the
6216 // resulting template argument list is used to generate a single
6217 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006218 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006219 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006220 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006221 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006222 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006223 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006224 FunctionType, Specialization, Info)) {
6225 // FIXME: make a note of the failed deduction for diagnostics.
6226 (void)Result;
6227 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006228 // FIXME: If the match isn't exact, shouldn't we just drop this as
6229 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006230 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006231 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006232 Matches.push_back(std::make_pair(I.getPair(),
6233 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006234 }
John McCalld14a8642009-11-21 08:51:07 +00006235
6236 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006237 }
Mike Stump11289f42009-09-09 15:08:12 +00006238
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006239 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006240 // Skip non-static functions when converting to pointer, and static
6241 // when converting to member pointer.
6242 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006243 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006244
6245 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006246 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006247 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006248 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006249 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006250
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006251 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006252 QualType ResultTy;
6253 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6254 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6255 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006256 Matches.push_back(std::make_pair(I.getPair(),
6257 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006258 FoundNonTemplateFunction = true;
6259 }
Mike Stump11289f42009-09-09 15:08:12 +00006260 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006261 }
6262
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006263 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006264 if (Matches.empty()) {
6265 if (Complain) {
6266 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6267 << OvlExpr->getName() << FunctionType;
6268 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6269 E = OvlExpr->decls_end();
6270 I != E; ++I)
6271 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6272 NoteOverloadCandidate(F);
6273 }
6274
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006275 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006276 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006277 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006278 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006279 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006280 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006281 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006282 return Result;
6283 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006284
6285 // C++ [over.over]p4:
6286 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006287 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006288 // [...] and any given function template specialization F1 is
6289 // eliminated if the set contains a second function template
6290 // specialization whose function template is more specialized
6291 // than the function template of F1 according to the partial
6292 // ordering rules of 14.5.5.2.
6293
6294 // The algorithm specified above is quadratic. We instead use a
6295 // two-pass algorithm (similar to the one used to identify the
6296 // best viable function in an overload set) that identifies the
6297 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006298
6299 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6300 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6301 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006302
6303 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006304 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006305 TPOC_Other, From->getLocStart(),
6306 PDiag(),
6307 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006308 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006309 PDiag(diag::note_ovl_candidate)
6310 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006311 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006312 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006313 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006314 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006315 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006316 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6317 }
John McCall58cc69d2010-01-27 01:50:18 +00006318 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006319 }
Mike Stump11289f42009-09-09 15:08:12 +00006320
Douglas Gregorfae1d712009-09-26 03:56:17 +00006321 // [...] any function template specializations in the set are
6322 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006323 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006324 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006325 ++I;
6326 else {
John McCalla0296f72010-03-19 07:35:19 +00006327 Matches[I] = Matches[--N];
6328 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006329 }
6330 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006331
Mike Stump11289f42009-09-09 15:08:12 +00006332 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006333 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006334 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006335 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006336 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006337 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006338 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006339 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6340 }
John McCalla0296f72010-03-19 07:35:19 +00006341 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006342 }
Mike Stump11289f42009-09-09 15:08:12 +00006343
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006344 // FIXME: We should probably return the same thing that BestViableFunction
6345 // returns (even if we issue the diagnostics here).
6346 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006347 << Matches[0].second->getDeclName();
6348 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6349 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006350 return 0;
6351}
6352
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006353/// \brief Given an expression that refers to an overloaded function, try to
6354/// resolve that overloaded function expression down to a single function.
6355///
6356/// This routine can only resolve template-ids that refer to a single function
6357/// template, where that template-id refers to a single template whose template
6358/// arguments are either provided by the template-id or have defaults,
6359/// as described in C++0x [temp.arg.explicit]p3.
6360FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6361 // C++ [over.over]p1:
6362 // [...] [Note: any redundant set of parentheses surrounding the
6363 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006364 // C++ [over.over]p1:
6365 // [...] The overloaded function name can be preceded by the &
6366 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006367
6368 if (From->getType() != Context.OverloadTy)
6369 return 0;
6370
6371 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006372
6373 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006374 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006375 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006376
6377 TemplateArgumentListInfo ExplicitTemplateArgs;
6378 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006379
6380 // Look through all of the overloaded functions, searching for one
6381 // whose type matches exactly.
6382 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006383 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6384 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006385 // C++0x [temp.arg.explicit]p3:
6386 // [...] In contexts where deduction is done and fails, or in contexts
6387 // where deduction is not done, if a template argument list is
6388 // specified and it, along with any default template arguments,
6389 // identifies a single function template specialization, then the
6390 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006391 FunctionTemplateDecl *FunctionTemplate
6392 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006393
6394 // C++ [over.over]p2:
6395 // If the name is a function template, template argument deduction is
6396 // done (14.8.2.2), and if the argument deduction succeeds, the
6397 // resulting template argument list is used to generate a single
6398 // function template specialization, which is added to the set of
6399 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006400 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006401 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006402 if (TemplateDeductionResult Result
6403 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6404 Specialization, Info)) {
6405 // FIXME: make a note of the failed deduction for diagnostics.
6406 (void)Result;
6407 continue;
6408 }
6409
6410 // Multiple matches; we can't resolve to a single declaration.
6411 if (Matched)
6412 return 0;
6413
6414 Matched = Specialization;
6415 }
6416
6417 return Matched;
6418}
6419
Douglas Gregorcabea402009-09-22 15:41:20 +00006420/// \brief Add a single candidate to the overload set.
6421static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006422 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006423 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006424 Expr **Args, unsigned NumArgs,
6425 OverloadCandidateSet &CandidateSet,
6426 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006427 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006428 if (isa<UsingShadowDecl>(Callee))
6429 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6430
Douglas Gregorcabea402009-09-22 15:41:20 +00006431 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006432 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006433 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006434 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006435 return;
John McCalld14a8642009-11-21 08:51:07 +00006436 }
6437
6438 if (FunctionTemplateDecl *FuncTemplate
6439 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006440 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6441 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006442 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006443 return;
6444 }
6445
6446 assert(false && "unhandled case in overloaded call candidate");
6447
6448 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006449}
6450
6451/// \brief Add the overload candidates named by callee and/or found by argument
6452/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006453void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006454 Expr **Args, unsigned NumArgs,
6455 OverloadCandidateSet &CandidateSet,
6456 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006457
6458#ifndef NDEBUG
6459 // Verify that ArgumentDependentLookup is consistent with the rules
6460 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006461 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006462 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6463 // and let Y be the lookup set produced by argument dependent
6464 // lookup (defined as follows). If X contains
6465 //
6466 // -- a declaration of a class member, or
6467 //
6468 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006469 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006470 //
6471 // -- a declaration that is neither a function or a function
6472 // template
6473 //
6474 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006475
John McCall57500772009-12-16 12:17:52 +00006476 if (ULE->requiresADL()) {
6477 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6478 E = ULE->decls_end(); I != E; ++I) {
6479 assert(!(*I)->getDeclContext()->isRecord());
6480 assert(isa<UsingShadowDecl>(*I) ||
6481 !(*I)->getDeclContext()->isFunctionOrMethod());
6482 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006483 }
6484 }
6485#endif
6486
John McCall57500772009-12-16 12:17:52 +00006487 // It would be nice to avoid this copy.
6488 TemplateArgumentListInfo TABuffer;
6489 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6490 if (ULE->hasExplicitTemplateArgs()) {
6491 ULE->copyTemplateArgumentsInto(TABuffer);
6492 ExplicitTemplateArgs = &TABuffer;
6493 }
6494
6495 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6496 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006497 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006498 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006499 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006500
John McCall57500772009-12-16 12:17:52 +00006501 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006502 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6503 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006504 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006505 CandidateSet,
6506 PartialOverloading);
6507}
John McCalld681c392009-12-16 08:11:27 +00006508
6509/// Attempts to recover from a call where no functions were found.
6510///
6511/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006512static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006513BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006514 UnresolvedLookupExpr *ULE,
6515 SourceLocation LParenLoc,
6516 Expr **Args, unsigned NumArgs,
6517 SourceLocation *CommaLocs,
6518 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006519
6520 CXXScopeSpec SS;
6521 if (ULE->getQualifier()) {
6522 SS.setScopeRep(ULE->getQualifier());
6523 SS.setRange(ULE->getQualifierRange());
6524 }
6525
John McCall57500772009-12-16 12:17:52 +00006526 TemplateArgumentListInfo TABuffer;
6527 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6528 if (ULE->hasExplicitTemplateArgs()) {
6529 ULE->copyTemplateArgumentsInto(TABuffer);
6530 ExplicitTemplateArgs = &TABuffer;
6531 }
6532
John McCalld681c392009-12-16 08:11:27 +00006533 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6534 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006535 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorb412e172010-07-25 18:17:45 +00006536 return SemaRef.ExprError();
John McCalld681c392009-12-16 08:11:27 +00006537
John McCall57500772009-12-16 12:17:52 +00006538 assert(!R.empty() && "lookup results empty despite recovery");
6539
6540 // Build an implicit member call if appropriate. Just drop the
6541 // casts and such from the call, we don't really care.
6542 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6543 if ((*R.begin())->isCXXClassMember())
6544 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6545 else if (ExplicitTemplateArgs)
6546 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6547 else
6548 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6549
6550 if (NewFn.isInvalid())
Douglas Gregorb412e172010-07-25 18:17:45 +00006551 return SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006552
6553 // This shouldn't cause an infinite loop because we're giving it
6554 // an expression with non-empty lookup results, which should never
6555 // end up here.
6556 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
John McCall37ad5512010-08-23 06:44:23 +00006557 Sema::MultiExprArg(SemaRef, Args, NumArgs),
John McCall57500772009-12-16 12:17:52 +00006558 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006559}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006560
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006561/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006562/// (which eventually refers to the declaration Func) and the call
6563/// arguments Args/NumArgs, attempt to resolve the function call down
6564/// to a specific function. If overload resolution succeeds, returns
6565/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006566/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006567/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006568Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006569Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006570 SourceLocation LParenLoc,
6571 Expr **Args, unsigned NumArgs,
6572 SourceLocation *CommaLocs,
6573 SourceLocation RParenLoc) {
6574#ifndef NDEBUG
6575 if (ULE->requiresADL()) {
6576 // To do ADL, we must have found an unqualified name.
6577 assert(!ULE->getQualifier() && "qualified name with ADL");
6578
6579 // We don't perform ADL for implicit declarations of builtins.
6580 // Verify that this was correctly set up.
6581 FunctionDecl *F;
6582 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6583 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6584 F->getBuiltinID() && F->isImplicit())
6585 assert(0 && "performing ADL for builtin");
6586
6587 // We don't perform ADL in C.
6588 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6589 }
6590#endif
6591
John McCallbc077cf2010-02-08 23:07:23 +00006592 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006593
John McCall57500772009-12-16 12:17:52 +00006594 // Add the functions denoted by the callee to the set of candidate
6595 // functions, including those from argument-dependent lookup.
6596 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006597
6598 // If we found nothing, try to recover.
6599 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6600 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006601 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006602 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006603 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006604
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006605 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006606 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006607 case OR_Success: {
6608 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006609 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006610 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006611 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006612 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6613 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006614
6615 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006616 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006617 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006618 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006619 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006620 break;
6621
6622 case OR_Ambiguous:
6623 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006624 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006625 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006626 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006627
6628 case OR_Deleted:
6629 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6630 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006631 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006632 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006633 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006634 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006635 }
6636
Douglas Gregorb412e172010-07-25 18:17:45 +00006637 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006638 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006639}
6640
John McCall4c4c1df2010-01-26 03:27:55 +00006641static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006642 return Functions.size() > 1 ||
6643 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6644}
6645
Douglas Gregor084d8552009-03-13 23:49:33 +00006646/// \brief Create a unary operation that may resolve to an overloaded
6647/// operator.
6648///
6649/// \param OpLoc The location of the operator itself (e.g., '*').
6650///
6651/// \param OpcIn The UnaryOperator::Opcode that describes this
6652/// operator.
6653///
6654/// \param Functions The set of non-member functions that will be
6655/// considered by overload resolution. The caller needs to build this
6656/// set based on the context using, e.g.,
6657/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6658/// set should not contain any member functions; those will be added
6659/// by CreateOverloadedUnaryOp().
6660///
6661/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006662Sema::OwningExprResult
6663Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6664 const UnresolvedSetImpl &Fns,
6665 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006666 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6667 Expr *Input = (Expr *)input.get();
6668
6669 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6670 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6671 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006672 // TODO: provide better source location info.
6673 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006674
6675 Expr *Args[2] = { Input, 0 };
6676 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006677
Douglas Gregor084d8552009-03-13 23:49:33 +00006678 // For post-increment and post-decrement, add the implicit '0' as
6679 // the second argument, so that we know this is a post-increment or
6680 // post-decrement.
6681 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6682 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006683 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006684 SourceLocation());
6685 NumArgs = 2;
6686 }
6687
6688 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006689 if (Fns.empty())
6690 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6691 Opc,
6692 Context.DependentTy,
6693 OpLoc));
6694
John McCall58cc69d2010-01-27 01:50:18 +00006695 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006696 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006697 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006698 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006699 /*ADL*/ true, IsOverloaded(Fns),
6700 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006701 input.release();
6702 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6703 &Args[0], NumArgs,
6704 Context.DependentTy,
6705 OpLoc));
6706 }
6707
6708 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006709 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006710
6711 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006712 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006713
6714 // Add operator candidates that are member functions.
6715 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6716
John McCall4c4c1df2010-01-26 03:27:55 +00006717 // Add candidates from ADL.
6718 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006719 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006720 /*ExplicitTemplateArgs*/ 0,
6721 CandidateSet);
6722
Douglas Gregor084d8552009-03-13 23:49:33 +00006723 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006724 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006725
6726 // Perform overload resolution.
6727 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006728 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006729 case OR_Success: {
6730 // We found a built-in operator or an overloaded operator.
6731 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006732
Douglas Gregor084d8552009-03-13 23:49:33 +00006733 if (FnDecl) {
6734 // We matched an overloaded operator. Build a call to that
6735 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006736
Douglas Gregor084d8552009-03-13 23:49:33 +00006737 // Convert the arguments.
6738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006739 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006740
John McCall16df1e52010-03-30 21:47:33 +00006741 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6742 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006743 return ExprError();
6744 } else {
6745 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006746 OwningExprResult InputInit
6747 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006748 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006749 SourceLocation(),
6750 move(input));
6751 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006752 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006753
Douglas Gregore6600372009-12-23 17:40:29 +00006754 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006755 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006756 }
6757
John McCall4fa0d5f2010-05-06 18:15:07 +00006758 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6759
Douglas Gregor084d8552009-03-13 23:49:33 +00006760 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006761 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006762
Douglas Gregor084d8552009-03-13 23:49:33 +00006763 // Build the actual expression node.
6764 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6765 SourceLocation());
6766 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006767
Douglas Gregor084d8552009-03-13 23:49:33 +00006768 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006769 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006770 ExprOwningPtr<CallExpr> TheCall(this,
6771 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006772 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006773
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006774 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6775 FnDecl))
6776 return ExprError();
6777
6778 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006779 } else {
6780 // We matched a built-in operator. Convert the arguments, then
6781 // break out so that we will build the appropriate built-in
6782 // operator node.
6783 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006784 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006785 return ExprError();
6786
6787 break;
6788 }
6789 }
6790
6791 case OR_No_Viable_Function:
6792 // No viable function; fall through to handling this as a
6793 // built-in operator, which will produce an error message for us.
6794 break;
6795
6796 case OR_Ambiguous:
6797 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6798 << UnaryOperator::getOpcodeStr(Opc)
6799 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006800 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006801 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006802 return ExprError();
6803
6804 case OR_Deleted:
6805 Diag(OpLoc, diag::err_ovl_deleted_oper)
6806 << Best->Function->isDeleted()
6807 << UnaryOperator::getOpcodeStr(Opc)
6808 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006809 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006810 return ExprError();
6811 }
6812
6813 // Either we found no viable overloaded operator or we matched a
6814 // built-in operator. In either case, fall through to trying to
6815 // build a built-in operation.
6816 input.release();
6817 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6818}
6819
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006820/// \brief Create a binary operation that may resolve to an overloaded
6821/// operator.
6822///
6823/// \param OpLoc The location of the operator itself (e.g., '+').
6824///
6825/// \param OpcIn The BinaryOperator::Opcode that describes this
6826/// operator.
6827///
6828/// \param Functions The set of non-member functions that will be
6829/// considered by overload resolution. The caller needs to build this
6830/// set based on the context using, e.g.,
6831/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6832/// set should not contain any member functions; those will be added
6833/// by CreateOverloadedBinOp().
6834///
6835/// \param LHS Left-hand argument.
6836/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006837Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006838Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006839 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006840 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006841 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006842 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006843 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006844
6845 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6846 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6848
6849 // If either side is type-dependent, create an appropriate dependent
6850 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006851 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006852 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006853 // If there are no functions to store, just build a dependent
6854 // BinaryOperator or CompoundAssignment.
6855 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6856 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6857 Context.DependentTy, OpLoc));
6858
6859 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6860 Context.DependentTy,
6861 Context.DependentTy,
6862 Context.DependentTy,
6863 OpLoc));
6864 }
John McCall4c4c1df2010-01-26 03:27:55 +00006865
6866 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006867 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006868 // TODO: provide better source location info in DNLoc component.
6869 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006870 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006871 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006872 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006873 /*ADL*/ true, IsOverloaded(Fns),
6874 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006875 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006876 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006877 Context.DependentTy,
6878 OpLoc));
6879 }
6880
6881 // If this is the .* operator, which is not overloadable, just
6882 // create a built-in binary operator.
6883 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006884 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006885
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006886 // If this is the assignment operator, we only perform overload resolution
6887 // if the left-hand side is a class or enumeration type. This is actually
6888 // a hack. The standard requires that we do overload resolution between the
6889 // various built-in candidates, but as DR507 points out, this can lead to
6890 // problems. So we do it this way, which pretty much follows what GCC does.
6891 // Note that we go the traditional code path for compound assignment forms.
6892 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006893 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006894
Douglas Gregor084d8552009-03-13 23:49:33 +00006895 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006896 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006897
6898 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006899 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006900
6901 // Add operator candidates that are member functions.
6902 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6903
John McCall4c4c1df2010-01-26 03:27:55 +00006904 // Add candidates from ADL.
6905 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6906 Args, 2,
6907 /*ExplicitTemplateArgs*/ 0,
6908 CandidateSet);
6909
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006910 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006911 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006912
6913 // Perform overload resolution.
6914 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006915 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006916 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006917 // We found a built-in operator or an overloaded operator.
6918 FunctionDecl *FnDecl = Best->Function;
6919
6920 if (FnDecl) {
6921 // We matched an overloaded operator. Build a call to that
6922 // operator.
6923
6924 // Convert the arguments.
6925 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006926 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006927 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006928
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006929 OwningExprResult Arg1
6930 = PerformCopyInitialization(
6931 InitializedEntity::InitializeParameter(
6932 FnDecl->getParamDecl(0)),
6933 SourceLocation(),
6934 Owned(Args[1]));
6935 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006936 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006937
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006938 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006939 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006940 return ExprError();
6941
6942 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006943 } else {
6944 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006945 OwningExprResult Arg0
6946 = PerformCopyInitialization(
6947 InitializedEntity::InitializeParameter(
6948 FnDecl->getParamDecl(0)),
6949 SourceLocation(),
6950 Owned(Args[0]));
6951 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006952 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006953
6954 OwningExprResult Arg1
6955 = PerformCopyInitialization(
6956 InitializedEntity::InitializeParameter(
6957 FnDecl->getParamDecl(1)),
6958 SourceLocation(),
6959 Owned(Args[1]));
6960 if (Arg1.isInvalid())
6961 return ExprError();
6962 Args[0] = LHS = Arg0.takeAs<Expr>();
6963 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006964 }
6965
John McCall4fa0d5f2010-05-06 18:15:07 +00006966 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6967
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006968 // Determine the result type
6969 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00006970 = FnDecl->getType()->getAs<FunctionType>()
6971 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006972
6973 // Build the actual expression node.
6974 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006975 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006976 UsualUnaryConversions(FnExpr);
6977
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006978 ExprOwningPtr<CXXOperatorCallExpr>
6979 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6980 Args, 2, ResultTy,
6981 OpLoc));
6982
6983 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6984 FnDecl))
6985 return ExprError();
6986
6987 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006988 } else {
6989 // We matched a built-in operator. Convert the arguments, then
6990 // break out so that we will build the appropriate built-in
6991 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006992 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006993 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006994 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006995 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006996 return ExprError();
6997
6998 break;
6999 }
7000 }
7001
Douglas Gregor66950a32009-09-30 21:46:01 +00007002 case OR_No_Viable_Function: {
7003 // C++ [over.match.oper]p9:
7004 // If the operator is the operator , [...] and there are no
7005 // viable functions, then the operator is assumed to be the
7006 // built-in operator and interpreted according to clause 5.
7007 if (Opc == BinaryOperator::Comma)
7008 break;
7009
Sebastian Redl027de2a2009-05-21 11:50:50 +00007010 // For class as left operand for assignment or compound assigment operator
7011 // do not fall through to handling in built-in, but report that no overloaded
7012 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00007013 OwningExprResult Result = ExprError();
7014 if (Args[0]->getType()->isRecordType() &&
7015 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007016 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7017 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007018 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007019 } else {
7020 // No viable function; try to create a built-in operation, which will
7021 // produce an error. Then, show the non-viable candidates.
7022 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007023 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007024 assert(Result.isInvalid() &&
7025 "C++ binary operator overloading is missing candidates!");
7026 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00007027 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007028 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007029 return move(Result);
7030 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007031
7032 case OR_Ambiguous:
7033 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7034 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007035 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007036 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007037 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007038 return ExprError();
7039
7040 case OR_Deleted:
7041 Diag(OpLoc, diag::err_ovl_deleted_oper)
7042 << Best->Function->isDeleted()
7043 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007044 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007045 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007046 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007047 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007048
Douglas Gregor66950a32009-09-30 21:46:01 +00007049 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007050 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007051}
7052
Sebastian Redladba46e2009-10-29 20:17:01 +00007053Action::OwningExprResult
7054Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7055 SourceLocation RLoc,
7056 ExprArg Base, ExprArg Idx) {
7057 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
7058 static_cast<Expr*>(Idx.get()) };
7059 DeclarationName OpName =
7060 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7061
7062 // If either side is type-dependent, create an appropriate dependent
7063 // expression.
7064 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7065
John McCall58cc69d2010-01-27 01:50:18 +00007066 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007067 // CHECKME: no 'operator' keyword?
7068 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7069 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007070 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007071 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007072 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007073 /*ADL*/ true, /*Overloaded*/ false,
7074 UnresolvedSetIterator(),
7075 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007076 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007077
7078 Base.release();
7079 Idx.release();
7080 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7081 Args, 2,
7082 Context.DependentTy,
7083 RLoc));
7084 }
7085
7086 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007087 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007088
7089 // Subscript can only be overloaded as a member function.
7090
7091 // Add operator candidates that are member functions.
7092 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7093
7094 // Add builtin operator candidates.
7095 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7096
7097 // Perform overload resolution.
7098 OverloadCandidateSet::iterator Best;
7099 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7100 case OR_Success: {
7101 // We found a built-in operator or an overloaded operator.
7102 FunctionDecl *FnDecl = Best->Function;
7103
7104 if (FnDecl) {
7105 // We matched an overloaded operator. Build a call to that
7106 // operator.
7107
John McCalla0296f72010-03-19 07:35:19 +00007108 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007109 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007110
Sebastian Redladba46e2009-10-29 20:17:01 +00007111 // Convert the arguments.
7112 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007113 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007114 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007115 return ExprError();
7116
Anders Carlssona68e51e2010-01-29 18:37:50 +00007117 // Convert the arguments.
7118 OwningExprResult InputInit
7119 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7120 FnDecl->getParamDecl(0)),
7121 SourceLocation(),
7122 Owned(Args[1]));
7123 if (InputInit.isInvalid())
7124 return ExprError();
7125
7126 Args[1] = InputInit.takeAs<Expr>();
7127
Sebastian Redladba46e2009-10-29 20:17:01 +00007128 // Determine the result type
7129 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007130 = FnDecl->getType()->getAs<FunctionType>()
7131 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007132
7133 // Build the actual expression node.
7134 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7135 LLoc);
7136 UsualUnaryConversions(FnExpr);
7137
7138 Base.release();
7139 Idx.release();
7140 ExprOwningPtr<CXXOperatorCallExpr>
7141 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7142 FnExpr, Args, 2,
7143 ResultTy, RLoc));
7144
7145 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7146 FnDecl))
7147 return ExprError();
7148
7149 return MaybeBindToTemporary(TheCall.release());
7150 } else {
7151 // We matched a built-in operator. Convert the arguments, then
7152 // break out so that we will build the appropriate built-in
7153 // operator node.
7154 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007155 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007156 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007157 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007158 return ExprError();
7159
7160 break;
7161 }
7162 }
7163
7164 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007165 if (CandidateSet.empty())
7166 Diag(LLoc, diag::err_ovl_no_oper)
7167 << Args[0]->getType() << /*subscript*/ 0
7168 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7169 else
7170 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7171 << Args[0]->getType()
7172 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007173 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00007174 "[]", LLoc);
7175 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007176 }
7177
7178 case OR_Ambiguous:
7179 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7180 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007181 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00007182 "[]", LLoc);
7183 return ExprError();
7184
7185 case OR_Deleted:
7186 Diag(LLoc, diag::err_ovl_deleted_oper)
7187 << Best->Function->isDeleted() << "[]"
7188 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007189 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00007190 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007191 return ExprError();
7192 }
7193
7194 // We matched a built-in operator; build it.
7195 Base.release();
7196 Idx.release();
7197 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7198 Owned(Args[1]), RLoc);
7199}
7200
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007201/// BuildCallToMemberFunction - Build a call to a member
7202/// function. MemExpr is the expression that refers to the member
7203/// function (and includes the object parameter), Args/NumArgs are the
7204/// arguments to the function call (not including the object
7205/// parameter). The caller needs to validate that the member
7206/// expression refers to a member function or an overloaded member
7207/// function.
John McCall2d74de92009-12-01 22:10:20 +00007208Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007209Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7210 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007211 unsigned NumArgs, SourceLocation *CommaLocs,
7212 SourceLocation RParenLoc) {
7213 // Dig out the member expression. This holds both the object
7214 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007215 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7216
John McCall10eae182009-11-30 22:42:35 +00007217 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007218 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007219 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007220 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007221 if (isa<MemberExpr>(NakedMemExpr)) {
7222 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007223 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007224 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007225 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007226 } else {
7227 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007228 Qualifier = UnresExpr->getQualifier();
7229
John McCall6e9f8f62009-12-03 04:06:58 +00007230 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007231
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007232 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007233 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007234
John McCall2d74de92009-12-01 22:10:20 +00007235 // FIXME: avoid copy.
7236 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7237 if (UnresExpr->hasExplicitTemplateArgs()) {
7238 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7239 TemplateArgs = &TemplateArgsBuffer;
7240 }
7241
John McCall10eae182009-11-30 22:42:35 +00007242 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7243 E = UnresExpr->decls_end(); I != E; ++I) {
7244
John McCall6e9f8f62009-12-03 04:06:58 +00007245 NamedDecl *Func = *I;
7246 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7247 if (isa<UsingShadowDecl>(Func))
7248 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7249
John McCall10eae182009-11-30 22:42:35 +00007250 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007251 // If explicit template arguments were provided, we can't call a
7252 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007253 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007254 continue;
7255
John McCalla0296f72010-03-19 07:35:19 +00007256 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007257 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007258 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007259 } else {
John McCall10eae182009-11-30 22:42:35 +00007260 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007261 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007262 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007263 CandidateSet,
7264 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007265 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007266 }
Mike Stump11289f42009-09-09 15:08:12 +00007267
John McCall10eae182009-11-30 22:42:35 +00007268 DeclarationName DeclName = UnresExpr->getMemberName();
7269
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007270 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00007271 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007272 case OR_Success:
7273 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007274 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007275 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007276 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007277 break;
7278
7279 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007280 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007281 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007282 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007283 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007284 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007285 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007286
7287 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007288 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007289 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007290 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007291 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007292 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007293
7294 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007295 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007296 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007297 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007298 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007299 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007300 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007301 }
7302
John McCall16df1e52010-03-30 21:47:33 +00007303 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007304
John McCall2d74de92009-12-01 22:10:20 +00007305 // If overload resolution picked a static member, build a
7306 // non-member call based on that function.
7307 if (Method->isStatic()) {
7308 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7309 Args, NumArgs, RParenLoc);
7310 }
7311
John McCall10eae182009-11-30 22:42:35 +00007312 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007313 }
7314
7315 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00007316 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00007317 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00007318 NumArgs,
Douglas Gregor603d81b2010-07-13 08:18:22 +00007319 Method->getCallResultType(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007320 RParenLoc));
7321
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007322 // Check for a valid return type.
7323 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7324 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00007325 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007326
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007327 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007328 // We only need to do this if there was actually an overload; otherwise
7329 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007330 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007331 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007332 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7333 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007334 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007335 MemExpr->setBase(ObjectArg);
7336
7337 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007338 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00007339 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007340 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007341 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007342
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007343 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00007344 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007345
John McCall2d74de92009-12-01 22:10:20 +00007346 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007347}
7348
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007349/// BuildCallToObjectOfClassType - Build a call to an object of class
7350/// type (C++ [over.call.object]), which can end up invoking an
7351/// overloaded function call operator (@c operator()) or performing a
7352/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007353Sema::ExprResult
7354Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007355 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007356 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007357 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007358 SourceLocation RParenLoc) {
7359 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007360 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007361
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007362 // C++ [over.call.object]p1:
7363 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007364 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007365 // candidate functions includes at least the function call
7366 // operators of T. The function call operators of T are obtained by
7367 // ordinary lookup of the name operator() in the context of
7368 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007369 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007370 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007371
7372 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007373 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007374 << Object->getSourceRange()))
7375 return true;
7376
John McCall27b18f82009-11-17 02:14:36 +00007377 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7378 LookupQualifiedName(R, Record->getDecl());
7379 R.suppressDiagnostics();
7380
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007381 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007382 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007383 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007384 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007385 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007386 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007387
Douglas Gregorab7897a2008-11-19 22:57:39 +00007388 // C++ [over.call.object]p2:
7389 // In addition, for each conversion function declared in T of the
7390 // form
7391 //
7392 // operator conversion-type-id () cv-qualifier;
7393 //
7394 // where cv-qualifier is the same cv-qualification as, or a
7395 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007396 // denotes the type "pointer to function of (P1,...,Pn) returning
7397 // R", or the type "reference to pointer to function of
7398 // (P1,...,Pn) returning R", or the type "reference to function
7399 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007400 // is also considered as a candidate function. Similarly,
7401 // surrogate call functions are added to the set of candidate
7402 // functions for each conversion function declared in an
7403 // accessible base class provided the function is not hidden
7404 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007405 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007406 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007407 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007408 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007409 NamedDecl *D = *I;
7410 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7411 if (isa<UsingShadowDecl>(D))
7412 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7413
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007414 // Skip over templated conversion functions; they aren't
7415 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007416 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007417 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007418
John McCall6e9f8f62009-12-03 04:06:58 +00007419 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007420
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007421 // Strip the reference type (if any) and then the pointer type (if
7422 // any) to get down to what might be a function type.
7423 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7424 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7425 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007426
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007427 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007428 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007429 Object->getType(), Args, NumArgs,
7430 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007431 }
Mike Stump11289f42009-09-09 15:08:12 +00007432
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007433 // Perform overload resolution.
7434 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007435 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007436 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007437 // Overload resolution succeeded; we'll build the appropriate call
7438 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007439 break;
7440
7441 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007442 if (CandidateSet.empty())
7443 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7444 << Object->getType() << /*call*/ 1
7445 << Object->getSourceRange();
7446 else
7447 Diag(Object->getSourceRange().getBegin(),
7448 diag::err_ovl_no_viable_object_call)
7449 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007450 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007451 break;
7452
7453 case OR_Ambiguous:
7454 Diag(Object->getSourceRange().getBegin(),
7455 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007456 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007457 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007458 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007459
7460 case OR_Deleted:
7461 Diag(Object->getSourceRange().getBegin(),
7462 diag::err_ovl_deleted_object_call)
7463 << Best->Function->isDeleted()
7464 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007465 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007466 break;
Mike Stump11289f42009-09-09 15:08:12 +00007467 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007468
Douglas Gregorb412e172010-07-25 18:17:45 +00007469 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007470 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007471
Douglas Gregorab7897a2008-11-19 22:57:39 +00007472 if (Best->Function == 0) {
7473 // Since there is no function declaration, this is one of the
7474 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007475 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007476 = cast<CXXConversionDecl>(
7477 Best->Conversions[0].UserDefined.ConversionFunction);
7478
John McCalla0296f72010-03-19 07:35:19 +00007479 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007480 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007481
Douglas Gregorab7897a2008-11-19 22:57:39 +00007482 // We selected one of the surrogate functions that converts the
7483 // object parameter to a function pointer. Perform the conversion
7484 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007485
7486 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007487 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007488 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7489 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007490
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007491 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007492 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007493 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007494 }
7495
John McCalla0296f72010-03-19 07:35:19 +00007496 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007497 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007498
Douglas Gregorab7897a2008-11-19 22:57:39 +00007499 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7500 // that calls this method, using Object for the implicit object
7501 // parameter and passing along the remaining arguments.
7502 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007503 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007504
7505 unsigned NumArgsInProto = Proto->getNumArgs();
7506 unsigned NumArgsToCheck = NumArgs;
7507
7508 // Build the full argument list for the method call (the
7509 // implicit object parameter is placed at the beginning of the
7510 // list).
7511 Expr **MethodArgs;
7512 if (NumArgs < NumArgsInProto) {
7513 NumArgsToCheck = NumArgsInProto;
7514 MethodArgs = new Expr*[NumArgsInProto + 1];
7515 } else {
7516 MethodArgs = new Expr*[NumArgs + 1];
7517 }
7518 MethodArgs[0] = Object;
7519 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7520 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007521
7522 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007523 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007524 UsualUnaryConversions(NewFn);
7525
7526 // Once we've built TheCall, all of the expressions are properly
7527 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007528 QualType ResultTy = Method->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00007529 ExprOwningPtr<CXXOperatorCallExpr>
7530 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007531 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007532 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007533 delete [] MethodArgs;
7534
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007535 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7536 Method))
7537 return true;
7538
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007539 // We may have default arguments. If so, we need to allocate more
7540 // slots in the call for them.
7541 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007542 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007543 else if (NumArgs > NumArgsInProto)
7544 NumArgsToCheck = NumArgsInProto;
7545
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007546 bool IsError = false;
7547
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007548 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007549 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007550 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007551 TheCall->setArg(0, Object);
7552
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007553
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007554 // Check the argument types.
7555 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007556 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007557 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007558 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007559
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007560 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007561
7562 OwningExprResult InputInit
7563 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7564 Method->getParamDecl(i)),
7565 SourceLocation(), Owned(Arg));
7566
7567 IsError |= InputInit.isInvalid();
7568 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007569 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007570 OwningExprResult DefArg
7571 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7572 if (DefArg.isInvalid()) {
7573 IsError = true;
7574 break;
7575 }
7576
7577 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007578 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007579
7580 TheCall->setArg(i + 1, Arg);
7581 }
7582
7583 // If this is a variadic call, handle args passed through "...".
7584 if (Proto->isVariadic()) {
7585 // Promote the arguments (C99 6.5.2.2p7).
7586 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7587 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007588 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007589 TheCall->setArg(i + 1, Arg);
7590 }
7591 }
7592
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007593 if (IsError) return true;
7594
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007595 if (CheckFunctionCall(Method, TheCall.get()))
7596 return true;
7597
Douglas Gregore5e775b2010-04-13 15:50:39 +00007598 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007599}
7600
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007601/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007602/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007603/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007604Sema::OwningExprResult
7605Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7606 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007607 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007608
John McCallbc077cf2010-02-08 23:07:23 +00007609 SourceLocation Loc = Base->getExprLoc();
7610
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007611 // C++ [over.ref]p1:
7612 //
7613 // [...] An expression x->m is interpreted as (x.operator->())->m
7614 // for a class object x of type T if T::operator->() exists and if
7615 // the operator is selected as the best match function by the
7616 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007617 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007618 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007619 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007620
John McCallbc077cf2010-02-08 23:07:23 +00007621 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007622 PDiag(diag::err_typecheck_incomplete_tag)
7623 << Base->getSourceRange()))
7624 return ExprError();
7625
John McCall27b18f82009-11-17 02:14:36 +00007626 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7627 LookupQualifiedName(R, BaseRecord->getDecl());
7628 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007629
7630 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007631 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007632 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007633 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007634 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007635
7636 // Perform overload resolution.
7637 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007638 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007639 case OR_Success:
7640 // Overload resolution succeeded; we'll build the call below.
7641 break;
7642
7643 case OR_No_Viable_Function:
7644 if (CandidateSet.empty())
7645 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007646 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007647 else
7648 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007649 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007650 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007651 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007652
7653 case OR_Ambiguous:
7654 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007655 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007656 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007657 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007658
7659 case OR_Deleted:
7660 Diag(OpLoc, diag::err_ovl_deleted_oper)
7661 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007662 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007663 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007664 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007665 }
7666
John McCalla0296f72010-03-19 07:35:19 +00007667 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007668 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007669
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007670 // Convert the object parameter.
7671 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007672 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7673 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007674 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007675
7676 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007677 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007678
7679 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007680 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7681 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007682 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007683
Douglas Gregor603d81b2010-07-13 08:18:22 +00007684 QualType ResultTy = Method->getCallResultType();
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007685 ExprOwningPtr<CXXOperatorCallExpr>
7686 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7687 &Base, 1, ResultTy, OpLoc));
7688
7689 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7690 Method))
7691 return ExprError();
7692 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007693}
7694
Douglas Gregorcd695e52008-11-10 20:40:00 +00007695/// FixOverloadedFunctionReference - E is an expression that refers to
7696/// a C++ overloaded function (possibly with some parentheses and
7697/// perhaps a '&' around it). We have resolved the overloaded function
7698/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007699/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007700Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007701 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007702 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007703 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7704 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007705 if (SubExpr == PE->getSubExpr())
7706 return PE->Retain();
7707
7708 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7709 }
7710
7711 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007712 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7713 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007714 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007715 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007716 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007717 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007718 if (SubExpr == ICE->getSubExpr())
7719 return ICE->Retain();
7720
John McCallcf142162010-08-07 06:22:56 +00007721 return ImplicitCastExpr::Create(Context, ICE->getType(),
7722 ICE->getCastKind(),
7723 SubExpr, 0,
7724 ICE->getCategory());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007725 }
7726
7727 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007728 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007729 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7731 if (Method->isStatic()) {
7732 // Do nothing: static member functions aren't any different
7733 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007734 } else {
John McCalle66edc12009-11-24 19:00:30 +00007735 // Fix the sub expression, which really has to be an
7736 // UnresolvedLookupExpr holding an overloaded member function
7737 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007738 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7739 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007740 if (SubExpr == UnOp->getSubExpr())
7741 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007742
John McCalld14a8642009-11-21 08:51:07 +00007743 assert(isa<DeclRefExpr>(SubExpr)
7744 && "fixed to something other than a decl ref");
7745 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7746 && "fixed to a member ref with no nested name qualifier");
7747
7748 // We have taken the address of a pointer to member
7749 // function. Perform the computation here so that we get the
7750 // appropriate pointer to member type.
7751 QualType ClassType
7752 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7753 QualType MemPtrType
7754 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7755
7756 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7757 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007758 }
7759 }
John McCall16df1e52010-03-30 21:47:33 +00007760 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7761 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007762 if (SubExpr == UnOp->getSubExpr())
7763 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007764
Douglas Gregor51c538b2009-11-20 19:42:02 +00007765 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7766 Context.getPointerType(SubExpr->getType()),
7767 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007768 }
John McCalld14a8642009-11-21 08:51:07 +00007769
7770 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007771 // FIXME: avoid copy.
7772 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007773 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007774 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7775 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007776 }
7777
John McCalld14a8642009-11-21 08:51:07 +00007778 return DeclRefExpr::Create(Context,
7779 ULE->getQualifier(),
7780 ULE->getQualifierRange(),
7781 Fn,
7782 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007783 Fn->getType(),
7784 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007785 }
7786
John McCall10eae182009-11-30 22:42:35 +00007787 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007788 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007789 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7790 if (MemExpr->hasExplicitTemplateArgs()) {
7791 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7792 TemplateArgs = &TemplateArgsBuffer;
7793 }
John McCall6b51f282009-11-23 01:53:49 +00007794
John McCall2d74de92009-12-01 22:10:20 +00007795 Expr *Base;
7796
7797 // If we're filling in
7798 if (MemExpr->isImplicitAccess()) {
7799 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7800 return DeclRefExpr::Create(Context,
7801 MemExpr->getQualifier(),
7802 MemExpr->getQualifierRange(),
7803 Fn,
7804 MemExpr->getMemberLoc(),
7805 Fn->getType(),
7806 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007807 } else {
7808 SourceLocation Loc = MemExpr->getMemberLoc();
7809 if (MemExpr->getQualifier())
7810 Loc = MemExpr->getQualifierRange().getBegin();
7811 Base = new (Context) CXXThisExpr(Loc,
7812 MemExpr->getBaseType(),
7813 /*isImplicit=*/true);
7814 }
John McCall2d74de92009-12-01 22:10:20 +00007815 } else
7816 Base = MemExpr->getBase()->Retain();
7817
7818 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007819 MemExpr->isArrow(),
7820 MemExpr->getQualifier(),
7821 MemExpr->getQualifierRange(),
7822 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007823 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007824 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00007825 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007826 Fn->getType());
7827 }
7828
Douglas Gregor51c538b2009-11-20 19:42:02 +00007829 assert(false && "Invalid reference to overloaded function");
7830 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007831}
7832
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007833Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007834 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007835 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007836 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007837}
7838
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007839} // end namespace clang