blob: 27e6c2c2a3467f9c0b15dec6e8585cdc7bc64dc0 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor4c2458a2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000055 ICC_Conversion,
56 ICC_Conversion,
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +000072 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000073 ICR_Promotion,
74 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000075 ICR_Promotion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000078 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000083 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000084 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000085 ICR_Conversion,
86 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +000087 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-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 Lopes2550d702009-12-23 17:49:57 +000095 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000096 "No conversion",
97 "Lvalue-to-rvalue",
98 "Array-to-pointer",
99 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000100 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Qualification",
102 "Integral promotion",
103 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 "Integral conversion",
106 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 "Floating-integral conversion",
109 "Pointer conversion",
110 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 "Derived-to-base conversion",
114 "Vector conversion",
115 "Vector splat",
116 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 };
118 return Name[Kind];
119}
120
Douglas Gregor60d62c22008-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 Gregora9bff302010-02-28 18:30:25 +0000127 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000128 ReferenceBinding = false;
129 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000130 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000131 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000132}
133
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000150/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000152bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-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 Gregorad323a82010-01-27 03:51:04 +0000157 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000158 (getFromType()->isPointerType() ||
159 getFromType()->isObjCObjectPointerType() ||
160 getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-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 Gregorbc0805a2008-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 Stump1eb44332009-09-09 15:08:12 +0000171bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000172StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000173isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000174 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000175 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-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 Gregor01919692009-12-13 21:37:05 +0000183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000185 return ToPtrType->getPointeeType()->isVoidType();
186
187 return false;
188}
189
Douglas Gregor8e9bebd2008-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 Dunbarf3f91f32010-01-22 02:04:41 +0000193 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194 bool PrintedSomething = false;
195 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197 PrintedSomething = true;
198 }
199
200 if (Second != ICK_Identity) {
201 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000202 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000203 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000204 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000205
206 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000207 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000208 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000209 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000210 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000211 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000212 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (Third != ICK_Identity) {
217 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000218 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000220 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221 PrintedSomething = true;
222 }
223
224 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000225 OS << "No conversions required";
Douglas Gregor8e9bebd2008-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 Dunbarf3f91f32010-01-22 02:04:41 +0000232 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000233 if (Before.First || Before.Second || Before.Third) {
234 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000237 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 OS << " -> ";
Douglas Gregor8e9bebd2008-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 Dunbarf3f91f32010-01-22 02:04:41 +0000247 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000248 switch (ConversionKind) {
249 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 Standard.DebugPrint();
252 break;
253 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000254 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 UserDefined.DebugPrint();
256 break;
257 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000258 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000259 break;
John McCall1d318332010-01-12 00:44:57 +0000260 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000261 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000262 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000263 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 break;
266 }
267
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269}
270
John McCall1d318332010-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 Gregora9333192010-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 Gregorff5adac2010-05-08 20:18:54 +0000299static MakeDeductionFailureInfo(ASTContext &Context,
300 Sema::TemplateDeductionResult TDK,
Douglas Gregorec20f462010-05-08 20:07:26 +0000301 Sema::TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000308 case Sema::TDK_TooManyArguments:
309 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000310 break;
311
312 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000313 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000314 Result.Data = Info.Param.getOpaqueValue();
315 break;
316
Douglas Gregora9333192010-05-08 17:41:32 +0000317 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000318 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-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 Gregora9333192010-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 Gregorec20f462010-05-08 20:07:26 +0000329 Result.Data = Info.take();
330 break;
331
Douglas Gregora9333192010-05-08 17:41:32 +0000332 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000333 case Sema::TDK_FailedOverloadResolution:
334 break;
335 }
336
337 return Result;
338}
John McCall1d318332010-01-12 00:44:57 +0000339
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000345 case Sema::TDK_TooManyArguments:
346 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000347 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000348 break;
349
Douglas Gregora9333192010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000352 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000353 Data = 0;
354 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000355
356 case Sema::TDK_SubstitutionFailure:
357 // FIXME: Destroy the template arugment list?
358 Data = 0;
359 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000360
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000361 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000362 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000373 case Sema::TDK_TooManyArguments:
374 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000375 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000376 return TemplateParameter();
377
378 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000380 return TemplateParameter::getFromOpaqueValue(Data);
381
382 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000384 return static_cast<DFIParamWithArguments*>(Data)->Param;
385
386 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000387 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000388 case Sema::TDK_FailedOverloadResolution:
389 break;
390 }
391
392 return TemplateParameter();
393}
Douglas Gregorec20f462010-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 McCall57e97782010-08-05 09:05:08 +0000405 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-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 Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000425 case Sema::TDK_TooManyArguments:
426 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000428 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000429 return 0;
430
Douglas Gregora9333192010-05-08 17:41:32 +0000431 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000432 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
434
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000450 case Sema::TDK_TooManyArguments:
451 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000452 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000453 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000454 return 0;
455
Douglas Gregora9333192010-05-08 17:41:32 +0000456 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-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 McCall871b2e72009-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 Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491//
John McCall51fa86f2009-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 Gregor8e9bebd2008-10-21 16:13:35 +0000496//
John McCall51fa86f2009-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 Gregor8e9bebd2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCallad00b772010-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 McCall871b2e72009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCallad00b772010-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 McCall51fa86f2009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-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 McCall871b2e72009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543 }
John McCall51fa86f2009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-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 McCall871b2e72009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000553 }
John McCall9f54ad42009-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 McCall68263142009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000568 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000569 }
John McCall68263142009-11-18 22:49:29 +0000570
John McCall871b2e72009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000572}
573
John McCallad00b772010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000576 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
577 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
578
579 // C++ [temp.fct]p2:
580 // A function template can be overloaded with other function templates
581 // and with normal (non-template) functions.
582 if ((OldTemplate == 0) != (NewTemplate == 0))
583 return true;
584
585 // Is the function New an overload of the function Old?
586 QualType OldQType = Context.getCanonicalType(Old->getType());
587 QualType NewQType = Context.getCanonicalType(New->getType());
588
589 // Compare the signatures (C++ 1.3.10) of the two functions to
590 // determine whether they are overloads. If we find any mismatch
591 // in the signature, they are overloads.
592
593 // If either of these functions is a K&R-style function (no
594 // prototype), then we consider them to have matching signatures.
595 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
596 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
597 return false;
598
599 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
600 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
601
602 // The signature of a function includes the types of its
603 // parameters (C++ 1.3.10), which includes the presence or absence
604 // of the ellipsis; see C++ DR 357).
605 if (OldQType != NewQType &&
606 (OldType->getNumArgs() != NewType->getNumArgs() ||
607 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000608 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000609 return true;
610
611 // C++ [temp.over.link]p4:
612 // The signature of a function template consists of its function
613 // signature, its return type and its template parameter list. The names
614 // of the template parameters are significant only for establishing the
615 // relationship between the template parameters and the rest of the
616 // signature.
617 //
618 // We check the return type and template parameter lists for function
619 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000620 //
621 // However, we don't consider either of these when deciding whether
622 // a member introduced by a shadow declaration is hidden.
623 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000624 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
625 OldTemplate->getTemplateParameters(),
626 false, TPL_TemplateMatch) ||
627 OldType->getResultType() != NewType->getResultType()))
628 return true;
629
630 // If the function is a class member, its signature includes the
631 // cv-qualifiers (if any) on the function itself.
632 //
633 // As part of this, also check whether one of the member functions
634 // is static, in which case they are not overloads (C++
635 // 13.1p2). While not part of the definition of the signature,
636 // this check is important to determine whether these functions
637 // can be overloaded.
638 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
639 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
640 if (OldMethod && NewMethod &&
641 !OldMethod->isStatic() && !NewMethod->isStatic() &&
642 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
643 return true;
644
645 // The signatures match; this is not an overload.
646 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000647}
648
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000649/// TryImplicitConversion - Attempt to perform an implicit conversion
650/// from the given expression (Expr) to the given type (ToType). This
651/// function returns an implicit conversion sequence that can be used
652/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000653///
654/// void f(float f);
655/// void g(int i) { f(i); }
656///
657/// this routine would produce an implicit conversion sequence to
658/// describe the initialization of f from i, which will be a standard
659/// conversion sequence containing an lvalue-to-rvalue conversion (C++
660/// 4.1) followed by a floating-integral conversion (C++ 4.9).
661//
662/// Note that this routine only determines how the conversion can be
663/// performed; it does not actually perform the conversion. As such,
664/// it will not produce any diagnostics if no conversion is available,
665/// but will instead return an implicit conversion sequence of kind
666/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000667///
668/// If @p SuppressUserConversions, then user-defined conversions are
669/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000670/// If @p AllowExplicit, then explicit user-defined conversions are
671/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000672ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000673Sema::TryImplicitConversion(Expr* From, QualType ToType,
674 bool SuppressUserConversions,
Douglas Gregor74e386e2010-04-16 18:00:29 +0000675 bool AllowExplicit,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000676 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000677 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000678 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000679 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000680 return ICS;
681 }
682
683 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000684 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000685 return ICS;
686 }
687
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000688 if (SuppressUserConversions) {
689 // C++ [over.ics.user]p4:
690 // A conversion of an expression of class type to the same class
691 // type is given Exact Match rank, and a conversion of an
692 // expression of class type to a base class of that type is
693 // given Conversion rank, in spite of the fact that a copy/move
694 // constructor (i.e., a user-defined conversion function) is
695 // called for those cases.
696 QualType FromType = From->getType();
697 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
698 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
699 IsDerivedFrom(FromType, ToType))) {
700 // We're not in the case above, so there is no conversion that
701 // we can perform.
702 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
703 return ICS;
704 }
705
706 ICS.setStandard();
707 ICS.Standard.setAsIdentityConversion();
708 ICS.Standard.setFromType(FromType);
709 ICS.Standard.setAllToTypes(ToType);
710
711 // We don't actually check at this point whether there is a valid
712 // copy/move constructor, since overloading just assumes that it
713 // exists. When we actually perform initialization, we'll find the
714 // appropriate constructor to copy the returned object, if needed.
715 ICS.Standard.CopyConstructor = 0;
716
717 // Determine whether this is considered a derived-to-base conversion.
718 if (!Context.hasSameUnqualifiedType(FromType, ToType))
719 ICS.Standard.Second = ICK_Derived_To_Base;
720
721 return ICS;
722 }
723
724 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000725 OverloadCandidateSet Conversions(From->getExprLoc());
726 OverloadingResult UserDefResult
727 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000728 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000729
730 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000731 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000732 // C++ [over.ics.user]p4:
733 // A conversion of an expression of class type to the same class
734 // type is given Exact Match rank, and a conversion of an
735 // expression of class type to a base class of that type is
736 // given Conversion rank, in spite of the fact that a copy
737 // constructor (i.e., a user-defined conversion function) is
738 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000739 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000740 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000741 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000742 = Context.getCanonicalType(From->getType().getUnqualifiedType());
743 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000744 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000745 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000746 // Turn this into a "standard" conversion sequence, so that it
747 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000748 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000749 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000750 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000751 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000752 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000753 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000754 ICS.Standard.Second = ICK_Derived_To_Base;
755 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000756 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000757
758 // C++ [over.best.ics]p4:
759 // However, when considering the argument of a user-defined
760 // conversion function that is a candidate by 13.3.1.3 when
761 // invoked for the copying of the temporary in the second step
762 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
763 // 13.3.1.6 in all cases, only standard conversion sequences and
764 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000765 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000766 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000767 }
John McCallcefd3ad2010-01-13 22:30:33 +0000768 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000769 ICS.setAmbiguous();
770 ICS.Ambiguous.setFromType(From->getType());
771 ICS.Ambiguous.setToType(ToType);
772 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
773 Cand != Conversions.end(); ++Cand)
774 if (Cand->Viable)
775 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000776 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000777 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000778 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000779
780 return ICS;
781}
782
Douglas Gregor575c63a2010-04-16 22:27:05 +0000783/// PerformImplicitConversion - Perform an implicit conversion of the
784/// expression From to the type ToType. Returns true if there was an
785/// error, false otherwise. The expression From is replaced with the
786/// converted expression. Flavor is the kind of conversion we're
787/// performing, used in the error message. If @p AllowExplicit,
788/// explicit user-defined conversions are permitted.
789bool
790Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
791 AssignmentAction Action, bool AllowExplicit) {
792 ImplicitConversionSequence ICS;
793 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
794}
795
796bool
797Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
798 AssignmentAction Action, bool AllowExplicit,
799 ImplicitConversionSequence& ICS) {
800 ICS = TryImplicitConversion(From, ToType,
801 /*SuppressUserConversions=*/false,
802 AllowExplicit,
803 /*InOverloadResolution=*/false);
804 return PerformImplicitConversion(From, ToType, ICS, Action);
805}
806
Douglas Gregor43c79c22009-12-09 00:47:37 +0000807/// \brief Determine whether the conversion from FromType to ToType is a valid
808/// conversion that strips "noreturn" off the nested function type.
809static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
810 QualType ToType, QualType &ResultTy) {
811 if (Context.hasSameUnqualifiedType(FromType, ToType))
812 return false;
813
814 // Strip the noreturn off the type we're converting from; noreturn can
815 // safely be removed.
816 FromType = Context.getNoReturnType(FromType, false);
817 if (!Context.hasSameUnqualifiedType(FromType, ToType))
818 return false;
819
820 ResultTy = FromType;
821 return true;
822}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000823
824/// \brief Determine whether the conversion from FromType to ToType is a valid
825/// vector conversion.
826///
827/// \param ICK Will be set to the vector conversion kind, if this is a vector
828/// conversion.
829static bool IsVectorConversion(ASTContext &Context, QualType FromType,
830 QualType ToType, ImplicitConversionKind &ICK) {
831 // We need at least one of these types to be a vector type to have a vector
832 // conversion.
833 if (!ToType->isVectorType() && !FromType->isVectorType())
834 return false;
835
836 // Identical types require no conversions.
837 if (Context.hasSameUnqualifiedType(FromType, ToType))
838 return false;
839
840 // There are no conversions between extended vector types, only identity.
841 if (ToType->isExtVectorType()) {
842 // There are no conversions between extended vector types other than the
843 // identity conversion.
844 if (FromType->isExtVectorType())
845 return false;
846
847 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000848 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000849 ICK = ICK_Vector_Splat;
850 return true;
851 }
852 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000853
854 // We can perform the conversion between vector types in the following cases:
855 // 1)vector types are equivalent AltiVec and GCC vector types
856 // 2)lax vector conversions are permitted and the vector types are of the
857 // same size
858 if (ToType->isVectorType() && FromType->isVectorType()) {
859 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
860 Context.getLangOptions().LaxVectorConversions &&
861 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType))) {
862 ICK = ICK_Vector_Conversion;
863 return true;
864 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000865 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000866
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000867 return false;
868}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000869
Douglas Gregor60d62c22008-10-31 16:23:19 +0000870/// IsStandardConversion - Determines whether there is a standard
871/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
872/// expression From to the type ToType. Standard conversion sequences
873/// only consider non-class types; for conversions that involve class
874/// types, use TryImplicitConversion. If a conversion exists, SCS will
875/// contain the standard conversion sequence required to perform this
876/// conversion and this routine will return true. Otherwise, this
877/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000878bool
879Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000880 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000881 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000882 QualType FromType = From->getType();
883
Douglas Gregor60d62c22008-10-31 16:23:19 +0000884 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000885 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000886 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000887 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000888 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000889 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000890
Douglas Gregorf9201e02009-02-11 23:02:49 +0000891 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000892 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000893 if (FromType->isRecordType() || ToType->isRecordType()) {
894 if (getLangOptions().CPlusPlus)
895 return false;
896
Mike Stump1eb44332009-09-09 15:08:12 +0000897 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000898 }
899
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000900 // The first conversion can be an lvalue-to-rvalue conversion,
901 // array-to-pointer conversion, or function-to-pointer conversion
902 // (C++ 4p1).
903
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000904 if (FromType == Context.OverloadTy) {
905 DeclAccessPair AccessPair;
906 if (FunctionDecl *Fn
907 = ResolveAddressOfOverloadedFunction(From, ToType, false,
908 AccessPair)) {
909 // We were able to resolve the address of the overloaded function,
910 // so we can convert to the type of that function.
911 FromType = Fn->getType();
912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
913 if (!Method->isStatic()) {
914 Type *ClassType
915 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
916 FromType = Context.getMemberPointerType(FromType, ClassType);
917 }
918 }
919
920 // If the "from" expression takes the address of the overloaded
921 // function, update the type of the resulting expression accordingly.
922 if (FromType->getAs<FunctionType>())
923 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
924 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
925 FromType = Context.getPointerType(FromType);
926
927 // Check that we've computed the proper type after overload resolution.
928 assert(Context.hasSameType(FromType,
929 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
930 } else {
931 return false;
932 }
933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000935 // An lvalue (3.10) of a non-function, non-array type T can be
936 // converted to an rvalue.
937 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000938 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000939 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000940 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000941 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000942
943 // If T is a non-class type, the type of the rvalue is the
944 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000945 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
946 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000947 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000948 } else if (FromType->isArrayType()) {
949 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000950 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000951
952 // An lvalue or rvalue of type "array of N T" or "array of unknown
953 // bound of T" can be converted to an rvalue of type "pointer to
954 // T" (C++ 4.2p1).
955 FromType = Context.getArrayDecayedType(FromType);
956
957 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
958 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000959 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000960
961 // For the purpose of ranking in overload resolution
962 // (13.3.3.1.1), this conversion is considered an
963 // array-to-pointer conversion followed by a qualification
964 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000965 SCS.Second = ICK_Identity;
966 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000967 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000968 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000969 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000970 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
971 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000972 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000973
974 // An lvalue of function type T can be converted to an rvalue of
975 // type "pointer to T." The result is a pointer to the
976 // function. (C++ 4.3p1).
977 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000978 } else {
979 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000980 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000981 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000982 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000983
984 // The second conversion can be an integral promotion, floating
985 // point promotion, integral conversion, floating point conversion,
986 // floating-integral conversion, pointer conversion,
987 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000988 // For overloading in C, this can also be a "compatible-type"
989 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000990 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000991 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000992 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000993 // The unqualified versions of the types are the same: there's no
994 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000995 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000996 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000997 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000998 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000999 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001000 } else if (IsFloatingPointPromotion(FromType, ToType)) {
1001 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001002 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001003 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001004 } else if (IsComplexPromotion(FromType, ToType)) {
1005 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001006 SCS.Second = ICK_Complex_Promotion;
1007 FromType = ToType.getUnqualifiedType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001008 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001009 ToType->isIntegralType(Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001010 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001011 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001012 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001013 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1014 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001015 SCS.Second = ICK_Complex_Conversion;
1016 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001017 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1018 (ToType->isComplexType() && FromType->isArithmeticType())) {
1019 // Complex-real conversions (C99 6.3.1.7)
1020 SCS.Second = ICK_Complex_Real;
1021 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001022 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001023 // Floating point conversions (C++ 4.8).
1024 SCS.Second = ICK_Floating_Conversion;
1025 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001026 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001027 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001028 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001029 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001030 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001031 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001032 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +00001033 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1034 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001035 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001036 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001037 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +00001038 } else if (IsMemberPointerConversion(From, FromType, ToType,
1039 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001040 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001041 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001042 } else if (ToType->isBooleanType() &&
1043 (FromType->isArithmeticType() ||
1044 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001045 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001046 FromType->isBlockPointerType() ||
1047 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001048 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001049 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001050 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001051 FromType = Context.BoolTy;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001052 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1053 SCS.Second = SecondICK;
1054 FromType = ToType.getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001055 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001056 Context.typesAreCompatible(ToType, FromType)) {
1057 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001058 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001059 FromType = ToType.getUnqualifiedType();
Douglas Gregor43c79c22009-12-09 00:47:37 +00001060 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1061 // Treat a conversion that strips "noreturn" as an identity conversion.
1062 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001063 } else {
1064 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001065 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001066 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001067 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001068
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001069 QualType CanonFrom;
1070 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001071 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +00001072 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001073 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001074 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001075 CanonFrom = Context.getCanonicalType(FromType);
1076 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001077 } else {
1078 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001079 SCS.Third = ICK_Identity;
1080
Mike Stump1eb44332009-09-09 15:08:12 +00001081 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001082 // [...] Any difference in top-level cv-qualification is
1083 // subsumed by the initialization itself and does not constitute
1084 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001085 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +00001086 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001087 if (CanonFrom.getLocalUnqualifiedType()
1088 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001089 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1090 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001091 FromType = ToType;
1092 CanonFrom = CanonTo;
1093 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001094 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001095 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001096
1097 // If we have not converted the argument type to the parameter type,
1098 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001099 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001100 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001101
Douglas Gregor60d62c22008-10-31 16:23:19 +00001102 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001103}
1104
1105/// IsIntegralPromotion - Determines whether the conversion from the
1106/// expression From (whose potentially-adjusted type is FromType) to
1107/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1108/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001109bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001110 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001111 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001112 if (!To) {
1113 return false;
1114 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001115
1116 // An rvalue of type char, signed char, unsigned char, short int, or
1117 // unsigned short int can be converted to an rvalue of type int if
1118 // int can represent all the values of the source type; otherwise,
1119 // the source rvalue can be converted to an rvalue of type unsigned
1120 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001121 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1122 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001123 if (// We can promote any signed, promotable integer type to an int
1124 (FromType->isSignedIntegerType() ||
1125 // We can promote any unsigned integer type whose size is
1126 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001127 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001128 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001129 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001130 }
1131
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001132 return To->getKind() == BuiltinType::UInt;
1133 }
1134
1135 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1136 // can be converted to an rvalue of the first of the following types
1137 // that can represent all the values of its underlying type: int,
1138 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001139
1140 // We pre-calculate the promotion type for enum types.
1141 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1142 if (ToType->isIntegerType())
1143 return Context.hasSameUnqualifiedType(ToType,
1144 FromEnumType->getDecl()->getPromotionType());
1145
1146 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001147 // Determine whether the type we're converting from is signed or
1148 // unsigned.
1149 bool FromIsSigned;
1150 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001151
1152 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1153 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001154
1155 // The types we'll try to promote to, in the appropriate
1156 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001157 QualType PromoteTypes[6] = {
1158 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001159 Context.LongTy, Context.UnsignedLongTy ,
1160 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001161 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001162 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001163 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1164 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001165 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001166 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1167 // We found the type that we can promote to. If this is the
1168 // type we wanted, we have a promotion. Otherwise, no
1169 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001170 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171 }
1172 }
1173 }
1174
1175 // An rvalue for an integral bit-field (9.6) can be converted to an
1176 // rvalue of type int if int can represent all the values of the
1177 // bit-field; otherwise, it can be converted to unsigned int if
1178 // unsigned int can represent all the values of the bit-field. If
1179 // the bit-field is larger yet, no integral promotion applies to
1180 // it. If the bit-field has an enumerated type, it is treated as any
1181 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001182 // FIXME: We should delay checking of bit-fields until we actually perform the
1183 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001184 using llvm::APSInt;
1185 if (From)
1186 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001187 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001188 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001189 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1190 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1191 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Douglas Gregor86f19402008-12-20 23:49:58 +00001193 // Are we promoting to an int from a bitfield that fits in an int?
1194 if (BitWidth < ToSize ||
1195 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1196 return To->getKind() == BuiltinType::Int;
1197 }
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregor86f19402008-12-20 23:49:58 +00001199 // Are we promoting to an unsigned int from an unsigned bitfield
1200 // that fits into an unsigned int?
1201 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1202 return To->getKind() == BuiltinType::UInt;
1203 }
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Douglas Gregor86f19402008-12-20 23:49:58 +00001205 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001206 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001207 }
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001209 // An rvalue of type bool can be converted to an rvalue of type int,
1210 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001211 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001212 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001213 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001214
1215 return false;
1216}
1217
1218/// IsFloatingPointPromotion - Determines whether the conversion from
1219/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1220/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001221bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001222 /// An rvalue of type float can be converted to an rvalue of type
1223 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001224 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1225 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001226 if (FromBuiltin->getKind() == BuiltinType::Float &&
1227 ToBuiltin->getKind() == BuiltinType::Double)
1228 return true;
1229
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001230 // C99 6.3.1.5p1:
1231 // When a float is promoted to double or long double, or a
1232 // double is promoted to long double [...].
1233 if (!getLangOptions().CPlusPlus &&
1234 (FromBuiltin->getKind() == BuiltinType::Float ||
1235 FromBuiltin->getKind() == BuiltinType::Double) &&
1236 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1237 return true;
1238 }
1239
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001240 return false;
1241}
1242
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001243/// \brief Determine if a conversion is a complex promotion.
1244///
1245/// A complex promotion is defined as a complex -> complex conversion
1246/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001247/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001248bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001249 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001250 if (!FromComplex)
1251 return false;
1252
John McCall183700f2009-09-21 23:43:11 +00001253 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001254 if (!ToComplex)
1255 return false;
1256
1257 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001258 ToComplex->getElementType()) ||
1259 IsIntegralPromotion(0, FromComplex->getElementType(),
1260 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001261}
1262
Douglas Gregorcb7de522008-11-26 23:31:11 +00001263/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1264/// the pointer type FromPtr to a pointer to type ToPointee, with the
1265/// same type qualifiers as FromPtr has on its pointee type. ToType,
1266/// if non-empty, will be a pointer to ToType that may or may not have
1267/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001268static QualType
1269BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001270 QualType ToPointee, QualType ToType,
1271 ASTContext &Context) {
1272 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1273 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001274 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001275
1276 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001277 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001278 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001279 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001280 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001281
1282 // Build a pointer to ToPointee. It has the right qualifiers
1283 // already.
1284 return Context.getPointerType(ToPointee);
1285 }
1286
1287 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001288 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001289 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1290 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001291}
1292
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001293/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1294/// the FromType, which is an objective-c pointer, to ToType, which may or may
1295/// not have the right set of qualifiers.
1296static QualType
1297BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1298 QualType ToType,
1299 ASTContext &Context) {
1300 QualType CanonFromType = Context.getCanonicalType(FromType);
1301 QualType CanonToType = Context.getCanonicalType(ToType);
1302 Qualifiers Quals = CanonFromType.getQualifiers();
1303
1304 // Exact qualifier match -> return the pointer type we're converting to.
1305 if (CanonToType.getLocalQualifiers() == Quals)
1306 return ToType;
1307
1308 // Just build a canonical type that has the right qualifiers.
1309 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1310}
1311
Mike Stump1eb44332009-09-09 15:08:12 +00001312static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001313 bool InOverloadResolution,
1314 ASTContext &Context) {
1315 // Handle value-dependent integral null pointer constants correctly.
1316 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1317 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001318 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001319 return !InOverloadResolution;
1320
Douglas Gregorce940492009-09-25 04:25:58 +00001321 return Expr->isNullPointerConstant(Context,
1322 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1323 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001324}
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001326/// IsPointerConversion - Determines whether the conversion of the
1327/// expression From, which has the (possibly adjusted) type FromType,
1328/// can be converted to the type ToType via a pointer conversion (C++
1329/// 4.10). If so, returns true and places the converted type (that
1330/// might differ from ToType in its cv-qualifiers at some level) into
1331/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001332///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001333/// This routine also supports conversions to and from block pointers
1334/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1335/// pointers to interfaces. FIXME: Once we've determined the
1336/// appropriate overloading rules for Objective-C, we may want to
1337/// split the Objective-C checks into a different routine; however,
1338/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001339/// conversions, so for now they live here. IncompatibleObjC will be
1340/// set if the conversion is an allowed Objective-C conversion that
1341/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001342bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001343 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001344 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001345 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001346 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001347 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1348 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001349
Mike Stump1eb44332009-09-09 15:08:12 +00001350 // Conversion from a null pointer constant to any Objective-C pointer type.
1351 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001352 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001353 ConvertedType = ToType;
1354 return true;
1355 }
1356
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001357 // Blocks: Block pointers can be converted to void*.
1358 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001359 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001360 ConvertedType = ToType;
1361 return true;
1362 }
1363 // Blocks: A null pointer constant can be converted to a block
1364 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001365 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001366 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001367 ConvertedType = ToType;
1368 return true;
1369 }
1370
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001371 // If the left-hand-side is nullptr_t, the right side can be a null
1372 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001373 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001374 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001375 ConvertedType = ToType;
1376 return true;
1377 }
1378
Ted Kremenek6217b802009-07-29 21:53:49 +00001379 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001380 if (!ToTypePtr)
1381 return false;
1382
1383 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001384 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001385 ConvertedType = ToType;
1386 return true;
1387 }
Sebastian Redl07779722008-10-31 14:43:28 +00001388
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001389 // Beyond this point, both types need to be pointers
1390 // , including objective-c pointers.
1391 QualType ToPointeeType = ToTypePtr->getPointeeType();
1392 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1393 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1394 ToType, Context);
1395 return true;
1396
1397 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001398 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001399 if (!FromTypePtr)
1400 return false;
1401
1402 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001403
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001404 // An rvalue of type "pointer to cv T," where T is an object type,
1405 // can be converted to an rvalue of type "pointer to cv void" (C++
1406 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001407 if (FromPointeeType->isIncompleteOrObjectType() &&
1408 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001409 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001410 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001411 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001412 return true;
1413 }
1414
Douglas Gregorf9201e02009-02-11 23:02:49 +00001415 // When we're overloading in C, we allow a special kind of pointer
1416 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001417 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001418 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001419 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001420 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001421 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001422 return true;
1423 }
1424
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001425 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001426 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001427 // An rvalue of type "pointer to cv D," where D is a class type,
1428 // can be converted to an rvalue of type "pointer to cv B," where
1429 // B is a base class (clause 10) of D. If B is an inaccessible
1430 // (clause 11) or ambiguous (10.2) base class of D, a program that
1431 // necessitates this conversion is ill-formed. The result of the
1432 // conversion is a pointer to the base class sub-object of the
1433 // derived class object. The null pointer value is converted to
1434 // the null pointer value of the destination type.
1435 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001436 // Note that we do not check for ambiguity or inaccessibility
1437 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001438 if (getLangOptions().CPlusPlus &&
1439 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001440 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001441 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001442 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001443 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001444 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001445 ToType, Context);
1446 return true;
1447 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001448
Douglas Gregorc7887512008-12-19 19:13:09 +00001449 return false;
1450}
1451
1452/// isObjCPointerConversion - Determines whether this is an
1453/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1454/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001455bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001456 QualType& ConvertedType,
1457 bool &IncompatibleObjC) {
1458 if (!getLangOptions().ObjC1)
1459 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001460
Steve Naroff14108da2009-07-10 23:34:53 +00001461 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001462 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001463 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001464 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001465
Steve Naroff14108da2009-07-10 23:34:53 +00001466 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001467 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001468 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001469 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001470 ConvertedType = ToType;
1471 return true;
1472 }
1473 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001474 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001475 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001476 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001477 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001478 ConvertedType = ToType;
1479 return true;
1480 }
1481 // Objective C++: We're able to convert from a pointer to an
1482 // interface to a pointer to a different interface.
1483 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001484 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1485 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1486 if (getLangOptions().CPlusPlus && LHS && RHS &&
1487 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1488 FromObjCPtr->getPointeeType()))
1489 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001490 ConvertedType = ToType;
1491 return true;
1492 }
1493
1494 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1495 // Okay: this is some kind of implicit downcast of Objective-C
1496 // interfaces, which is permitted. However, we're going to
1497 // complain about it.
1498 IncompatibleObjC = true;
1499 ConvertedType = FromType;
1500 return true;
1501 }
Mike Stump1eb44332009-09-09 15:08:12 +00001502 }
Steve Naroff14108da2009-07-10 23:34:53 +00001503 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001504 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001505 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001506 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001507 else if (const BlockPointerType *ToBlockPtr =
1508 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001509 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001510 // to a block pointer type.
1511 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1512 ConvertedType = ToType;
1513 return true;
1514 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001515 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001516 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001517 else if (FromType->getAs<BlockPointerType>() &&
1518 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1519 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001520 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001521 ConvertedType = ToType;
1522 return true;
1523 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001524 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001525 return false;
1526
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001527 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001528 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001529 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001530 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001531 FromPointeeType = FromBlockPtr->getPointeeType();
1532 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001533 return false;
1534
Douglas Gregorc7887512008-12-19 19:13:09 +00001535 // If we have pointers to pointers, recursively check whether this
1536 // is an Objective-C conversion.
1537 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1538 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1539 IncompatibleObjC)) {
1540 // We always complain about this conversion.
1541 IncompatibleObjC = true;
1542 ConvertedType = ToType;
1543 return true;
1544 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001545 // Allow conversion of pointee being objective-c pointer to another one;
1546 // as in I* to id.
1547 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1548 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1549 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1550 IncompatibleObjC)) {
1551 ConvertedType = ToType;
1552 return true;
1553 }
1554
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001555 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001556 // differences in the argument and result types are in Objective-C
1557 // pointer conversions. If so, we permit the conversion (but
1558 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001559 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001560 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001561 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001562 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001563 if (FromFunctionType && ToFunctionType) {
1564 // If the function types are exactly the same, this isn't an
1565 // Objective-C pointer conversion.
1566 if (Context.getCanonicalType(FromPointeeType)
1567 == Context.getCanonicalType(ToPointeeType))
1568 return false;
1569
1570 // Perform the quick checks that will tell us whether these
1571 // function types are obviously different.
1572 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1573 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1574 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1575 return false;
1576
1577 bool HasObjCConversion = false;
1578 if (Context.getCanonicalType(FromFunctionType->getResultType())
1579 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1580 // Okay, the types match exactly. Nothing to do.
1581 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1582 ToFunctionType->getResultType(),
1583 ConvertedType, IncompatibleObjC)) {
1584 // Okay, we have an Objective-C pointer conversion.
1585 HasObjCConversion = true;
1586 } else {
1587 // Function types are too different. Abort.
1588 return false;
1589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Douglas Gregorc7887512008-12-19 19:13:09 +00001591 // Check argument types.
1592 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1593 ArgIdx != NumArgs; ++ArgIdx) {
1594 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1595 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1596 if (Context.getCanonicalType(FromArgType)
1597 == Context.getCanonicalType(ToArgType)) {
1598 // Okay, the types match exactly. Nothing to do.
1599 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1600 ConvertedType, IncompatibleObjC)) {
1601 // Okay, we have an Objective-C pointer conversion.
1602 HasObjCConversion = true;
1603 } else {
1604 // Argument types are too different. Abort.
1605 return false;
1606 }
1607 }
1608
1609 if (HasObjCConversion) {
1610 // We had an Objective-C conversion. Allow this pointer
1611 // conversion, but complain about it.
1612 ConvertedType = ToType;
1613 IncompatibleObjC = true;
1614 return true;
1615 }
1616 }
1617
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001618 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001619}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001620
1621/// FunctionArgTypesAreEqual - This routine checks two function proto types
1622/// for equlity of their argument types. Caller has already checked that
1623/// they have same number of arguments. This routine assumes that Objective-C
1624/// pointer types which only differ in their protocol qualifiers are equal.
1625bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1626 FunctionProtoType* NewType){
1627 if (!getLangOptions().ObjC1)
1628 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1629 NewType->arg_type_begin());
1630
1631 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1632 N = NewType->arg_type_begin(),
1633 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1634 QualType ToType = (*O);
1635 QualType FromType = (*N);
1636 if (ToType != FromType) {
1637 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1638 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001639 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1640 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1641 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1642 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001643 continue;
1644 }
John McCallc12c5bb2010-05-15 11:32:37 +00001645 else if (const ObjCObjectPointerType *PTTo =
1646 ToType->getAs<ObjCObjectPointerType>()) {
1647 if (const ObjCObjectPointerType *PTFr =
1648 FromType->getAs<ObjCObjectPointerType>())
1649 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1650 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001651 }
1652 return false;
1653 }
1654 }
1655 return true;
1656}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001657
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001658/// CheckPointerConversion - Check the pointer conversion from the
1659/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001660/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001661/// conversions for which IsPointerConversion has already returned
1662/// true. It returns true and produces a diagnostic if there was an
1663/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001664bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001665 CastExpr::CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001666 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001667 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001668 QualType FromType = From->getType();
1669
Douglas Gregord7a95972010-06-08 17:35:15 +00001670 if (CXXBoolLiteralExpr* LitBool
1671 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1672 if (LitBool->getValue() == false)
1673 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1674 << ToType;
1675
Ted Kremenek6217b802009-07-29 21:53:49 +00001676 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1677 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001678 QualType FromPointeeType = FromPtrType->getPointeeType(),
1679 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001680
Douglas Gregor5fccd362010-03-03 23:55:11 +00001681 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1682 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001683 // We must have a derived-to-base conversion. Check an
1684 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001685 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1686 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001687 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001688 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001689 return true;
1690
1691 // The conversion was successful.
1692 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001693 }
1694 }
Mike Stump1eb44332009-09-09 15:08:12 +00001695 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001696 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001697 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001698 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001699 // Objective-C++ conversions are always okay.
1700 // FIXME: We should have a different class of conversions for the
1701 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001702 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001703 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001704
Steve Naroff14108da2009-07-10 23:34:53 +00001705 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001706 return false;
1707}
1708
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001709/// IsMemberPointerConversion - Determines whether the conversion of the
1710/// expression From, which has the (possibly adjusted) type FromType, can be
1711/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1712/// If so, returns true and places the converted type (that might differ from
1713/// ToType in its cv-qualifiers at some level) into ConvertedType.
1714bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001715 QualType ToType,
1716 bool InOverloadResolution,
1717 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001718 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001719 if (!ToTypePtr)
1720 return false;
1721
1722 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001723 if (From->isNullPointerConstant(Context,
1724 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1725 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001726 ConvertedType = ToType;
1727 return true;
1728 }
1729
1730 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001731 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001732 if (!FromTypePtr)
1733 return false;
1734
1735 // A pointer to member of B can be converted to a pointer to member of D,
1736 // where D is derived from B (C++ 4.11p2).
1737 QualType FromClass(FromTypePtr->getClass(), 0);
1738 QualType ToClass(ToTypePtr->getClass(), 0);
1739 // FIXME: What happens when these are dependent? Is this function even called?
1740
1741 if (IsDerivedFrom(ToClass, FromClass)) {
1742 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1743 ToClass.getTypePtr());
1744 return true;
1745 }
1746
1747 return false;
1748}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001749
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001750/// CheckMemberPointerConversion - Check the member pointer conversion from the
1751/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001752/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001753/// for which IsMemberPointerConversion has already returned true. It returns
1754/// true and produces a diagnostic if there was an error, or returns false
1755/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001756bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001757 CastExpr::CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001758 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001759 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001760 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001761 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001762 if (!FromPtrType) {
1763 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001764 assert(From->isNullPointerConstant(Context,
1765 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001766 "Expr must be null pointer constant!");
1767 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001768 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001769 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001770
Ted Kremenek6217b802009-07-29 21:53:49 +00001771 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001772 assert(ToPtrType && "No member pointer cast has a target type "
1773 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001774
Sebastian Redl21593ac2009-01-28 18:33:18 +00001775 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1776 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001777
Sebastian Redl21593ac2009-01-28 18:33:18 +00001778 // FIXME: What about dependent types?
1779 assert(FromClass->isRecordType() && "Pointer into non-class.");
1780 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001781
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001782 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001783 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001784 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1785 assert(DerivationOkay &&
1786 "Should not have been called if derivation isn't OK.");
1787 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001788
Sebastian Redl21593ac2009-01-28 18:33:18 +00001789 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1790 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001791 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1792 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1793 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1794 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001795 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001796
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001797 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001798 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1799 << FromClass << ToClass << QualType(VBase, 0)
1800 << From->getSourceRange();
1801 return true;
1802 }
1803
John McCall6b2accb2010-02-10 09:31:12 +00001804 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001805 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1806 Paths.front(),
1807 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001808
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001809 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001810 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001811 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001812 return false;
1813}
1814
Douglas Gregor98cd5992008-10-21 23:43:52 +00001815/// IsQualificationConversion - Determines whether the conversion from
1816/// an rvalue of type FromType to ToType is a qualification conversion
1817/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001818bool
1819Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001820 FromType = Context.getCanonicalType(FromType);
1821 ToType = Context.getCanonicalType(ToType);
1822
1823 // If FromType and ToType are the same type, this is not a
1824 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001825 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001826 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001827
Douglas Gregor98cd5992008-10-21 23:43:52 +00001828 // (C++ 4.4p4):
1829 // A conversion can add cv-qualifiers at levels other than the first
1830 // in multi-level pointers, subject to the following rules: [...]
1831 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001832 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001833 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001834 // Within each iteration of the loop, we check the qualifiers to
1835 // determine if this still looks like a qualification
1836 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001837 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001838 // until there are no more pointers or pointers-to-members left to
1839 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001840 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001841
1842 // -- for every j > 0, if const is in cv 1,j then const is in cv
1843 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001844 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001845 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Douglas Gregor98cd5992008-10-21 23:43:52 +00001847 // -- if the cv 1,j and cv 2,j are different, then const is in
1848 // every cv for 0 < k < j.
1849 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001850 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001851 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Douglas Gregor98cd5992008-10-21 23:43:52 +00001853 // Keep track of whether all prior cv-qualifiers in the "to" type
1854 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001855 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001856 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001857 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001858
1859 // We are left with FromType and ToType being the pointee types
1860 // after unwrapping the original FromType and ToType the same number
1861 // of types. If we unwrapped any pointers, and if FromType and
1862 // ToType have the same unqualified type (since we checked
1863 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001864 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001865}
1866
Douglas Gregor734d9862009-01-30 23:27:23 +00001867/// Determines whether there is a user-defined conversion sequence
1868/// (C++ [over.ics.user]) that converts expression From to the type
1869/// ToType. If such a conversion exists, User will contain the
1870/// user-defined conversion sequence that performs such a conversion
1871/// and this routine will return true. Otherwise, this routine returns
1872/// false and User is unspecified.
1873///
Douglas Gregor734d9862009-01-30 23:27:23 +00001874/// \param AllowExplicit true if the conversion should consider C++0x
1875/// "explicit" conversion functions as well as non-explicit conversion
1876/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor20093b42009-12-09 23:02:17 +00001877OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1878 UserDefinedConversionSequence& User,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001879 OverloadCandidateSet& CandidateSet,
1880 bool AllowExplicit) {
1881 // Whether we will only visit constructors.
1882 bool ConstructorsOnly = false;
1883
1884 // If the type we are conversion to is a class type, enumerate its
1885 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001886 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001887 // C++ [over.match.ctor]p1:
1888 // When objects of class type are direct-initialized (8.5), or
1889 // copy-initialized from an expression of the same or a
1890 // derived class type (8.5), overload resolution selects the
1891 // constructor. [...] For copy-initialization, the candidate
1892 // functions are all the converting constructors (12.3.1) of
1893 // that class. The argument list is the expression-list within
1894 // the parentheses of the initializer.
1895 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1896 (From->getType()->getAs<RecordType>() &&
1897 IsDerivedFrom(From->getType(), ToType)))
1898 ConstructorsOnly = true;
1899
Douglas Gregor393896f2009-11-05 13:06:35 +00001900 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1901 // We're not going to find any constructors.
1902 } else if (CXXRecordDecl *ToRecordDecl
1903 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001904 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00001905 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001906 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001907 NamedDecl *D = *Con;
1908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1909
Douglas Gregordec06662009-08-21 18:42:58 +00001910 // Find the constructor (which may be a template).
1911 CXXConstructorDecl *Constructor = 0;
1912 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001913 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001914 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001915 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1917 else
John McCall9aa472c2010-03-19 07:35:19 +00001918 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001919
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001920 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001921 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001922 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001923 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001924 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001925 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001926 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001927 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001928 // Allow one user-defined conversion when user specifies a
1929 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001930 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001931 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001932 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001933 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001934 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001935 }
1936 }
1937
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001938 // Enumerate conversion functions, if we're allowed to.
1939 if (ConstructorsOnly) {
Mike Stump1eb44332009-09-09 15:08:12 +00001940 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001941 PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001942 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001943 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001944 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001945 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001946 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1947 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001948 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001949 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001950 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001951 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001952 DeclAccessPair FoundDecl = I.getPair();
1953 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001954 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1955 if (isa<UsingShadowDecl>(D))
1956 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1957
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001958 CXXConversionDecl *Conv;
1959 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001960 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1961 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001962 else
John McCall32daa422010-03-31 01:36:47 +00001963 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001964
1965 if (AllowExplicit || !Conv->isExplicit()) {
1966 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001967 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001968 ActingContext, From, ToType,
1969 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001970 else
John McCall9aa472c2010-03-19 07:35:19 +00001971 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001972 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001973 }
1974 }
1975 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001976 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001977
1978 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001979 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001980 case OR_Success:
1981 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001982 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001983 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1984 // C++ [over.ics.user]p1:
1985 // If the user-defined conversion is specified by a
1986 // constructor (12.3.1), the initial standard conversion
1987 // sequence converts the source type to the type required by
1988 // the argument of the constructor.
1989 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001990 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001991 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001992 User.EllipsisConversion = true;
1993 else {
1994 User.Before = Best->Conversions[0].Standard;
1995 User.EllipsisConversion = false;
1996 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001997 User.ConversionFunction = Constructor;
1998 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001999 User.After.setFromType(
2000 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00002001 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002002 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002003 } else if (CXXConversionDecl *Conversion
2004 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2005 // C++ [over.ics.user]p1:
2006 //
2007 // [...] If the user-defined conversion is specified by a
2008 // conversion function (12.3.2), the initial standard
2009 // conversion sequence converts the source type to the
2010 // implicit object parameter of the conversion function.
2011 User.Before = Best->Conversions[0].Standard;
2012 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002013 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
2015 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002016 // The second standard conversion sequence converts the
2017 // result of the user-defined conversion to the target type
2018 // for the sequence. Since an implicit conversion sequence
2019 // is an initialization, the special rules for
2020 // initialization by user-defined conversion apply when
2021 // selecting the best user-defined conversion for a
2022 // user-defined conversion sequence (see 13.3.3 and
2023 // 13.3.3.1).
2024 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002025 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002026 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002027 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002028 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002029 }
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Douglas Gregor60d62c22008-10-31 16:23:19 +00002031 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002032 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002033 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00002034 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002035 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002036
2037 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002038 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002039 }
2040
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002041 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002042}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002043
2044bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002045Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002046 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002047 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002048 OverloadingResult OvResult =
2049 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002050 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002051 if (OvResult == OR_Ambiguous)
2052 Diag(From->getSourceRange().getBegin(),
2053 diag::err_typecheck_ambiguous_condition)
2054 << From->getType() << ToType << From->getSourceRange();
2055 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2056 Diag(From->getSourceRange().getBegin(),
2057 diag::err_typecheck_nonviable_condition)
2058 << From->getType() << ToType << From->getSourceRange();
2059 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002060 return false;
John McCallcbce6062010-01-12 07:18:19 +00002061 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002062 return true;
2063}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002064
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002065/// CompareImplicitConversionSequences - Compare two implicit
2066/// conversion sequences to determine whether one is better than the
2067/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00002068ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002069Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2070 const ImplicitConversionSequence& ICS2)
2071{
2072 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2073 // conversion sequences (as defined in 13.3.3.1)
2074 // -- a standard conversion sequence (13.3.3.1.1) is a better
2075 // conversion sequence than a user-defined conversion sequence or
2076 // an ellipsis conversion sequence, and
2077 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2078 // conversion sequence than an ellipsis conversion sequence
2079 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002080 //
John McCall1d318332010-01-12 00:44:57 +00002081 // C++0x [over.best.ics]p10:
2082 // For the purpose of ranking implicit conversion sequences as
2083 // described in 13.3.3.2, the ambiguous conversion sequence is
2084 // treated as a user-defined sequence that is indistinguishable
2085 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002086 if (ICS1.getKindRank() < ICS2.getKindRank())
2087 return ImplicitConversionSequence::Better;
2088 else if (ICS2.getKindRank() < ICS1.getKindRank())
2089 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002090
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002091 // The following checks require both conversion sequences to be of
2092 // the same kind.
2093 if (ICS1.getKind() != ICS2.getKind())
2094 return ImplicitConversionSequence::Indistinguishable;
2095
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002096 // Two implicit conversion sequences of the same form are
2097 // indistinguishable conversion sequences unless one of the
2098 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002099 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002100 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002101 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002102 // User-defined conversion sequence U1 is a better conversion
2103 // sequence than another user-defined conversion sequence U2 if
2104 // they contain the same user-defined conversion function or
2105 // constructor and if the second standard conversion sequence of
2106 // U1 is better than the second standard conversion sequence of
2107 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002108 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002109 ICS2.UserDefined.ConversionFunction)
2110 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2111 ICS2.UserDefined.After);
2112 }
2113
2114 return ImplicitConversionSequence::Indistinguishable;
2115}
2116
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002117static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2118 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2119 Qualifiers Quals;
2120 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2121 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2122 }
2123
2124 return Context.hasSameUnqualifiedType(T1, T2);
2125}
2126
Douglas Gregorad323a82010-01-27 03:51:04 +00002127// Per 13.3.3.2p3, compare the given standard conversion sequences to
2128// determine if one is a proper subset of the other.
2129static ImplicitConversionSequence::CompareKind
2130compareStandardConversionSubsets(ASTContext &Context,
2131 const StandardConversionSequence& SCS1,
2132 const StandardConversionSequence& SCS2) {
2133 ImplicitConversionSequence::CompareKind Result
2134 = ImplicitConversionSequence::Indistinguishable;
2135
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002136 // the identity conversion sequence is considered to be a subsequence of
2137 // any non-identity conversion sequence
2138 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2139 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2140 return ImplicitConversionSequence::Better;
2141 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2142 return ImplicitConversionSequence::Worse;
2143 }
2144
Douglas Gregorad323a82010-01-27 03:51:04 +00002145 if (SCS1.Second != SCS2.Second) {
2146 if (SCS1.Second == ICK_Identity)
2147 Result = ImplicitConversionSequence::Better;
2148 else if (SCS2.Second == ICK_Identity)
2149 Result = ImplicitConversionSequence::Worse;
2150 else
2151 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002152 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002153 return ImplicitConversionSequence::Indistinguishable;
2154
2155 if (SCS1.Third == SCS2.Third) {
2156 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2157 : ImplicitConversionSequence::Indistinguishable;
2158 }
2159
2160 if (SCS1.Third == ICK_Identity)
2161 return Result == ImplicitConversionSequence::Worse
2162 ? ImplicitConversionSequence::Indistinguishable
2163 : ImplicitConversionSequence::Better;
2164
2165 if (SCS2.Third == ICK_Identity)
2166 return Result == ImplicitConversionSequence::Better
2167 ? ImplicitConversionSequence::Indistinguishable
2168 : ImplicitConversionSequence::Worse;
2169
2170 return ImplicitConversionSequence::Indistinguishable;
2171}
2172
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002173/// CompareStandardConversionSequences - Compare two standard
2174/// conversion sequences to determine whether one is better than the
2175/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002176ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002177Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2178 const StandardConversionSequence& SCS2)
2179{
2180 // Standard conversion sequence S1 is a better conversion sequence
2181 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2182
2183 // -- S1 is a proper subsequence of S2 (comparing the conversion
2184 // sequences in the canonical form defined by 13.3.3.1.1,
2185 // excluding any Lvalue Transformation; the identity conversion
2186 // sequence is considered to be a subsequence of any
2187 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002188 if (ImplicitConversionSequence::CompareKind CK
2189 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2190 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002191
2192 // -- the rank of S1 is better than the rank of S2 (by the rules
2193 // defined below), or, if not that,
2194 ImplicitConversionRank Rank1 = SCS1.getRank();
2195 ImplicitConversionRank Rank2 = SCS2.getRank();
2196 if (Rank1 < Rank2)
2197 return ImplicitConversionSequence::Better;
2198 else if (Rank2 < Rank1)
2199 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002200
Douglas Gregor57373262008-10-22 14:17:15 +00002201 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2202 // are indistinguishable unless one of the following rules
2203 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Douglas Gregor57373262008-10-22 14:17:15 +00002205 // A conversion that is not a conversion of a pointer, or
2206 // pointer to member, to bool is better than another conversion
2207 // that is such a conversion.
2208 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2209 return SCS2.isPointerConversionToBool()
2210 ? ImplicitConversionSequence::Better
2211 : ImplicitConversionSequence::Worse;
2212
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002213 // C++ [over.ics.rank]p4b2:
2214 //
2215 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002216 // conversion of B* to A* is better than conversion of B* to
2217 // void*, and conversion of A* to void* is better than conversion
2218 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002219 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002220 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002221 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002222 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002223 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2224 // Exactly one of the conversion sequences is a conversion to
2225 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002226 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2227 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002228 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2229 // Neither conversion sequence converts to a void pointer; compare
2230 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002231 if (ImplicitConversionSequence::CompareKind DerivedCK
2232 = CompareDerivedToBaseConversions(SCS1, SCS2))
2233 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002234 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2235 // Both conversion sequences are conversions to void
2236 // pointers. Compare the source types to determine if there's an
2237 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002238 QualType FromType1 = SCS1.getFromType();
2239 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002240
2241 // Adjust the types we're converting from via the array-to-pointer
2242 // conversion, if we need to.
2243 if (SCS1.First == ICK_Array_To_Pointer)
2244 FromType1 = Context.getArrayDecayedType(FromType1);
2245 if (SCS2.First == ICK_Array_To_Pointer)
2246 FromType2 = Context.getArrayDecayedType(FromType2);
2247
Douglas Gregor01919692009-12-13 21:37:05 +00002248 QualType FromPointee1
2249 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2250 QualType FromPointee2
2251 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002252
Douglas Gregor01919692009-12-13 21:37:05 +00002253 if (IsDerivedFrom(FromPointee2, FromPointee1))
2254 return ImplicitConversionSequence::Better;
2255 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2256 return ImplicitConversionSequence::Worse;
2257
2258 // Objective-C++: If one interface is more specific than the
2259 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002260 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2261 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002262 if (FromIface1 && FromIface1) {
2263 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2264 return ImplicitConversionSequence::Better;
2265 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2266 return ImplicitConversionSequence::Worse;
2267 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002268 }
Douglas Gregor57373262008-10-22 14:17:15 +00002269
2270 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2271 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002272 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00002273 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002274 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002275
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002276 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002277 // C++0x [over.ics.rank]p3b4:
2278 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2279 // implicit object parameter of a non-static member function declared
2280 // without a ref-qualifier, and S1 binds an rvalue reference to an
2281 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002282 // FIXME: We don't know if we're dealing with the implicit object parameter,
2283 // or if the member function in this case has a ref qualifier.
2284 // (Of course, we don't have ref qualifiers yet.)
2285 if (SCS1.RRefBinding != SCS2.RRefBinding)
2286 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2287 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002288
2289 // C++ [over.ics.rank]p3b4:
2290 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2291 // which the references refer are the same type except for
2292 // top-level cv-qualifiers, and the type to which the reference
2293 // initialized by S2 refers is more cv-qualified than the type
2294 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002295 QualType T1 = SCS1.getToType(2);
2296 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002297 T1 = Context.getCanonicalType(T1);
2298 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002299 Qualifiers T1Quals, T2Quals;
2300 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2301 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2302 if (UnqualT1 == UnqualT2) {
2303 // If the type is an array type, promote the element qualifiers to the type
2304 // for comparison.
2305 if (isa<ArrayType>(T1) && T1Quals)
2306 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2307 if (isa<ArrayType>(T2) && T2Quals)
2308 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002309 if (T2.isMoreQualifiedThan(T1))
2310 return ImplicitConversionSequence::Better;
2311 else if (T1.isMoreQualifiedThan(T2))
2312 return ImplicitConversionSequence::Worse;
2313 }
2314 }
Douglas Gregor57373262008-10-22 14:17:15 +00002315
2316 return ImplicitConversionSequence::Indistinguishable;
2317}
2318
2319/// CompareQualificationConversions - Compares two standard conversion
2320/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002321/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2322ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00002323Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00002324 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002325 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002326 // -- S1 and S2 differ only in their qualification conversion and
2327 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2328 // cv-qualification signature of type T1 is a proper subset of
2329 // the cv-qualification signature of type T2, and S1 is not the
2330 // deprecated string literal array-to-pointer conversion (4.2).
2331 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2332 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2333 return ImplicitConversionSequence::Indistinguishable;
2334
2335 // FIXME: the example in the standard doesn't use a qualification
2336 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002337 QualType T1 = SCS1.getToType(2);
2338 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00002339 T1 = Context.getCanonicalType(T1);
2340 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002341 Qualifiers T1Quals, T2Quals;
2342 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2343 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002344
2345 // If the types are the same, we won't learn anything by unwrapped
2346 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002347 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002348 return ImplicitConversionSequence::Indistinguishable;
2349
Chandler Carruth28e318c2009-12-29 07:16:59 +00002350 // If the type is an array type, promote the element qualifiers to the type
2351 // for comparison.
2352 if (isa<ArrayType>(T1) && T1Quals)
2353 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2354 if (isa<ArrayType>(T2) && T2Quals)
2355 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2356
Mike Stump1eb44332009-09-09 15:08:12 +00002357 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002358 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002359 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002360 // Within each iteration of the loop, we check the qualifiers to
2361 // determine if this still looks like a qualification
2362 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002363 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002364 // until there are no more pointers or pointers-to-members left
2365 // to unwrap. This essentially mimics what
2366 // IsQualificationConversion does, but here we're checking for a
2367 // strict subset of qualifiers.
2368 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2369 // The qualifiers are the same, so this doesn't tell us anything
2370 // about how the sequences rank.
2371 ;
2372 else if (T2.isMoreQualifiedThan(T1)) {
2373 // T1 has fewer qualifiers, so it could be the better sequence.
2374 if (Result == ImplicitConversionSequence::Worse)
2375 // Neither has qualifiers that are a subset of the other's
2376 // qualifiers.
2377 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Douglas Gregor57373262008-10-22 14:17:15 +00002379 Result = ImplicitConversionSequence::Better;
2380 } else if (T1.isMoreQualifiedThan(T2)) {
2381 // T2 has fewer qualifiers, so it could be the better sequence.
2382 if (Result == ImplicitConversionSequence::Better)
2383 // Neither has qualifiers that are a subset of the other's
2384 // qualifiers.
2385 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Douglas Gregor57373262008-10-22 14:17:15 +00002387 Result = ImplicitConversionSequence::Worse;
2388 } else {
2389 // Qualifiers are disjoint.
2390 return ImplicitConversionSequence::Indistinguishable;
2391 }
2392
2393 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002394 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002395 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002396 }
2397
Douglas Gregor57373262008-10-22 14:17:15 +00002398 // Check that the winning standard conversion sequence isn't using
2399 // the deprecated string literal array to pointer conversion.
2400 switch (Result) {
2401 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002402 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002403 Result = ImplicitConversionSequence::Indistinguishable;
2404 break;
2405
2406 case ImplicitConversionSequence::Indistinguishable:
2407 break;
2408
2409 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002410 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002411 Result = ImplicitConversionSequence::Indistinguishable;
2412 break;
2413 }
2414
2415 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002416}
2417
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002418/// CompareDerivedToBaseConversions - Compares two standard conversion
2419/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002420/// various kinds of derived-to-base conversions (C++
2421/// [over.ics.rank]p4b3). As part of these checks, we also look at
2422/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002423ImplicitConversionSequence::CompareKind
2424Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2425 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002426 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002427 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002428 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002429 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002430
2431 // Adjust the types we're converting from via the array-to-pointer
2432 // conversion, if we need to.
2433 if (SCS1.First == ICK_Array_To_Pointer)
2434 FromType1 = Context.getArrayDecayedType(FromType1);
2435 if (SCS2.First == ICK_Array_To_Pointer)
2436 FromType2 = Context.getArrayDecayedType(FromType2);
2437
2438 // Canonicalize all of the types.
2439 FromType1 = Context.getCanonicalType(FromType1);
2440 ToType1 = Context.getCanonicalType(ToType1);
2441 FromType2 = Context.getCanonicalType(FromType2);
2442 ToType2 = Context.getCanonicalType(ToType2);
2443
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002444 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002445 //
2446 // If class B is derived directly or indirectly from class A and
2447 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002448 //
2449 // For Objective-C, we let A, B, and C also be Objective-C
2450 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002451
2452 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002453 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002454 SCS2.Second == ICK_Pointer_Conversion &&
2455 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2456 FromType1->isPointerType() && FromType2->isPointerType() &&
2457 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002458 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002459 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002460 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002461 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002462 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002463 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002464 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002465 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002466
John McCallc12c5bb2010-05-15 11:32:37 +00002467 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2468 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2469 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2470 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002471
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002472 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002473 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2474 if (IsDerivedFrom(ToPointee1, ToPointee2))
2475 return ImplicitConversionSequence::Better;
2476 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2477 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002478
2479 if (ToIface1 && ToIface2) {
2480 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2481 return ImplicitConversionSequence::Better;
2482 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2483 return ImplicitConversionSequence::Worse;
2484 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002485 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002486
2487 // -- conversion of B* to A* is better than conversion of C* to A*,
2488 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2489 if (IsDerivedFrom(FromPointee2, FromPointee1))
2490 return ImplicitConversionSequence::Better;
2491 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2492 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002493
Douglas Gregorcb7de522008-11-26 23:31:11 +00002494 if (FromIface1 && FromIface2) {
2495 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2496 return ImplicitConversionSequence::Better;
2497 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2498 return ImplicitConversionSequence::Worse;
2499 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002500 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002501 }
2502
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002503 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002504 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2505 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2506 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2507 const MemberPointerType * FromMemPointer1 =
2508 FromType1->getAs<MemberPointerType>();
2509 const MemberPointerType * ToMemPointer1 =
2510 ToType1->getAs<MemberPointerType>();
2511 const MemberPointerType * FromMemPointer2 =
2512 FromType2->getAs<MemberPointerType>();
2513 const MemberPointerType * ToMemPointer2 =
2514 ToType2->getAs<MemberPointerType>();
2515 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2516 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2517 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2518 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2519 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2520 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2521 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2522 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002523 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002524 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2525 if (IsDerivedFrom(ToPointee1, ToPointee2))
2526 return ImplicitConversionSequence::Worse;
2527 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2528 return ImplicitConversionSequence::Better;
2529 }
2530 // conversion of B::* to C::* is better than conversion of A::* to C::*
2531 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2532 if (IsDerivedFrom(FromPointee1, FromPointee2))
2533 return ImplicitConversionSequence::Better;
2534 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2535 return ImplicitConversionSequence::Worse;
2536 }
2537 }
2538
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002539 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002540 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002541 // -- binding of an expression of type C to a reference of type
2542 // B& is better than binding an expression of type C to a
2543 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002544 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2545 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002546 if (IsDerivedFrom(ToType1, ToType2))
2547 return ImplicitConversionSequence::Better;
2548 else if (IsDerivedFrom(ToType2, ToType1))
2549 return ImplicitConversionSequence::Worse;
2550 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002551
Douglas Gregor225c41e2008-11-03 19:09:14 +00002552 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002553 // -- binding of an expression of type B to a reference of type
2554 // A& is better than binding an expression of type C to a
2555 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002556 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2557 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002558 if (IsDerivedFrom(FromType2, FromType1))
2559 return ImplicitConversionSequence::Better;
2560 else if (IsDerivedFrom(FromType1, FromType2))
2561 return ImplicitConversionSequence::Worse;
2562 }
2563 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002564
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002565 return ImplicitConversionSequence::Indistinguishable;
2566}
2567
Douglas Gregorabe183d2010-04-13 16:31:36 +00002568/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2569/// determine whether they are reference-related,
2570/// reference-compatible, reference-compatible with added
2571/// qualification, or incompatible, for use in C++ initialization by
2572/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2573/// type, and the first type (T1) is the pointee type of the reference
2574/// type being initialized.
2575Sema::ReferenceCompareResult
2576Sema::CompareReferenceRelationship(SourceLocation Loc,
2577 QualType OrigT1, QualType OrigT2,
2578 bool& DerivedToBase) {
2579 assert(!OrigT1->isReferenceType() &&
2580 "T1 must be the pointee type of the reference type");
2581 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2582
2583 QualType T1 = Context.getCanonicalType(OrigT1);
2584 QualType T2 = Context.getCanonicalType(OrigT2);
2585 Qualifiers T1Quals, T2Quals;
2586 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2587 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2588
2589 // C++ [dcl.init.ref]p4:
2590 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2591 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2592 // T1 is a base class of T2.
2593 if (UnqualT1 == UnqualT2)
2594 DerivedToBase = false;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002595 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002596 IsDerivedFrom(UnqualT2, UnqualT1))
2597 DerivedToBase = true;
2598 else
2599 return Ref_Incompatible;
2600
2601 // At this point, we know that T1 and T2 are reference-related (at
2602 // least).
2603
2604 // If the type is an array type, promote the element qualifiers to the type
2605 // for comparison.
2606 if (isa<ArrayType>(T1) && T1Quals)
2607 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2608 if (isa<ArrayType>(T2) && T2Quals)
2609 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2610
2611 // C++ [dcl.init.ref]p4:
2612 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2613 // reference-related to T2 and cv1 is the same cv-qualification
2614 // as, or greater cv-qualification than, cv2. For purposes of
2615 // overload resolution, cases for which cv1 is greater
2616 // cv-qualification than cv2 are identified as
2617 // reference-compatible with added qualification (see 13.3.3.2).
2618 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2619 return Ref_Compatible;
2620 else if (T1.isMoreQualifiedThan(T2))
2621 return Ref_Compatible_With_Added_Qualification;
2622 else
2623 return Ref_Related;
2624}
2625
Sebastian Redl4680bf22010-06-30 18:13:39 +00002626/// \brief Look for a user-defined conversion to an lvalue reference-compatible
2627/// with DeclType. Return true if something definite is found.
2628static bool
2629FindConversionToLValue(Sema &S, ImplicitConversionSequence &ICS,
2630 QualType DeclType, SourceLocation DeclLoc,
2631 Expr *Init, QualType T2, bool AllowExplicit) {
2632 assert(T2->isRecordType() && "Can only find conversions of record types.");
2633 CXXRecordDecl *T2RecordDecl
2634 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2635
2636 OverloadCandidateSet CandidateSet(DeclLoc);
2637 const UnresolvedSetImpl *Conversions
2638 = T2RecordDecl->getVisibleConversionFunctions();
2639 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2640 E = Conversions->end(); I != E; ++I) {
2641 NamedDecl *D = *I;
2642 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2643 if (isa<UsingShadowDecl>(D))
2644 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2645
2646 FunctionTemplateDecl *ConvTemplate
2647 = dyn_cast<FunctionTemplateDecl>(D);
2648 CXXConversionDecl *Conv;
2649 if (ConvTemplate)
2650 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2651 else
2652 Conv = cast<CXXConversionDecl>(D);
2653
2654 // If the conversion function doesn't return a reference type,
2655 // it can't be considered for this conversion. An rvalue reference
2656 // is only acceptable if its referencee is a function type.
2657 const ReferenceType *RefType =
2658 Conv->getConversionType()->getAs<ReferenceType>();
2659 if (RefType && (RefType->isLValueReferenceType() ||
2660 RefType->getPointeeType()->isFunctionType()) &&
2661 (AllowExplicit || !Conv->isExplicit())) {
2662 if (ConvTemplate)
2663 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2664 Init, DeclType, CandidateSet);
2665 else
2666 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2667 DeclType, CandidateSet);
2668 }
2669 }
2670
2671 OverloadCandidateSet::iterator Best;
2672 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2673 case OR_Success:
2674 // C++ [over.ics.ref]p1:
2675 //
2676 // [...] If the parameter binds directly to the result of
2677 // applying a conversion function to the argument
2678 // expression, the implicit conversion sequence is a
2679 // user-defined conversion sequence (13.3.3.1.2), with the
2680 // second standard conversion sequence either an identity
2681 // conversion or, if the conversion function returns an
2682 // entity of a type that is a derived class of the parameter
2683 // type, a derived-to-base Conversion.
2684 if (!Best->FinalConversion.DirectBinding)
2685 return false;
2686
2687 ICS.setUserDefined();
2688 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2689 ICS.UserDefined.After = Best->FinalConversion;
2690 ICS.UserDefined.ConversionFunction = Best->Function;
2691 ICS.UserDefined.EllipsisConversion = false;
2692 assert(ICS.UserDefined.After.ReferenceBinding &&
2693 ICS.UserDefined.After.DirectBinding &&
2694 "Expected a direct reference binding!");
2695 return true;
2696
2697 case OR_Ambiguous:
2698 ICS.setAmbiguous();
2699 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2700 Cand != CandidateSet.end(); ++Cand)
2701 if (Cand->Viable)
2702 ICS.Ambiguous.addConversion(Cand->Function);
2703 return true;
2704
2705 case OR_No_Viable_Function:
2706 case OR_Deleted:
2707 // There was no suitable conversion, or we found a deleted
2708 // conversion; continue with other checks.
2709 return false;
2710 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002711
2712 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002713}
2714
Douglas Gregorabe183d2010-04-13 16:31:36 +00002715/// \brief Compute an implicit conversion sequence for reference
2716/// initialization.
2717static ImplicitConversionSequence
2718TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2719 SourceLocation DeclLoc,
2720 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002721 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002722 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2723
2724 // Most paths end in a failed conversion.
2725 ImplicitConversionSequence ICS;
2726 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2727
2728 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2729 QualType T2 = Init->getType();
2730
2731 // If the initializer is the address of an overloaded function, try
2732 // to resolve the overloaded function. If all goes well, T2 is the
2733 // type of the resulting function.
2734 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2735 DeclAccessPair Found;
2736 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2737 false, Found))
2738 T2 = Fn->getType();
2739 }
2740
2741 // Compute some basic properties of the types and the initializer.
2742 bool isRValRef = DeclType->isRValueReferenceType();
2743 bool DerivedToBase = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002744 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002745 Sema::ReferenceCompareResult RefRelationship
2746 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2747
Douglas Gregorabe183d2010-04-13 16:31:36 +00002748
Sebastian Redl4680bf22010-06-30 18:13:39 +00002749 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002750 // A reference to type "cv1 T1" is initialized by an expression
2751 // of type "cv2 T2" as follows:
2752
Sebastian Redl4680bf22010-06-30 18:13:39 +00002753 // -- If reference is an lvalue reference and the initializer expression
2754 // The next bullet point (T1 is a function) is pretty much equivalent to this
2755 // one, so it's handled here.
2756 if (!isRValRef || T1->isFunctionType()) {
2757 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2758 // reference-compatible with "cv2 T2," or
2759 //
2760 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2761 if (InitCategory.isLValue() &&
2762 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002763 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002764 // When a parameter of reference type binds directly (8.5.3)
2765 // to an argument expression, the implicit conversion sequence
2766 // is the identity conversion, unless the argument expression
2767 // has a type that is a derived class of the parameter type,
2768 // in which case the implicit conversion sequence is a
2769 // derived-to-base Conversion (13.3.3.1).
2770 ICS.setStandard();
2771 ICS.Standard.First = ICK_Identity;
2772 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2773 ICS.Standard.Third = ICK_Identity;
2774 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2775 ICS.Standard.setToType(0, T2);
2776 ICS.Standard.setToType(1, T1);
2777 ICS.Standard.setToType(2, T1);
2778 ICS.Standard.ReferenceBinding = true;
2779 ICS.Standard.DirectBinding = true;
2780 ICS.Standard.RRefBinding = isRValRef;
2781 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002782
Sebastian Redl4680bf22010-06-30 18:13:39 +00002783 // Nothing more to do: the inaccessibility/ambiguity check for
2784 // derived-to-base conversions is suppressed when we're
2785 // computing the implicit conversion sequence (C++
2786 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002787 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002788 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002789
Sebastian Redl4680bf22010-06-30 18:13:39 +00002790 // -- has a class type (i.e., T2 is a class type), where T1 is
2791 // not reference-related to T2, and can be implicitly
2792 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2793 // is reference-compatible with "cv3 T3" 92) (this
2794 // conversion is selected by enumerating the applicable
2795 // conversion functions (13.3.1.6) and choosing the best
2796 // one through overload resolution (13.3)),
2797 if (!SuppressUserConversions && T2->isRecordType() &&
2798 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2799 RefRelationship == Sema::Ref_Incompatible) {
2800 if (FindConversionToLValue(S, ICS, DeclType, DeclLoc,
2801 Init, T2, AllowExplicit))
2802 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002803 }
2804 }
2805
Sebastian Redl4680bf22010-06-30 18:13:39 +00002806 // -- Otherwise, the reference shall be an lvalue reference to a
2807 // non-volatile const type (i.e., cv1 shall be const), or the reference
2808 // shall be an rvalue reference and the initializer expression shall be
2809 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002810 //
2811 // We actually handle one oddity of C++ [over.ics.ref] at this
2812 // point, which is that, due to p2 (which short-circuits reference
2813 // binding by only attempting a simple conversion for non-direct
2814 // bindings) and p3's strange wording, we allow a const volatile
2815 // reference to bind to an rvalue. Hence the check for the presence
2816 // of "const" rather than checking for "const" being the only
2817 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002818 // This is also the point where rvalue references and lvalue inits no longer
2819 // go together.
2820 if ((!isRValRef && !T1.isConstQualified()) ||
2821 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002822 return ICS;
2823
Sebastian Redl4680bf22010-06-30 18:13:39 +00002824 // -- If T1 is a function type, then
2825 // -- if T2 is the same type as T1, the reference is bound to the
2826 // initializer expression lvalue;
2827 // -- if T2 is a class type and the initializer expression can be
2828 // implicitly converted to an lvalue of type T1 [...], the
2829 // reference is bound to the function lvalue that is the result
2830 // of the conversion;
2831 // This is the same as for the lvalue case above, so it was handled there.
2832 // -- otherwise, the program is ill-formed.
2833 // This is the one difference to the lvalue case.
2834 if (T1->isFunctionType())
2835 return ICS;
2836
2837 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002838 // -- the initializer expression is an rvalue and "cv1 T1"
2839 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002840 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002841 // -- T1 is not reference-related to T2 and the initializer
2842 // expression can be implicitly converted to an rvalue
2843 // of type "cv3 T3" (this conversion is selected by
2844 // enumerating the applicable conversion functions
2845 // (13.3.1.6) and choosing the best one through overload
2846 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002847 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002848 // then the reference is bound to the initializer
2849 // expression rvalue in the first case and to the object
2850 // that is the result of the conversion in the second case
2851 // (or, in either case, to the appropriate base class
2852 // subobject of the object).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002853 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002854 // We're only checking the first case here, which is a direct
2855 // binding in C++0x but not in C++03.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002856 if (InitCategory.isRValue() && T2->isRecordType() &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002857 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2858 ICS.setStandard();
2859 ICS.Standard.First = ICK_Identity;
2860 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2861 ICS.Standard.Third = ICK_Identity;
2862 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2863 ICS.Standard.setToType(0, T2);
2864 ICS.Standard.setToType(1, T1);
2865 ICS.Standard.setToType(2, T1);
2866 ICS.Standard.ReferenceBinding = true;
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002867 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002868 ICS.Standard.RRefBinding = isRValRef;
2869 ICS.Standard.CopyConstructor = 0;
2870 return ICS;
2871 }
2872
2873 // -- Otherwise, a temporary of type "cv1 T1" is created and
2874 // initialized from the initializer expression using the
2875 // rules for a non-reference copy initialization (8.5). The
2876 // reference is then bound to the temporary. If T1 is
2877 // reference-related to T2, cv1 must be the same
2878 // cv-qualification as, or greater cv-qualification than,
2879 // cv2; otherwise, the program is ill-formed.
2880 if (RefRelationship == Sema::Ref_Related) {
2881 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2882 // we would be reference-compatible or reference-compatible with
2883 // added qualification. But that wasn't the case, so the reference
2884 // initialization fails.
2885 return ICS;
2886 }
2887
2888 // If at least one of the types is a class type, the types are not
2889 // related, and we aren't allowed any user conversions, the
2890 // reference binding fails. This case is important for breaking
2891 // recursion, since TryImplicitConversion below will attempt to
2892 // create a temporary through the use of a copy constructor.
2893 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2894 (T1->isRecordType() || T2->isRecordType()))
2895 return ICS;
2896
2897 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00002898 // When a parameter of reference type is not bound directly to
2899 // an argument expression, the conversion sequence is the one
2900 // required to convert the argument expression to the
2901 // underlying type of the reference according to
2902 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2903 // to copy-initializing a temporary of the underlying type with
2904 // the argument expression. Any difference in top-level
2905 // cv-qualification is subsumed by the initialization itself
2906 // and does not constitute a conversion.
2907 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2908 /*AllowExplicit=*/false,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002909 /*InOverloadResolution=*/false);
2910
2911 // Of course, that's still a reference binding.
2912 if (ICS.isStandard()) {
2913 ICS.Standard.ReferenceBinding = true;
2914 ICS.Standard.RRefBinding = isRValRef;
2915 } else if (ICS.isUserDefined()) {
2916 ICS.UserDefined.After.ReferenceBinding = true;
2917 ICS.UserDefined.After.RRefBinding = isRValRef;
2918 }
2919 return ICS;
2920}
2921
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002922/// TryCopyInitialization - Try to copy-initialize a value of type
2923/// ToType from the expression From. Return the implicit conversion
2924/// sequence required to pass this argument, which may be a bad
2925/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002926/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00002927/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00002928static ImplicitConversionSequence
2929TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00002930 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002931 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002932 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00002933 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002934 /*FIXME:*/From->getLocStart(),
2935 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002936 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002937
Douglas Gregor74eb6582010-04-16 17:51:22 +00002938 return S.TryImplicitConversion(From, ToType,
2939 SuppressUserConversions,
2940 /*AllowExplicit=*/false,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002941 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002942}
2943
Douglas Gregor96176b32008-11-18 23:14:02 +00002944/// TryObjectArgumentInitialization - Try to initialize the object
2945/// parameter of the given member function (@c Method) from the
2946/// expression @p From.
2947ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002948Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002949 CXXMethodDecl *Method,
2950 CXXRecordDecl *ActingContext) {
2951 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002952 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2953 // const volatile object.
2954 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2955 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2956 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002957
2958 // Set up the conversion sequence as a "bad" conversion, to allow us
2959 // to exit early.
2960 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002961
2962 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002963 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002964 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002965 FromType = PT->getPointeeType();
2966
2967 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002968
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002969 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002970 // where X is the class of which the function is a member
2971 // (C++ [over.match.funcs]p4). However, when finding an implicit
2972 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002973 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002974 // (C++ [over.match.funcs]p5). We perform a simplified version of
2975 // reference binding here, that allows class rvalues to bind to
2976 // non-constant references.
2977
2978 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2979 // with the implicit object parameter (C++ [over.match.funcs]p5).
2980 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002981 if (ImplicitParamType.getCVRQualifiers()
2982 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002983 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002984 ICS.setBad(BadConversionSequence::bad_qualifiers,
2985 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002986 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002987 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002988
2989 // Check that we have either the same type or a derived type. It
2990 // affects the conversion rank.
2991 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002992 ImplicitConversionKind SecondKind;
2993 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2994 SecondKind = ICK_Identity;
2995 } else if (IsDerivedFrom(FromType, ClassType))
2996 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002997 else {
John McCallb1bdc622010-02-25 01:37:24 +00002998 ICS.setBad(BadConversionSequence::unrelated_class,
2999 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003000 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003001 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003002
3003 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003004 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003005 ICS.Standard.setAsIdentityConversion();
3006 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003007 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003008 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003009 ICS.Standard.ReferenceBinding = true;
3010 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003011 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003012 return ICS;
3013}
3014
3015/// PerformObjectArgumentInitialization - Perform initialization of
3016/// the implicit object parameter for the given Method with the given
3017/// expression.
3018bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003019Sema::PerformObjectArgumentInitialization(Expr *&From,
3020 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003021 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003022 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003023 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003024 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003025 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Ted Kremenek6217b802009-07-29 21:53:49 +00003027 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003028 FromRecordType = PT->getPointeeType();
3029 DestType = Method->getThisType(Context);
3030 } else {
3031 FromRecordType = From->getType();
3032 DestType = ImplicitParamRecordType;
3033 }
3034
John McCall701c89e2009-12-03 04:06:58 +00003035 // Note that we always use the true parent context when performing
3036 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003037 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00003038 = TryObjectArgumentInitialization(From->getType(), Method,
3039 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003040 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003041 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003042 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003043 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Douglas Gregor5fccd362010-03-03 23:55:11 +00003045 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003046 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003047
Douglas Gregor5fccd362010-03-03 23:55:11 +00003048 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003049 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +00003050 From->getType()->isPointerType() ?
3051 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003052 return false;
3053}
3054
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003055/// TryContextuallyConvertToBool - Attempt to contextually convert the
3056/// expression From to bool (C++0x [conv]p3).
3057ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003058 // FIXME: This is pretty broken.
Mike Stump1eb44332009-09-09 15:08:12 +00003059 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003060 // FIXME: Are these flags correct?
3061 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003062 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003063 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003064}
3065
3066/// PerformContextuallyConvertToBool - Perform a contextual conversion
3067/// of the expression From to bool (C++0x [conv]p3).
3068bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3069 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00003070 if (!ICS.isBad())
3071 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003072
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003073 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003074 return Diag(From->getSourceRange().getBegin(),
3075 diag::err_typecheck_bool_condition)
3076 << From->getType() << From->getSourceRange();
3077 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003078}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003079
3080/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3081/// expression From to 'id'.
3082ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003083 QualType Ty = Context.getObjCIdType();
3084 return TryImplicitConversion(From, Ty,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003085 // FIXME: Are these flags correct?
3086 /*SuppressUserConversions=*/false,
3087 /*AllowExplicit=*/true,
3088 /*InOverloadResolution=*/false);
3089}
3090
3091/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3092/// of the expression From to 'id'.
3093bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003094 QualType Ty = Context.getObjCIdType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003095 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3096 if (!ICS.isBad())
3097 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3098 return true;
3099}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003100
Douglas Gregorc30614b2010-06-29 23:17:37 +00003101/// \brief Attempt to convert the given expression to an integral or
3102/// enumeration type.
3103///
3104/// This routine will attempt to convert an expression of class type to an
3105/// integral or enumeration type, if that class type only has a single
3106/// conversion to an integral or enumeration type.
3107///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003108/// \param Loc The source location of the construct that requires the
3109/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003110///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003111/// \param FromE The expression we're converting from.
3112///
3113/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3114/// have integral or enumeration type.
3115///
3116/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3117/// incomplete class type.
3118///
3119/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3120/// explicit conversion function (because no implicit conversion functions
3121/// were available). This is a recovery mode.
3122///
3123/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3124/// showing which conversion was picked.
3125///
3126/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3127/// conversion function that could convert to integral or enumeration type.
3128///
3129/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3130/// usable conversion function.
3131///
3132/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3133/// function, which may be an extension in this case.
3134///
3135/// \returns The expression, converted to an integral or enumeration type if
3136/// successful.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003137Sema::OwningExprResult
3138Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3139 const PartialDiagnostic &NotIntDiag,
3140 const PartialDiagnostic &IncompleteDiag,
3141 const PartialDiagnostic &ExplicitConvDiag,
3142 const PartialDiagnostic &ExplicitConvNote,
3143 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003144 const PartialDiagnostic &AmbigNote,
3145 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003146 Expr *From = static_cast<Expr *>(FromE.get());
3147
3148 // We can't perform any more checking for type-dependent expressions.
3149 if (From->isTypeDependent())
3150 return move(FromE);
3151
3152 // If the expression already has integral or enumeration type, we're golden.
3153 QualType T = From->getType();
3154 if (T->isIntegralOrEnumerationType())
3155 return move(FromE);
3156
3157 // FIXME: Check for missing '()' if T is a function type?
3158
3159 // If we don't have a class type in C++, there's no way we can get an
3160 // expression of integral or enumeration type.
3161 const RecordType *RecordTy = T->getAs<RecordType>();
3162 if (!RecordTy || !getLangOptions().CPlusPlus) {
3163 Diag(Loc, NotIntDiag)
3164 << T << From->getSourceRange();
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003165 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003166 }
3167
3168 // We must have a complete class type.
3169 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003170 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003171
3172 // Look for a conversion to an integral or enumeration type.
3173 UnresolvedSet<4> ViableConversions;
3174 UnresolvedSet<4> ExplicitConversions;
3175 const UnresolvedSetImpl *Conversions
3176 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3177
3178 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3179 E = Conversions->end();
3180 I != E;
3181 ++I) {
3182 if (CXXConversionDecl *Conversion
3183 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3184 if (Conversion->getConversionType().getNonReferenceType()
3185 ->isIntegralOrEnumerationType()) {
3186 if (Conversion->isExplicit())
3187 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3188 else
3189 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3190 }
3191 }
3192
3193 switch (ViableConversions.size()) {
3194 case 0:
3195 if (ExplicitConversions.size() == 1) {
3196 DeclAccessPair Found = ExplicitConversions[0];
3197 CXXConversionDecl *Conversion
3198 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3199
3200 // The user probably meant to invoke the given explicit
3201 // conversion; use it.
3202 QualType ConvTy
3203 = Conversion->getConversionType().getNonReferenceType();
3204 std::string TypeStr;
3205 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3206
3207 Diag(Loc, ExplicitConvDiag)
3208 << T << ConvTy
3209 << FixItHint::CreateInsertion(From->getLocStart(),
3210 "static_cast<" + TypeStr + ">(")
3211 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3212 ")");
3213 Diag(Conversion->getLocation(), ExplicitConvNote)
3214 << ConvTy->isEnumeralType() << ConvTy;
3215
3216 // If we aren't in a SFINAE context, build a call to the
3217 // explicit conversion function.
3218 if (isSFINAEContext())
3219 return ExprError();
3220
3221 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3222 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3223 FromE = Owned(From);
3224 }
3225
3226 // We'll complain below about a non-integral condition type.
3227 break;
3228
3229 case 1: {
3230 // Apply this conversion.
3231 DeclAccessPair Found = ViableConversions[0];
3232 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003233
3234 CXXConversionDecl *Conversion
3235 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3236 QualType ConvTy
3237 = Conversion->getConversionType().getNonReferenceType();
3238 if (ConvDiag.getDiagID()) {
3239 if (isSFINAEContext())
3240 return ExprError();
3241
3242 Diag(Loc, ConvDiag)
3243 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3244 }
3245
Douglas Gregorc30614b2010-06-29 23:17:37 +00003246 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3247 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3248 FromE = Owned(From);
3249 break;
3250 }
3251
3252 default:
3253 Diag(Loc, AmbigDiag)
3254 << T << From->getSourceRange();
3255 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3256 CXXConversionDecl *Conv
3257 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3258 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3259 Diag(Conv->getLocation(), AmbigNote)
3260 << ConvTy->isEnumeralType() << ConvTy;
3261 }
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003262 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003263 }
3264
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003265 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003266 Diag(Loc, NotIntDiag)
3267 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003268
3269 return move(FromE);
3270}
3271
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003272/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003273/// candidate functions, using the given function call arguments. If
3274/// @p SuppressUserConversions, then don't allow user-defined
3275/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003276///
3277/// \para PartialOverloading true if we are performing "partial" overloading
3278/// based on an incomplete set of function arguments. This feature is used by
3279/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003280void
3281Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003282 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003283 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003284 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003285 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003286 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003287 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003288 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003289 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003290 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003291 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003292
Douglas Gregor88a35142008-12-22 05:46:06 +00003293 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003294 if (!isa<CXXConstructorDecl>(Method)) {
3295 // If we get here, it's because we're calling a member function
3296 // that is named without a member access expression (e.g.,
3297 // "this->f") that was either written explicitly or created
3298 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003299 // function, e.g., X::f(). We use an empty type for the implied
3300 // object argument (C++ [over.call.func]p3), and the acting context
3301 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003302 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003303 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003304 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003305 return;
3306 }
3307 // We treat a constructor like a non-member function, since its object
3308 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003309 }
3310
Douglas Gregorfd476482009-11-13 23:59:09 +00003311 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003312 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003313
Douglas Gregor7edfb692009-11-23 12:27:39 +00003314 // Overload resolution is always an unevaluated context.
3315 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3316
Douglas Gregor66724ea2009-11-14 01:20:54 +00003317 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3318 // C++ [class.copy]p3:
3319 // A member function template is never instantiated to perform the copy
3320 // of a class object to an object of its class type.
3321 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3322 if (NumArgs == 1 &&
3323 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003324 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3325 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003326 return;
3327 }
3328
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003329 // Add this candidate
3330 CandidateSet.push_back(OverloadCandidate());
3331 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003332 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003333 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003334 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003335 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003336 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003337
3338 unsigned NumArgsInProto = Proto->getNumArgs();
3339
3340 // (C++ 13.3.2p2): A candidate function having fewer than m
3341 // parameters is viable only if it has an ellipsis in its parameter
3342 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003343 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3344 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003345 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003346 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003347 return;
3348 }
3349
3350 // (C++ 13.3.2p2): A candidate function having more than m parameters
3351 // is viable only if the (m+1)st parameter has a default argument
3352 // (8.3.6). For the purposes of overload resolution, the
3353 // parameter list is truncated on the right, so that there are
3354 // exactly m parameters.
3355 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003356 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003357 // Not enough arguments.
3358 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003359 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003360 return;
3361 }
3362
3363 // Determine the implicit conversion sequences for each of the
3364 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003365 Candidate.Conversions.resize(NumArgs);
3366 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3367 if (ArgIdx < NumArgsInProto) {
3368 // (C++ 13.3.2p3): for F to be a viable function, there shall
3369 // exist for each argument an implicit conversion sequence
3370 // (13.3.3.1) that converts that argument to the corresponding
3371 // parameter of F.
3372 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003373 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003374 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003375 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003376 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003377 if (Candidate.Conversions[ArgIdx].isBad()) {
3378 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003379 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003380 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003381 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003382 } else {
3383 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3384 // argument for which there is no corresponding parameter is
3385 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003386 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003387 }
3388 }
3389}
3390
Douglas Gregor063daf62009-03-13 18:40:31 +00003391/// \brief Add all of the function declarations in the given function set to
3392/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003393void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003394 Expr **Args, unsigned NumArgs,
3395 OverloadCandidateSet& CandidateSet,
3396 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003397 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003398 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3399 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003400 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003401 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003402 cast<CXXMethodDecl>(FD)->getParent(),
3403 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003404 CandidateSet, SuppressUserConversions);
3405 else
John McCall9aa472c2010-03-19 07:35:19 +00003406 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003407 SuppressUserConversions);
3408 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003409 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003410 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3411 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003412 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003413 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003414 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003415 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003416 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003417 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003418 else
John McCall9aa472c2010-03-19 07:35:19 +00003419 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003420 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003421 Args, NumArgs, CandidateSet,
3422 SuppressUserConversions);
3423 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003424 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003425}
3426
John McCall314be4e2009-11-17 07:50:12 +00003427/// AddMethodCandidate - Adds a named decl (which is some kind of
3428/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003429void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003430 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003431 Expr **Args, unsigned NumArgs,
3432 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003433 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003434 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003435 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003436
3437 if (isa<UsingShadowDecl>(Decl))
3438 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3439
3440 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3441 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3442 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003443 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3444 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003445 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003446 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003447 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003448 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003449 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003450 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003451 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003452 }
3453}
3454
Douglas Gregor96176b32008-11-18 23:14:02 +00003455/// AddMethodCandidate - Adds the given C++ member function to the set
3456/// of candidate functions, using the given function call arguments
3457/// and the object argument (@c Object). For example, in a call
3458/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3459/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3460/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003461/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003462void
John McCall9aa472c2010-03-19 07:35:19 +00003463Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003464 CXXRecordDecl *ActingContext, QualType ObjectType,
3465 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003466 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003467 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003468 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003469 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003470 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003471 assert(!isa<CXXConstructorDecl>(Method) &&
3472 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003473
Douglas Gregor3f396022009-09-28 04:47:19 +00003474 if (!CandidateSet.isNewCandidate(Method))
3475 return;
3476
Douglas Gregor7edfb692009-11-23 12:27:39 +00003477 // Overload resolution is always an unevaluated context.
3478 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3479
Douglas Gregor96176b32008-11-18 23:14:02 +00003480 // Add this candidate
3481 CandidateSet.push_back(OverloadCandidate());
3482 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003483 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003484 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003485 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003486 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003487
3488 unsigned NumArgsInProto = Proto->getNumArgs();
3489
3490 // (C++ 13.3.2p2): A candidate function having fewer than m
3491 // parameters is viable only if it has an ellipsis in its parameter
3492 // list (8.3.5).
3493 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3494 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003495 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003496 return;
3497 }
3498
3499 // (C++ 13.3.2p2): A candidate function having more than m parameters
3500 // is viable only if the (m+1)st parameter has a default argument
3501 // (8.3.6). For the purposes of overload resolution, the
3502 // parameter list is truncated on the right, so that there are
3503 // exactly m parameters.
3504 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3505 if (NumArgs < MinRequiredArgs) {
3506 // Not enough arguments.
3507 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003508 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003509 return;
3510 }
3511
3512 Candidate.Viable = true;
3513 Candidate.Conversions.resize(NumArgs + 1);
3514
John McCall701c89e2009-12-03 04:06:58 +00003515 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003516 // The implicit object argument is ignored.
3517 Candidate.IgnoreObjectArgument = true;
3518 else {
3519 // Determine the implicit conversion sequence for the object
3520 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003521 Candidate.Conversions[0]
3522 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003523 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003524 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003525 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003526 return;
3527 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003528 }
3529
3530 // Determine the implicit conversion sequences for each of the
3531 // arguments.
3532 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3533 if (ArgIdx < NumArgsInProto) {
3534 // (C++ 13.3.2p3): for F to be a viable function, there shall
3535 // exist for each argument an implicit conversion sequence
3536 // (13.3.3.1) that converts that argument to the corresponding
3537 // parameter of F.
3538 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003539 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003540 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003541 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003542 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003543 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003544 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003545 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003546 break;
3547 }
3548 } else {
3549 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3550 // argument for which there is no corresponding parameter is
3551 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003552 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003553 }
3554 }
3555}
Douglas Gregora9333192010-05-08 17:41:32 +00003556
Douglas Gregor6b906862009-08-21 00:16:32 +00003557/// \brief Add a C++ member function template as a candidate to the candidate
3558/// set, using template argument deduction to produce an appropriate member
3559/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003560void
Douglas Gregor6b906862009-08-21 00:16:32 +00003561Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003562 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003563 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003564 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003565 QualType ObjectType,
3566 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003567 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003568 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003569 if (!CandidateSet.isNewCandidate(MethodTmpl))
3570 return;
3571
Douglas Gregor6b906862009-08-21 00:16:32 +00003572 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003573 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003574 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003575 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003576 // candidate functions in the usual way.113) A given name can refer to one
3577 // or more function templates and also to a set of overloaded non-template
3578 // functions. In such a case, the candidate functions generated from each
3579 // function template are combined with the set of non-template candidate
3580 // functions.
John McCall5769d612010-02-08 23:07:23 +00003581 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003582 FunctionDecl *Specialization = 0;
3583 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003584 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003585 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003586 CandidateSet.push_back(OverloadCandidate());
3587 OverloadCandidate &Candidate = CandidateSet.back();
3588 Candidate.FoundDecl = FoundDecl;
3589 Candidate.Function = MethodTmpl->getTemplatedDecl();
3590 Candidate.Viable = false;
3591 Candidate.FailureKind = ovl_fail_bad_deduction;
3592 Candidate.IsSurrogate = false;
3593 Candidate.IgnoreObjectArgument = false;
3594 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3595 Info);
3596 return;
3597 }
Mike Stump1eb44332009-09-09 15:08:12 +00003598
Douglas Gregor6b906862009-08-21 00:16:32 +00003599 // Add the function template specialization produced by template argument
3600 // deduction as a candidate.
3601 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003602 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003603 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003604 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003605 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003606 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003607}
3608
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003609/// \brief Add a C++ function template specialization as a candidate
3610/// in the candidate set, using template argument deduction to produce
3611/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003612void
Douglas Gregore53060f2009-06-25 22:08:12 +00003613Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003614 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003615 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003616 Expr **Args, unsigned NumArgs,
3617 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003618 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003619 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3620 return;
3621
Douglas Gregore53060f2009-06-25 22:08:12 +00003622 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003623 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003624 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003625 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003626 // candidate functions in the usual way.113) A given name can refer to one
3627 // or more function templates and also to a set of overloaded non-template
3628 // functions. In such a case, the candidate functions generated from each
3629 // function template are combined with the set of non-template candidate
3630 // functions.
John McCall5769d612010-02-08 23:07:23 +00003631 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003632 FunctionDecl *Specialization = 0;
3633 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003634 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003635 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003636 CandidateSet.push_back(OverloadCandidate());
3637 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003638 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003639 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3640 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003641 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003642 Candidate.IsSurrogate = false;
3643 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003644 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3645 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003646 return;
3647 }
Mike Stump1eb44332009-09-09 15:08:12 +00003648
Douglas Gregore53060f2009-06-25 22:08:12 +00003649 // Add the function template specialization produced by template argument
3650 // deduction as a candidate.
3651 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003652 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003653 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003654}
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003656/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003657/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003658/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003659/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003660/// (which may or may not be the same type as the type that the
3661/// conversion function produces).
3662void
3663Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003664 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003665 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003666 Expr *From, QualType ToType,
3667 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003668 assert(!Conversion->getDescribedFunctionTemplate() &&
3669 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003670 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003671 if (!CandidateSet.isNewCandidate(Conversion))
3672 return;
3673
Douglas Gregor7edfb692009-11-23 12:27:39 +00003674 // Overload resolution is always an unevaluated context.
3675 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3676
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003677 // Add this candidate
3678 CandidateSet.push_back(OverloadCandidate());
3679 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003680 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003681 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003682 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003683 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003684 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003685 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003686 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003687
Douglas Gregor96176b32008-11-18 23:14:02 +00003688 // Determine the implicit conversion sequence for the implicit
3689 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003690 Candidate.Viable = true;
3691 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00003692 Candidate.Conversions[0]
3693 = TryObjectArgumentInitialization(From->getType(), Conversion,
3694 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003695 // Conversion functions to a different type in the base class is visible in
3696 // the derived class. So, a derived to base conversion should not participate
3697 // in overload resolution.
3698 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3699 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00003700 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003701 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003702 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003703 return;
3704 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003705
3706 // We won't go through a user-define type conversion function to convert a
3707 // derived to base as such conversions are given Conversion Rank. They only
3708 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3709 QualType FromCanon
3710 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3711 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3712 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3713 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003714 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003715 return;
3716 }
3717
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003718 // To determine what the conversion from the result of calling the
3719 // conversion function to the type we're eventually trying to
3720 // convert to (ToType), we need to synthesize a call to the
3721 // conversion function and attempt copy initialization from it. This
3722 // makes sure that we get the right semantics with respect to
3723 // lvalues/rvalues and the type. Fortunately, we can allocate this
3724 // call on the stack and we don't need its arguments to be
3725 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003726 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003727 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003728 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3729 Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003730 CastExpr::CK_FunctionToPointerDecay,
John McCallf871d0c2010-08-07 06:22:56 +00003731 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003732
3733 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003734 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3735 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003736 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003737 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003738 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003739 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003740 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003741 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003742 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003743
John McCall1d318332010-01-12 00:44:57 +00003744 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003745 case ImplicitConversionSequence::StandardConversion:
3746 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003747
3748 // C++ [over.ics.user]p3:
3749 // If the user-defined conversion is specified by a specialization of a
3750 // conversion function template, the second standard conversion sequence
3751 // shall have exact match rank.
3752 if (Conversion->getPrimaryTemplate() &&
3753 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3754 Candidate.Viable = false;
3755 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3756 }
3757
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003758 break;
3759
3760 case ImplicitConversionSequence::BadConversion:
3761 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003762 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003763 break;
3764
3765 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003766 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003767 "Can only end up with a standard conversion sequence or failure");
3768 }
3769}
3770
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003771/// \brief Adds a conversion function template specialization
3772/// candidate to the overload set, using template argument deduction
3773/// to deduce the template arguments of the conversion function
3774/// template from the type that we are converting to (C++
3775/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003776void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003777Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003778 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003779 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003780 Expr *From, QualType ToType,
3781 OverloadCandidateSet &CandidateSet) {
3782 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3783 "Only conversion function templates permitted here");
3784
Douglas Gregor3f396022009-09-28 04:47:19 +00003785 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3786 return;
3787
John McCall5769d612010-02-08 23:07:23 +00003788 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003789 CXXConversionDecl *Specialization = 0;
3790 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003791 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003792 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003793 CandidateSet.push_back(OverloadCandidate());
3794 OverloadCandidate &Candidate = CandidateSet.back();
3795 Candidate.FoundDecl = FoundDecl;
3796 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3797 Candidate.Viable = false;
3798 Candidate.FailureKind = ovl_fail_bad_deduction;
3799 Candidate.IsSurrogate = false;
3800 Candidate.IgnoreObjectArgument = false;
3801 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3802 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003803 return;
3804 }
Mike Stump1eb44332009-09-09 15:08:12 +00003805
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003806 // Add the conversion function template specialization produced by
3807 // template argument deduction as a candidate.
3808 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003809 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003810 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003811}
3812
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003813/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3814/// converts the given @c Object to a function pointer via the
3815/// conversion function @c Conversion, and then attempts to call it
3816/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3817/// the type of function that we'll eventually be calling.
3818void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003819 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003820 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003821 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003822 QualType ObjectType,
3823 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003824 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003825 if (!CandidateSet.isNewCandidate(Conversion))
3826 return;
3827
Douglas Gregor7edfb692009-11-23 12:27:39 +00003828 // Overload resolution is always an unevaluated context.
3829 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3830
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003831 CandidateSet.push_back(OverloadCandidate());
3832 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003833 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003834 Candidate.Function = 0;
3835 Candidate.Surrogate = Conversion;
3836 Candidate.Viable = true;
3837 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003838 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003839 Candidate.Conversions.resize(NumArgs + 1);
3840
3841 // Determine the implicit conversion sequence for the implicit
3842 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003843 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003844 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003845 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003846 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003847 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003848 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003849 return;
3850 }
3851
3852 // The first conversion is actually a user-defined conversion whose
3853 // first conversion is ObjectInit's standard conversion (which is
3854 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003855 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003856 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003857 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003858 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003859 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003860 = Candidate.Conversions[0].UserDefined.Before;
3861 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3862
Mike Stump1eb44332009-09-09 15:08:12 +00003863 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003864 unsigned NumArgsInProto = Proto->getNumArgs();
3865
3866 // (C++ 13.3.2p2): A candidate function having fewer than m
3867 // parameters is viable only if it has an ellipsis in its parameter
3868 // list (8.3.5).
3869 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3870 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003871 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003872 return;
3873 }
3874
3875 // Function types don't have any default arguments, so just check if
3876 // we have enough arguments.
3877 if (NumArgs < NumArgsInProto) {
3878 // Not enough arguments.
3879 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003880 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003881 return;
3882 }
3883
3884 // Determine the implicit conversion sequences for each of the
3885 // arguments.
3886 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3887 if (ArgIdx < NumArgsInProto) {
3888 // (C++ 13.3.2p3): for F to be a viable function, there shall
3889 // exist for each argument an implicit conversion sequence
3890 // (13.3.3.1) that converts that argument to the corresponding
3891 // parameter of F.
3892 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003893 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003894 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003895 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003896 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003897 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003898 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003899 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003900 break;
3901 }
3902 } else {
3903 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3904 // argument for which there is no corresponding parameter is
3905 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003906 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003907 }
3908 }
3909}
3910
Douglas Gregor063daf62009-03-13 18:40:31 +00003911/// \brief Add overload candidates for overloaded operators that are
3912/// member functions.
3913///
3914/// Add the overloaded operator candidates that are member functions
3915/// for the operator Op that was used in an operator expression such
3916/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3917/// CandidateSet will store the added overload candidates. (C++
3918/// [over.match.oper]).
3919void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3920 SourceLocation OpLoc,
3921 Expr **Args, unsigned NumArgs,
3922 OverloadCandidateSet& CandidateSet,
3923 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003924 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3925
3926 // C++ [over.match.oper]p3:
3927 // For a unary operator @ with an operand of a type whose
3928 // cv-unqualified version is T1, and for a binary operator @ with
3929 // a left operand of a type whose cv-unqualified version is T1 and
3930 // a right operand of a type whose cv-unqualified version is T2,
3931 // three sets of candidate functions, designated member
3932 // candidates, non-member candidates and built-in candidates, are
3933 // constructed as follows:
3934 QualType T1 = Args[0]->getType();
3935 QualType T2;
3936 if (NumArgs > 1)
3937 T2 = Args[1]->getType();
3938
3939 // -- If T1 is a class type, the set of member candidates is the
3940 // result of the qualified lookup of T1::operator@
3941 // (13.3.1.1.1); otherwise, the set of member candidates is
3942 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003943 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003944 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003945 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003946 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003947
John McCalla24dc2e2009-11-17 02:14:36 +00003948 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3949 LookupQualifiedName(Operators, T1Rec->getDecl());
3950 Operators.suppressDiagnostics();
3951
Mike Stump1eb44332009-09-09 15:08:12 +00003952 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003953 OperEnd = Operators.end();
3954 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003955 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003956 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003957 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003958 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003959 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003960}
3961
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003962/// AddBuiltinCandidate - Add a candidate for a built-in
3963/// operator. ResultTy and ParamTys are the result and parameter types
3964/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003965/// arguments being passed to the candidate. IsAssignmentOperator
3966/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003967/// operator. NumContextualBoolArguments is the number of arguments
3968/// (at the beginning of the argument list) that will be contextually
3969/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003970void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003971 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003972 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003973 bool IsAssignmentOperator,
3974 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003975 // Overload resolution is always an unevaluated context.
3976 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3977
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003978 // Add this candidate
3979 CandidateSet.push_back(OverloadCandidate());
3980 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003981 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003982 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003983 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003984 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003985 Candidate.BuiltinTypes.ResultTy = ResultTy;
3986 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3987 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3988
3989 // Determine the implicit conversion sequences for each of the
3990 // arguments.
3991 Candidate.Viable = true;
3992 Candidate.Conversions.resize(NumArgs);
3993 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003994 // C++ [over.match.oper]p4:
3995 // For the built-in assignment operators, conversions of the
3996 // left operand are restricted as follows:
3997 // -- no temporaries are introduced to hold the left operand, and
3998 // -- no user-defined conversions are applied to the left
3999 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004000 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004001 //
4002 // We block these conversions by turning off user-defined
4003 // conversions, since that is the only way that initialization of
4004 // a reference to a non-class type can occur from something that
4005 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004006 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004007 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004008 "Contextual conversion to bool requires bool type");
4009 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4010 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004011 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004012 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004013 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004014 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004015 }
John McCall1d318332010-01-12 00:44:57 +00004016 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004017 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004018 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004019 break;
4020 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004021 }
4022}
4023
4024/// BuiltinCandidateTypeSet - A set of types that will be used for the
4025/// candidate operator functions for built-in operators (C++
4026/// [over.built]). The types are separated into pointer types and
4027/// enumeration types.
4028class BuiltinCandidateTypeSet {
4029 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004030 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004031
4032 /// PointerTypes - The set of pointer types that will be used in the
4033 /// built-in candidates.
4034 TypeSet PointerTypes;
4035
Sebastian Redl78eb8742009-04-19 21:53:20 +00004036 /// MemberPointerTypes - The set of member pointer types that will be
4037 /// used in the built-in candidates.
4038 TypeSet MemberPointerTypes;
4039
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004040 /// EnumerationTypes - The set of enumeration types that will be
4041 /// used in the built-in candidates.
4042 TypeSet EnumerationTypes;
4043
Douglas Gregor26bcf672010-05-19 03:21:00 +00004044 /// \brief The set of vector types that will be used in the built-in
4045 /// candidates.
4046 TypeSet VectorTypes;
4047
Douglas Gregor5842ba92009-08-24 15:23:48 +00004048 /// Sema - The semantic analysis instance where we are building the
4049 /// candidate type set.
4050 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004052 /// Context - The AST context in which we will build the type sets.
4053 ASTContext &Context;
4054
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004055 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4056 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004057 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004058
4059public:
4060 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004061 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004062
Mike Stump1eb44332009-09-09 15:08:12 +00004063 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004064 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004065
Douglas Gregor573d9c32009-10-21 23:19:44 +00004066 void AddTypesConvertedFrom(QualType Ty,
4067 SourceLocation Loc,
4068 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004069 bool AllowExplicitConversions,
4070 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004071
4072 /// pointer_begin - First pointer type found;
4073 iterator pointer_begin() { return PointerTypes.begin(); }
4074
Sebastian Redl78eb8742009-04-19 21:53:20 +00004075 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004076 iterator pointer_end() { return PointerTypes.end(); }
4077
Sebastian Redl78eb8742009-04-19 21:53:20 +00004078 /// member_pointer_begin - First member pointer type found;
4079 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4080
4081 /// member_pointer_end - Past the last member pointer type found;
4082 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4083
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004084 /// enumeration_begin - First enumeration type found;
4085 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4086
Sebastian Redl78eb8742009-04-19 21:53:20 +00004087 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004088 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004089
4090 iterator vector_begin() { return VectorTypes.begin(); }
4091 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004092};
4093
Sebastian Redl78eb8742009-04-19 21:53:20 +00004094/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004095/// the set of pointer types along with any more-qualified variants of
4096/// that type. For example, if @p Ty is "int const *", this routine
4097/// will add "int const *", "int const volatile *", "int const
4098/// restrict *", and "int const volatile restrict *" to the set of
4099/// pointer types. Returns true if the add of @p Ty itself succeeded,
4100/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004101///
4102/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004103bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004104BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4105 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004106
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004107 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004108 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004109 return false;
4110
John McCall0953e762009-09-24 19:53:00 +00004111 const PointerType *PointerTy = Ty->getAs<PointerType>();
4112 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004113
John McCall0953e762009-09-24 19:53:00 +00004114 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004115 // Don't add qualified variants of arrays. For one, they're not allowed
4116 // (the qualifier would sink to the element type), and for another, the
4117 // only overload situation where it matters is subscript or pointer +- int,
4118 // and those shouldn't have qualifier variants anyway.
4119 if (PointeeTy->isArrayType())
4120 return true;
John McCall0953e762009-09-24 19:53:00 +00004121 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004122 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004123 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004124 bool hasVolatile = VisibleQuals.hasVolatile();
4125 bool hasRestrict = VisibleQuals.hasRestrict();
4126
John McCall0953e762009-09-24 19:53:00 +00004127 // Iterate through all strict supersets of BaseCVR.
4128 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4129 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004130 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4131 // in the types.
4132 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4133 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004134 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4135 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004136 }
4137
4138 return true;
4139}
4140
Sebastian Redl78eb8742009-04-19 21:53:20 +00004141/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4142/// to the set of pointer types along with any more-qualified variants of
4143/// that type. For example, if @p Ty is "int const *", this routine
4144/// will add "int const *", "int const volatile *", "int const
4145/// restrict *", and "int const volatile restrict *" to the set of
4146/// pointer types. Returns true if the add of @p Ty itself succeeded,
4147/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004148///
4149/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004150bool
4151BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4152 QualType Ty) {
4153 // Insert this type.
4154 if (!MemberPointerTypes.insert(Ty))
4155 return false;
4156
John McCall0953e762009-09-24 19:53:00 +00004157 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4158 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004159
John McCall0953e762009-09-24 19:53:00 +00004160 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004161 // Don't add qualified variants of arrays. For one, they're not allowed
4162 // (the qualifier would sink to the element type), and for another, the
4163 // only overload situation where it matters is subscript or pointer +- int,
4164 // and those shouldn't have qualifier variants anyway.
4165 if (PointeeTy->isArrayType())
4166 return true;
John McCall0953e762009-09-24 19:53:00 +00004167 const Type *ClassTy = PointerTy->getClass();
4168
4169 // Iterate through all strict supersets of the pointee type's CVR
4170 // qualifiers.
4171 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4172 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4173 if ((CVR | BaseCVR) != CVR) continue;
4174
4175 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4176 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004177 }
4178
4179 return true;
4180}
4181
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004182/// AddTypesConvertedFrom - Add each of the types to which the type @p
4183/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004184/// primarily interested in pointer types and enumeration types. We also
4185/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004186/// AllowUserConversions is true if we should look at the conversion
4187/// functions of a class type, and AllowExplicitConversions if we
4188/// should also include the explicit conversion functions of a class
4189/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004190void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004191BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004192 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004193 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004194 bool AllowExplicitConversions,
4195 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004196 // Only deal with canonical types.
4197 Ty = Context.getCanonicalType(Ty);
4198
4199 // Look through reference types; they aren't part of the type of an
4200 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004201 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004202 Ty = RefTy->getPointeeType();
4203
4204 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004205 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004206
Sebastian Redla65b5512009-11-05 16:36:20 +00004207 // If we're dealing with an array type, decay to the pointer.
4208 if (Ty->isArrayType())
4209 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4210
Ted Kremenek6217b802009-07-29 21:53:49 +00004211 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004212 QualType PointeeTy = PointerTy->getPointeeType();
4213
4214 // Insert our type, and its more-qualified variants, into the set
4215 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004216 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004217 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004218 } else if (Ty->isMemberPointerType()) {
4219 // Member pointers are far easier, since the pointee can't be converted.
4220 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4221 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004222 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004223 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004224 } else if (Ty->isVectorType()) {
4225 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004226 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004227 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004228 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004229 // No conversion functions in incomplete types.
4230 return;
4231 }
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004233 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004234 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004235 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004236 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004237 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004238 NamedDecl *D = I.getDecl();
4239 if (isa<UsingShadowDecl>(D))
4240 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004241
Mike Stump1eb44332009-09-09 15:08:12 +00004242 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004243 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004244 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004245 continue;
4246
John McCall32daa422010-03-31 01:36:47 +00004247 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004248 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004249 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004250 VisibleQuals);
4251 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004252 }
4253 }
4254 }
4255}
4256
Douglas Gregor19b7b152009-08-24 13:43:27 +00004257/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4258/// the volatile- and non-volatile-qualified assignment operators for the
4259/// given type to the candidate set.
4260static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4261 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004262 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004263 unsigned NumArgs,
4264 OverloadCandidateSet &CandidateSet) {
4265 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Douglas Gregor19b7b152009-08-24 13:43:27 +00004267 // T& operator=(T&, T)
4268 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4269 ParamTypes[1] = T;
4270 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4271 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Douglas Gregor19b7b152009-08-24 13:43:27 +00004273 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4274 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004275 ParamTypes[0]
4276 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004277 ParamTypes[1] = T;
4278 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004279 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004280 }
4281}
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Sebastian Redl9994a342009-10-25 17:03:50 +00004283/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4284/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004285static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4286 Qualifiers VRQuals;
4287 const RecordType *TyRec;
4288 if (const MemberPointerType *RHSMPType =
4289 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004290 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004291 else
4292 TyRec = ArgExpr->getType()->getAs<RecordType>();
4293 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004294 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004295 VRQuals.addVolatile();
4296 VRQuals.addRestrict();
4297 return VRQuals;
4298 }
4299
4300 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004301 if (!ClassDecl->hasDefinition())
4302 return VRQuals;
4303
John McCalleec51cf2010-01-20 00:46:10 +00004304 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004305 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004306
John McCalleec51cf2010-01-20 00:46:10 +00004307 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004308 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004309 NamedDecl *D = I.getDecl();
4310 if (isa<UsingShadowDecl>(D))
4311 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4312 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004313 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4314 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4315 CanTy = ResTypeRef->getPointeeType();
4316 // Need to go down the pointer/mempointer chain and add qualifiers
4317 // as see them.
4318 bool done = false;
4319 while (!done) {
4320 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4321 CanTy = ResTypePtr->getPointeeType();
4322 else if (const MemberPointerType *ResTypeMPtr =
4323 CanTy->getAs<MemberPointerType>())
4324 CanTy = ResTypeMPtr->getPointeeType();
4325 else
4326 done = true;
4327 if (CanTy.isVolatileQualified())
4328 VRQuals.addVolatile();
4329 if (CanTy.isRestrictQualified())
4330 VRQuals.addRestrict();
4331 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4332 return VRQuals;
4333 }
4334 }
4335 }
4336 return VRQuals;
4337}
4338
Douglas Gregor74253732008-11-19 15:42:04 +00004339/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4340/// operator overloads to the candidate set (C++ [over.built]), based
4341/// on the operator @p Op and the arguments given. For example, if the
4342/// operator is a binary '+', this routine might add "int
4343/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004344void
Mike Stump1eb44332009-09-09 15:08:12 +00004345Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004346 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004347 Expr **Args, unsigned NumArgs,
4348 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004349 // The set of "promoted arithmetic types", which are the arithmetic
4350 // types are that preserved by promotion (C++ [over.built]p2). Note
4351 // that the first few of these types are the promoted integral
4352 // types; these types need to be first.
4353 // FIXME: What about complex?
4354 const unsigned FirstIntegralType = 0;
4355 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004356 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004357 LastPromotedIntegralType = 13;
4358 const unsigned FirstPromotedArithmeticType = 7,
4359 LastPromotedArithmeticType = 16;
4360 const unsigned NumArithmeticTypes = 16;
4361 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004362 Context.BoolTy, Context.CharTy, Context.WCharTy,
4363// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004364 Context.SignedCharTy, Context.ShortTy,
4365 Context.UnsignedCharTy, Context.UnsignedShortTy,
4366 Context.IntTy, Context.LongTy, Context.LongLongTy,
4367 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4368 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4369 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004370 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4371 "Invalid first promoted integral type");
4372 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4373 == Context.UnsignedLongLongTy &&
4374 "Invalid last promoted integral type");
4375 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4376 "Invalid first promoted arithmetic type");
4377 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4378 == Context.LongDoubleTy &&
4379 "Invalid last promoted arithmetic type");
4380
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004381 // Find all of the types that the arguments can convert to, but only
4382 // if the operator we're looking at has built-in operator candidates
4383 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004384 Qualifiers VisibleTypeConversionsQuals;
4385 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004386 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4387 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4388
Douglas Gregor5842ba92009-08-24 15:23:48 +00004389 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004390 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4391 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4392 OpLoc,
4393 true,
4394 (Op == OO_Exclaim ||
4395 Op == OO_AmpAmp ||
4396 Op == OO_PipePipe),
4397 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004398
4399 bool isComparison = false;
4400 switch (Op) {
4401 case OO_None:
4402 case NUM_OVERLOADED_OPERATORS:
4403 assert(false && "Expected an overloaded operator");
4404 break;
4405
Douglas Gregor74253732008-11-19 15:42:04 +00004406 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004407 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004408 goto UnaryStar;
4409 else
4410 goto BinaryStar;
4411 break;
4412
4413 case OO_Plus: // '+' is either unary or binary
4414 if (NumArgs == 1)
4415 goto UnaryPlus;
4416 else
4417 goto BinaryPlus;
4418 break;
4419
4420 case OO_Minus: // '-' is either unary or binary
4421 if (NumArgs == 1)
4422 goto UnaryMinus;
4423 else
4424 goto BinaryMinus;
4425 break;
4426
4427 case OO_Amp: // '&' is either unary or binary
4428 if (NumArgs == 1)
4429 goto UnaryAmp;
4430 else
4431 goto BinaryAmp;
4432
4433 case OO_PlusPlus:
4434 case OO_MinusMinus:
4435 // C++ [over.built]p3:
4436 //
4437 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4438 // is either volatile or empty, there exist candidate operator
4439 // functions of the form
4440 //
4441 // VQ T& operator++(VQ T&);
4442 // T operator++(VQ T&, int);
4443 //
4444 // C++ [over.built]p4:
4445 //
4446 // For every pair (T, VQ), where T is an arithmetic type other
4447 // than bool, and VQ is either volatile or empty, there exist
4448 // candidate operator functions of the form
4449 //
4450 // VQ T& operator--(VQ T&);
4451 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004452 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004453 Arith < NumArithmeticTypes; ++Arith) {
4454 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004455 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004456 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004457
4458 // Non-volatile version.
4459 if (NumArgs == 1)
4460 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4461 else
4462 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004463 // heuristic to reduce number of builtin candidates in the set.
4464 // Add volatile version only if there are conversions to a volatile type.
4465 if (VisibleTypeConversionsQuals.hasVolatile()) {
4466 // Volatile version
4467 ParamTypes[0]
4468 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4469 if (NumArgs == 1)
4470 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4471 else
4472 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4473 }
Douglas Gregor74253732008-11-19 15:42:04 +00004474 }
4475
4476 // C++ [over.built]p5:
4477 //
4478 // For every pair (T, VQ), where T is a cv-qualified or
4479 // cv-unqualified object type, and VQ is either volatile or
4480 // empty, there exist candidate operator functions of the form
4481 //
4482 // T*VQ& operator++(T*VQ&);
4483 // T*VQ& operator--(T*VQ&);
4484 // T* operator++(T*VQ&, int);
4485 // T* operator--(T*VQ&, int);
4486 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4487 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4488 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004489 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004490 continue;
4491
Mike Stump1eb44332009-09-09 15:08:12 +00004492 QualType ParamTypes[2] = {
4493 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004494 };
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Douglas Gregor74253732008-11-19 15:42:04 +00004496 // Without volatile
4497 if (NumArgs == 1)
4498 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4499 else
4500 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4501
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004502 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4503 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004504 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004505 ParamTypes[0]
4506 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004507 if (NumArgs == 1)
4508 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4509 else
4510 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4511 }
4512 }
4513 break;
4514
4515 UnaryStar:
4516 // C++ [over.built]p6:
4517 // For every cv-qualified or cv-unqualified object type T, there
4518 // exist candidate operator functions of the form
4519 //
4520 // T& operator*(T*);
4521 //
4522 // C++ [over.built]p7:
4523 // For every function type T, there exist candidate operator
4524 // functions of the form
4525 // T& operator*(T*);
4526 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4527 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4528 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00004529 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004530 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004531 &ParamTy, Args, 1, CandidateSet);
4532 }
4533 break;
4534
4535 UnaryPlus:
4536 // C++ [over.built]p8:
4537 // For every type T, there exist candidate operator functions of
4538 // the form
4539 //
4540 // T* operator+(T*);
4541 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4542 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4543 QualType ParamTy = *Ptr;
4544 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4545 }
Mike Stump1eb44332009-09-09 15:08:12 +00004546
Douglas Gregor74253732008-11-19 15:42:04 +00004547 // Fall through
4548
4549 UnaryMinus:
4550 // C++ [over.built]p9:
4551 // For every promoted arithmetic type T, there exist candidate
4552 // operator functions of the form
4553 //
4554 // T operator+(T);
4555 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004556 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004557 Arith < LastPromotedArithmeticType; ++Arith) {
4558 QualType ArithTy = ArithmeticTypes[Arith];
4559 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4560 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004561
4562 // Extension: We also add these operators for vector types.
4563 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4564 VecEnd = CandidateTypes.vector_end();
4565 Vec != VecEnd; ++Vec) {
4566 QualType VecTy = *Vec;
4567 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4568 }
Douglas Gregor74253732008-11-19 15:42:04 +00004569 break;
4570
4571 case OO_Tilde:
4572 // C++ [over.built]p10:
4573 // For every promoted integral type T, there exist candidate
4574 // operator functions of the form
4575 //
4576 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004577 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004578 Int < LastPromotedIntegralType; ++Int) {
4579 QualType IntTy = ArithmeticTypes[Int];
4580 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4581 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004582
4583 // Extension: We also add this operator for vector types.
4584 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4585 VecEnd = CandidateTypes.vector_end();
4586 Vec != VecEnd; ++Vec) {
4587 QualType VecTy = *Vec;
4588 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4589 }
Douglas Gregor74253732008-11-19 15:42:04 +00004590 break;
4591
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004592 case OO_New:
4593 case OO_Delete:
4594 case OO_Array_New:
4595 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004596 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004597 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004598 break;
4599
4600 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004601 UnaryAmp:
4602 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004603 // C++ [over.match.oper]p3:
4604 // -- For the operator ',', the unary operator '&', or the
4605 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004606 break;
4607
Douglas Gregor19b7b152009-08-24 13:43:27 +00004608 case OO_EqualEqual:
4609 case OO_ExclaimEqual:
4610 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004611 // For every pointer to member type T, there exist candidate operator
4612 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004613 //
4614 // bool operator==(T,T);
4615 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004616 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004617 MemPtr = CandidateTypes.member_pointer_begin(),
4618 MemPtrEnd = CandidateTypes.member_pointer_end();
4619 MemPtr != MemPtrEnd;
4620 ++MemPtr) {
4621 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4622 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4623 }
Mike Stump1eb44332009-09-09 15:08:12 +00004624
Douglas Gregor19b7b152009-08-24 13:43:27 +00004625 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004626
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004627 case OO_Less:
4628 case OO_Greater:
4629 case OO_LessEqual:
4630 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004631 // C++ [over.built]p15:
4632 //
4633 // For every pointer or enumeration type T, there exist
4634 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004635 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004636 // bool operator<(T, T);
4637 // bool operator>(T, T);
4638 // bool operator<=(T, T);
4639 // bool operator>=(T, T);
4640 // bool operator==(T, T);
4641 // bool operator!=(T, T);
4642 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4643 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4644 QualType ParamTypes[2] = { *Ptr, *Ptr };
4645 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4646 }
Mike Stump1eb44332009-09-09 15:08:12 +00004647 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004648 = CandidateTypes.enumeration_begin();
4649 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4650 QualType ParamTypes[2] = { *Enum, *Enum };
4651 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4652 }
4653
4654 // Fall through.
4655 isComparison = true;
4656
Douglas Gregor74253732008-11-19 15:42:04 +00004657 BinaryPlus:
4658 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004659 if (!isComparison) {
4660 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4661
4662 // C++ [over.built]p13:
4663 //
4664 // For every cv-qualified or cv-unqualified object type T
4665 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004666 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004667 // T* operator+(T*, ptrdiff_t);
4668 // T& operator[](T*, ptrdiff_t); [BELOW]
4669 // T* operator-(T*, ptrdiff_t);
4670 // T* operator+(ptrdiff_t, T*);
4671 // T& operator[](ptrdiff_t, T*); [BELOW]
4672 //
4673 // C++ [over.built]p14:
4674 //
4675 // For every T, where T is a pointer to object type, there
4676 // exist candidate operator functions of the form
4677 //
4678 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004679 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004680 = CandidateTypes.pointer_begin();
4681 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4682 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4683
4684 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4685 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4686
4687 if (Op == OO_Plus) {
4688 // T* operator+(ptrdiff_t, T*);
4689 ParamTypes[0] = ParamTypes[1];
4690 ParamTypes[1] = *Ptr;
4691 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4692 } else {
4693 // ptrdiff_t operator-(T, T);
4694 ParamTypes[1] = *Ptr;
4695 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4696 Args, 2, CandidateSet);
4697 }
4698 }
4699 }
4700 // Fall through
4701
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004702 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004703 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004704 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004705 // C++ [over.built]p12:
4706 //
4707 // For every pair of promoted arithmetic types L and R, there
4708 // exist candidate operator functions of the form
4709 //
4710 // LR operator*(L, R);
4711 // LR operator/(L, R);
4712 // LR operator+(L, R);
4713 // LR operator-(L, R);
4714 // bool operator<(L, R);
4715 // bool operator>(L, R);
4716 // bool operator<=(L, R);
4717 // bool operator>=(L, R);
4718 // bool operator==(L, R);
4719 // bool operator!=(L, R);
4720 //
4721 // where LR is the result of the usual arithmetic conversions
4722 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004723 //
4724 // C++ [over.built]p24:
4725 //
4726 // For every pair of promoted arithmetic types L and R, there exist
4727 // candidate operator functions of the form
4728 //
4729 // LR operator?(bool, L, R);
4730 //
4731 // where LR is the result of the usual arithmetic conversions
4732 // between types L and R.
4733 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004734 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004735 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004736 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004737 Right < LastPromotedArithmeticType; ++Right) {
4738 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004739 QualType Result
4740 = isComparison
4741 ? Context.BoolTy
4742 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004743 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4744 }
4745 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004746
4747 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4748 // conditional operator for vector types.
4749 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4750 Vec1End = CandidateTypes.vector_end();
4751 Vec1 != Vec1End; ++Vec1)
4752 for (BuiltinCandidateTypeSet::iterator
4753 Vec2 = CandidateTypes.vector_begin(),
4754 Vec2End = CandidateTypes.vector_end();
4755 Vec2 != Vec2End; ++Vec2) {
4756 QualType LandR[2] = { *Vec1, *Vec2 };
4757 QualType Result;
4758 if (isComparison)
4759 Result = Context.BoolTy;
4760 else {
4761 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4762 Result = *Vec1;
4763 else
4764 Result = *Vec2;
4765 }
4766
4767 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4768 }
4769
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004770 break;
4771
4772 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004773 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004774 case OO_Caret:
4775 case OO_Pipe:
4776 case OO_LessLess:
4777 case OO_GreaterGreater:
4778 // C++ [over.built]p17:
4779 //
4780 // For every pair of promoted integral 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 // L operator<<(L, R);
4788 // L operator>>(L, R);
4789 //
4790 // where LR is the result of the usual arithmetic conversions
4791 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004792 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004793 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004794 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004795 Right < LastPromotedIntegralType; ++Right) {
4796 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4797 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4798 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004799 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004800 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4801 }
4802 }
4803 break;
4804
4805 case OO_Equal:
4806 // C++ [over.built]p20:
4807 //
4808 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004809 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004810 // empty, there exist candidate operator functions of the form
4811 //
4812 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004813 for (BuiltinCandidateTypeSet::iterator
4814 Enum = CandidateTypes.enumeration_begin(),
4815 EnumEnd = CandidateTypes.enumeration_end();
4816 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004817 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004818 CandidateSet);
4819 for (BuiltinCandidateTypeSet::iterator
4820 MemPtr = CandidateTypes.member_pointer_begin(),
4821 MemPtrEnd = CandidateTypes.member_pointer_end();
4822 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004823 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004824 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004825
4826 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004827
4828 case OO_PlusEqual:
4829 case OO_MinusEqual:
4830 // C++ [over.built]p19:
4831 //
4832 // For every pair (T, VQ), where T is any type and VQ is either
4833 // volatile or empty, there exist candidate operator functions
4834 // of the form
4835 //
4836 // T*VQ& operator=(T*VQ&, T*);
4837 //
4838 // C++ [over.built]p21:
4839 //
4840 // For every pair (T, VQ), where T is a cv-qualified or
4841 // cv-unqualified object type and VQ is either volatile or
4842 // empty, there exist candidate operator functions of the form
4843 //
4844 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4845 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4846 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4847 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4848 QualType ParamTypes[2];
4849 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4850
4851 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004852 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004853 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4854 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004855
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004856 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4857 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004858 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004859 ParamTypes[0]
4860 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004861 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4862 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004863 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004864 }
4865 // Fall through.
4866
4867 case OO_StarEqual:
4868 case OO_SlashEqual:
4869 // C++ [over.built]p18:
4870 //
4871 // For every triple (L, VQ, R), where L is an arithmetic type,
4872 // VQ is either volatile or empty, and R is a promoted
4873 // arithmetic type, there exist candidate operator functions of
4874 // the form
4875 //
4876 // VQ L& operator=(VQ L&, R);
4877 // VQ L& operator*=(VQ L&, R);
4878 // VQ L& operator/=(VQ L&, R);
4879 // VQ L& operator+=(VQ L&, R);
4880 // VQ L& operator-=(VQ L&, R);
4881 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004882 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004883 Right < LastPromotedArithmeticType; ++Right) {
4884 QualType ParamTypes[2];
4885 ParamTypes[1] = ArithmeticTypes[Right];
4886
4887 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004888 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004889 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4890 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004891
4892 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004893 if (VisibleTypeConversionsQuals.hasVolatile()) {
4894 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4895 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4896 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4897 /*IsAssigmentOperator=*/Op == OO_Equal);
4898 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004899 }
4900 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004901
4902 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4903 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4904 Vec1End = CandidateTypes.vector_end();
4905 Vec1 != Vec1End; ++Vec1)
4906 for (BuiltinCandidateTypeSet::iterator
4907 Vec2 = CandidateTypes.vector_begin(),
4908 Vec2End = CandidateTypes.vector_end();
4909 Vec2 != Vec2End; ++Vec2) {
4910 QualType ParamTypes[2];
4911 ParamTypes[1] = *Vec2;
4912 // Add this built-in operator as a candidate (VQ is empty).
4913 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4914 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4915 /*IsAssigmentOperator=*/Op == OO_Equal);
4916
4917 // Add this built-in operator as a candidate (VQ is 'volatile').
4918 if (VisibleTypeConversionsQuals.hasVolatile()) {
4919 ParamTypes[0] = Context.getVolatileType(*Vec1);
4920 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4921 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4922 /*IsAssigmentOperator=*/Op == OO_Equal);
4923 }
4924 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004925 break;
4926
4927 case OO_PercentEqual:
4928 case OO_LessLessEqual:
4929 case OO_GreaterGreaterEqual:
4930 case OO_AmpEqual:
4931 case OO_CaretEqual:
4932 case OO_PipeEqual:
4933 // C++ [over.built]p22:
4934 //
4935 // For every triple (L, VQ, R), where L is an integral type, VQ
4936 // is either volatile or empty, and R is a promoted integral
4937 // type, there exist candidate operator functions of the form
4938 //
4939 // VQ L& operator%=(VQ L&, R);
4940 // VQ L& operator<<=(VQ L&, R);
4941 // VQ L& operator>>=(VQ L&, R);
4942 // VQ L& operator&=(VQ L&, R);
4943 // VQ L& operator^=(VQ L&, R);
4944 // VQ L& operator|=(VQ L&, R);
4945 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004946 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004947 Right < LastPromotedIntegralType; ++Right) {
4948 QualType ParamTypes[2];
4949 ParamTypes[1] = ArithmeticTypes[Right];
4950
4951 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004952 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004953 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00004954 if (VisibleTypeConversionsQuals.hasVolatile()) {
4955 // Add this built-in operator as a candidate (VQ is 'volatile').
4956 ParamTypes[0] = ArithmeticTypes[Left];
4957 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4958 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4959 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4960 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004961 }
4962 }
4963 break;
4964
Douglas Gregor74253732008-11-19 15:42:04 +00004965 case OO_Exclaim: {
4966 // C++ [over.operator]p23:
4967 //
4968 // There also exist candidate operator functions of the form
4969 //
Mike Stump1eb44332009-09-09 15:08:12 +00004970 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004971 // bool operator&&(bool, bool); [BELOW]
4972 // bool operator||(bool, bool); [BELOW]
4973 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004974 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4975 /*IsAssignmentOperator=*/false,
4976 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004977 break;
4978 }
4979
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004980 case OO_AmpAmp:
4981 case OO_PipePipe: {
4982 // C++ [over.operator]p23:
4983 //
4984 // There also exist candidate operator functions of the form
4985 //
Douglas Gregor74253732008-11-19 15:42:04 +00004986 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004987 // bool operator&&(bool, bool);
4988 // bool operator||(bool, bool);
4989 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004990 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4991 /*IsAssignmentOperator=*/false,
4992 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004993 break;
4994 }
4995
4996 case OO_Subscript:
4997 // C++ [over.built]p13:
4998 //
4999 // For every cv-qualified or cv-unqualified object type T there
5000 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005001 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005002 // T* operator+(T*, ptrdiff_t); [ABOVE]
5003 // T& operator[](T*, ptrdiff_t);
5004 // T* operator-(T*, ptrdiff_t); [ABOVE]
5005 // T* operator+(ptrdiff_t, T*); [ABOVE]
5006 // T& operator[](ptrdiff_t, T*);
5007 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5008 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5009 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00005010 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005011 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005012
5013 // T& operator[](T*, ptrdiff_t)
5014 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5015
5016 // T& operator[](ptrdiff_t, T*);
5017 ParamTypes[0] = ParamTypes[1];
5018 ParamTypes[1] = *Ptr;
5019 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005020 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005021 break;
5022
5023 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005024 // C++ [over.built]p11:
5025 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5026 // C1 is the same type as C2 or is a derived class of C2, T is an object
5027 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5028 // there exist candidate operator functions of the form
5029 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5030 // where CV12 is the union of CV1 and CV2.
5031 {
5032 for (BuiltinCandidateTypeSet::iterator Ptr =
5033 CandidateTypes.pointer_begin();
5034 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5035 QualType C1Ty = (*Ptr);
5036 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005037 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005038 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005039 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005040 if (!isa<RecordType>(C1))
5041 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005042 // heuristic to reduce number of builtin candidates in the set.
5043 // Add volatile/restrict version only if there are conversions to a
5044 // volatile/restrict type.
5045 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5046 continue;
5047 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5048 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005049 }
5050 for (BuiltinCandidateTypeSet::iterator
5051 MemPtr = CandidateTypes.member_pointer_begin(),
5052 MemPtrEnd = CandidateTypes.member_pointer_end();
5053 MemPtr != MemPtrEnd; ++MemPtr) {
5054 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5055 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005056 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005057 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5058 break;
5059 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5060 // build CV12 T&
5061 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005062 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5063 T.isVolatileQualified())
5064 continue;
5065 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5066 T.isRestrictQualified())
5067 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005068 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005069 QualType ResultTy = Context.getLValueReferenceType(T);
5070 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5071 }
5072 }
5073 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005074 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005075
5076 case OO_Conditional:
5077 // Note that we don't consider the first argument, since it has been
5078 // contextually converted to bool long ago. The candidates below are
5079 // therefore added as binary.
5080 //
5081 // C++ [over.built]p24:
5082 // For every type T, where T is a pointer or pointer-to-member type,
5083 // there exist candidate operator functions of the form
5084 //
5085 // T operator?(bool, T, T);
5086 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005087 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5088 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5089 QualType ParamTypes[2] = { *Ptr, *Ptr };
5090 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5091 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00005092 for (BuiltinCandidateTypeSet::iterator Ptr =
5093 CandidateTypes.member_pointer_begin(),
5094 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5095 QualType ParamTypes[2] = { *Ptr, *Ptr };
5096 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5097 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005098 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005099 }
5100}
5101
Douglas Gregorfa047642009-02-04 00:32:51 +00005102/// \brief Add function candidates found via argument-dependent lookup
5103/// to the set of overloading candidates.
5104///
5105/// This routine performs argument-dependent name lookup based on the
5106/// given function name (which may also be an operator name) and adds
5107/// all of the overload candidates found by ADL to the overload
5108/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005109void
Douglas Gregorfa047642009-02-04 00:32:51 +00005110Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005111 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005112 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005113 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005114 OverloadCandidateSet& CandidateSet,
5115 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005116 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005117
John McCalla113e722010-01-26 06:04:06 +00005118 // FIXME: This approach for uniquing ADL results (and removing
5119 // redundant candidates from the set) relies on pointer-equality,
5120 // which means we need to key off the canonical decl. However,
5121 // always going back to the canonical decl might not get us the
5122 // right set of default arguments. What default arguments are
5123 // we supposed to consider on ADL candidates, anyway?
5124
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005125 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005126 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005127
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005128 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005129 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5130 CandEnd = CandidateSet.end();
5131 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005132 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005133 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005134 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005135 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005136 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005137
5138 // For each of the ADL candidates we found, add it to the overload
5139 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005140 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005141 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005142 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005143 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005144 continue;
5145
John McCall9aa472c2010-03-19 07:35:19 +00005146 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005147 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005148 } else
John McCall6e266892010-01-26 03:27:55 +00005149 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005150 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005151 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005152 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005153}
5154
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005155/// isBetterOverloadCandidate - Determines whether the first overload
5156/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005157bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005158Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00005159 const OverloadCandidate& Cand2,
5160 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005161 // Define viable functions to be better candidates than non-viable
5162 // functions.
5163 if (!Cand2.Viable)
5164 return Cand1.Viable;
5165 else if (!Cand1.Viable)
5166 return false;
5167
Douglas Gregor88a35142008-12-22 05:46:06 +00005168 // C++ [over.match.best]p1:
5169 //
5170 // -- if F is a static member function, ICS1(F) is defined such
5171 // that ICS1(F) is neither better nor worse than ICS1(G) for
5172 // any function G, and, symmetrically, ICS1(G) is neither
5173 // better nor worse than ICS1(F).
5174 unsigned StartArg = 0;
5175 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5176 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005177
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005178 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005179 // A viable function F1 is defined to be a better function than another
5180 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005181 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005182 unsigned NumArgs = Cand1.Conversions.size();
5183 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5184 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005185 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005186 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5187 Cand2.Conversions[ArgIdx])) {
5188 case ImplicitConversionSequence::Better:
5189 // Cand1 has a better conversion sequence.
5190 HasBetterConversion = true;
5191 break;
5192
5193 case ImplicitConversionSequence::Worse:
5194 // Cand1 can't be better than Cand2.
5195 return false;
5196
5197 case ImplicitConversionSequence::Indistinguishable:
5198 // Do nothing.
5199 break;
5200 }
5201 }
5202
Mike Stump1eb44332009-09-09 15:08:12 +00005203 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005204 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005205 if (HasBetterConversion)
5206 return true;
5207
Mike Stump1eb44332009-09-09 15:08:12 +00005208 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005209 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005210 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005211 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5212 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005213
5214 // -- F1 and F2 are function template specializations, and the function
5215 // template for F1 is more specialized than the template for F2
5216 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005217 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005218 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5219 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005220 if (FunctionTemplateDecl *BetterTemplate
5221 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5222 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00005223 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005224 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5225 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005226 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005227
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005228 // -- the context is an initialization by user-defined conversion
5229 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5230 // from the return type of F1 to the destination type (i.e.,
5231 // the type of the entity being initialized) is a better
5232 // conversion sequence than the standard conversion sequence
5233 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00005234 if (Cand1.Function && Cand2.Function &&
5235 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005236 isa<CXXConversionDecl>(Cand2.Function)) {
5237 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5238 Cand2.FinalConversion)) {
5239 case ImplicitConversionSequence::Better:
5240 // Cand1 has a better conversion sequence.
5241 return true;
5242
5243 case ImplicitConversionSequence::Worse:
5244 // Cand1 can't be better than Cand2.
5245 return false;
5246
5247 case ImplicitConversionSequence::Indistinguishable:
5248 // Do nothing
5249 break;
5250 }
5251 }
5252
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005253 return false;
5254}
5255
Mike Stump1eb44332009-09-09 15:08:12 +00005256/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005257/// within an overload candidate set.
5258///
5259/// \param CandidateSet the set of candidate functions.
5260///
5261/// \param Loc the location of the function name (or operator symbol) for
5262/// which overload resolution occurs.
5263///
Mike Stump1eb44332009-09-09 15:08:12 +00005264/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005265/// function, Best points to the candidate function found.
5266///
5267/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00005268OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5269 SourceLocation Loc,
5270 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005271 // Find the best viable function.
5272 Best = CandidateSet.end();
5273 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5274 Cand != CandidateSet.end(); ++Cand) {
5275 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00005276 if (Best == CandidateSet.end() ||
5277 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005278 Best = Cand;
5279 }
5280 }
5281
5282 // If we didn't find any viable functions, abort.
5283 if (Best == CandidateSet.end())
5284 return OR_No_Viable_Function;
5285
5286 // Make sure that this function is better than every other viable
5287 // function. If not, we have an ambiguity.
5288 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5289 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005290 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005291 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00005292 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005293 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005294 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005295 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005296 }
Mike Stump1eb44332009-09-09 15:08:12 +00005297
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005298 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005299 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005300 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005301 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005302 return OR_Deleted;
5303
Douglas Gregore0762c92009-06-19 23:52:42 +00005304 // C++ [basic.def.odr]p2:
5305 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005306 // when referred to from a potentially-evaluated expression. [Note: this
5307 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005308 // (clause 13), user-defined conversions (12.3.2), allocation function for
5309 // placement new (5.3.4), as well as non-default initialization (8.5).
5310 if (Best->Function)
5311 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005312 return OR_Success;
5313}
5314
John McCall3c80f572010-01-12 02:15:36 +00005315namespace {
5316
5317enum OverloadCandidateKind {
5318 oc_function,
5319 oc_method,
5320 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005321 oc_function_template,
5322 oc_method_template,
5323 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005324 oc_implicit_default_constructor,
5325 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005326 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005327};
5328
John McCall220ccbf2010-01-13 00:25:19 +00005329OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5330 FunctionDecl *Fn,
5331 std::string &Description) {
5332 bool isTemplate = false;
5333
5334 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5335 isTemplate = true;
5336 Description = S.getTemplateArgumentBindingsText(
5337 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5338 }
John McCallb1622a12010-01-06 09:43:14 +00005339
5340 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005341 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005342 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005343
John McCall3c80f572010-01-12 02:15:36 +00005344 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5345 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005346 }
5347
5348 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5349 // This actually gets spelled 'candidate function' for now, but
5350 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005351 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005352 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005353
5354 assert(Meth->isCopyAssignment()
5355 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005356 return oc_implicit_copy_assignment;
5357 }
5358
John McCall220ccbf2010-01-13 00:25:19 +00005359 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005360}
5361
5362} // end anonymous namespace
5363
5364// Notes the location of an overload candidate.
5365void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005366 std::string FnDesc;
5367 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5368 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5369 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005370}
5371
John McCall1d318332010-01-12 00:44:57 +00005372/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5373/// "lead" diagnostic; it will be given two arguments, the source and
5374/// target types of the conversion.
5375void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5376 SourceLocation CaretLoc,
5377 const PartialDiagnostic &PDiag) {
5378 Diag(CaretLoc, PDiag)
5379 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5380 for (AmbiguousConversionSequence::const_iterator
5381 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5382 NoteOverloadCandidate(*I);
5383 }
John McCall81201622010-01-08 04:41:39 +00005384}
5385
John McCall1d318332010-01-12 00:44:57 +00005386namespace {
5387
John McCalladbb8f82010-01-13 09:16:55 +00005388void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5389 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5390 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005391 assert(Cand->Function && "for now, candidate must be a function");
5392 FunctionDecl *Fn = Cand->Function;
5393
5394 // There's a conversion slot for the object argument if this is a
5395 // non-constructor method. Note that 'I' corresponds the
5396 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005397 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005398 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005399 if (I == 0)
5400 isObjectArgument = true;
5401 else
5402 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005403 }
5404
John McCall220ccbf2010-01-13 00:25:19 +00005405 std::string FnDesc;
5406 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5407
John McCalladbb8f82010-01-13 09:16:55 +00005408 Expr *FromExpr = Conv.Bad.FromExpr;
5409 QualType FromTy = Conv.Bad.getFromType();
5410 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005411
John McCall5920dbb2010-02-02 02:42:52 +00005412 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005413 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005414 Expr *E = FromExpr->IgnoreParens();
5415 if (isa<UnaryOperator>(E))
5416 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005417 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005418
5419 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5420 << (unsigned) FnKind << FnDesc
5421 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5422 << ToTy << Name << I+1;
5423 return;
5424 }
5425
John McCall258b2032010-01-23 08:10:49 +00005426 // Do some hand-waving analysis to see if the non-viability is due
5427 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005428 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5429 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5430 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5431 CToTy = RT->getPointeeType();
5432 else {
5433 // TODO: detect and diagnose the full richness of const mismatches.
5434 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5435 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5436 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5437 }
5438
5439 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5440 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5441 // It is dumb that we have to do this here.
5442 while (isa<ArrayType>(CFromTy))
5443 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5444 while (isa<ArrayType>(CToTy))
5445 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5446
5447 Qualifiers FromQs = CFromTy.getQualifiers();
5448 Qualifiers ToQs = CToTy.getQualifiers();
5449
5450 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5451 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5452 << (unsigned) FnKind << FnDesc
5453 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5454 << FromTy
5455 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5456 << (unsigned) isObjectArgument << I+1;
5457 return;
5458 }
5459
5460 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5461 assert(CVR && "unexpected qualifiers mismatch");
5462
5463 if (isObjectArgument) {
5464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5465 << (unsigned) FnKind << FnDesc
5466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5467 << FromTy << (CVR - 1);
5468 } else {
5469 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5470 << (unsigned) FnKind << FnDesc
5471 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5472 << FromTy << (CVR - 1) << I+1;
5473 }
5474 return;
5475 }
5476
John McCall258b2032010-01-23 08:10:49 +00005477 // Diagnose references or pointers to incomplete types differently,
5478 // since it's far from impossible that the incompleteness triggered
5479 // the failure.
5480 QualType TempFromTy = FromTy.getNonReferenceType();
5481 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5482 TempFromTy = PTy->getPointeeType();
5483 if (TempFromTy->isIncompleteType()) {
5484 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5485 << (unsigned) FnKind << FnDesc
5486 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5487 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5488 return;
5489 }
5490
Douglas Gregor85789812010-06-30 23:01:39 +00005491 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005492 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005493 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5494 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5495 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5496 FromPtrTy->getPointeeType()) &&
5497 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5498 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5499 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5500 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005501 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005502 }
5503 } else if (const ObjCObjectPointerType *FromPtrTy
5504 = FromTy->getAs<ObjCObjectPointerType>()) {
5505 if (const ObjCObjectPointerType *ToPtrTy
5506 = ToTy->getAs<ObjCObjectPointerType>())
5507 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5508 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5509 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5510 FromPtrTy->getPointeeType()) &&
5511 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005512 BaseToDerivedConversion = 2;
5513 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5514 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5515 !FromTy->isIncompleteType() &&
5516 !ToRefTy->getPointeeType()->isIncompleteType() &&
5517 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5518 BaseToDerivedConversion = 3;
5519 }
5520
5521 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005522 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005523 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005524 << (unsigned) FnKind << FnDesc
5525 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005526 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005527 << FromTy << ToTy << I+1;
5528 return;
5529 }
5530
John McCall651f3ee2010-01-14 03:28:57 +00005531 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5533 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005534 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005535 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005536}
5537
5538void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5539 unsigned NumFormalArgs) {
5540 // TODO: treat calls to a missing default constructor as a special case
5541
5542 FunctionDecl *Fn = Cand->Function;
5543 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5544
5545 unsigned MinParams = Fn->getMinRequiredArguments();
5546
5547 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005548 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005549 unsigned mode, modeCount;
5550 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005551 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5552 (Cand->FailureKind == ovl_fail_bad_deduction &&
5553 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005554 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5555 mode = 0; // "at least"
5556 else
5557 mode = 2; // "exactly"
5558 modeCount = MinParams;
5559 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005560 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5561 (Cand->FailureKind == ovl_fail_bad_deduction &&
5562 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005563 if (MinParams != FnTy->getNumArgs())
5564 mode = 1; // "at most"
5565 else
5566 mode = 2; // "exactly"
5567 modeCount = FnTy->getNumArgs();
5568 }
5569
5570 std::string Description;
5571 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5572
5573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005574 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5575 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005576}
5577
John McCall342fec42010-02-01 18:53:26 +00005578/// Diagnose a failed template-argument deduction.
5579void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5580 Expr **Args, unsigned NumArgs) {
5581 FunctionDecl *Fn = Cand->Function; // pattern
5582
Douglas Gregora9333192010-05-08 17:41:32 +00005583 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005584 NamedDecl *ParamD;
5585 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5586 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5587 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005588 switch (Cand->DeductionFailure.Result) {
5589 case Sema::TDK_Success:
5590 llvm_unreachable("TDK_success while diagnosing bad deduction");
5591
5592 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005593 assert(ParamD && "no parameter found for incomplete deduction result");
5594 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5595 << ParamD->getDeclName();
5596 return;
5597 }
5598
John McCall57e97782010-08-05 09:05:08 +00005599 case Sema::TDK_Underqualified: {
5600 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5601 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5602
5603 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5604
5605 // Param will have been canonicalized, but it should just be a
5606 // qualified version of ParamD, so move the qualifiers to that.
5607 QualifierCollector Qs(S.Context);
5608 Qs.strip(Param);
5609 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5610 assert(S.Context.hasSameType(Param, NonCanonParam));
5611
5612 // Arg has also been canonicalized, but there's nothing we can do
5613 // about that. It also doesn't matter as much, because it won't
5614 // have any template parameters in it (because deduction isn't
5615 // done on dependent types).
5616 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5617
5618 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5619 << ParamD->getDeclName() << Arg << NonCanonParam;
5620 return;
5621 }
5622
5623 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005624 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005625 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005626 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005627 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005628 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005629 which = 1;
5630 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005631 which = 2;
5632 }
5633
5634 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5635 << which << ParamD->getDeclName()
5636 << *Cand->DeductionFailure.getFirstArg()
5637 << *Cand->DeductionFailure.getSecondArg();
5638 return;
5639 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005640
Douglas Gregorf1a84452010-05-08 19:15:54 +00005641 case Sema::TDK_InvalidExplicitArguments:
5642 assert(ParamD && "no parameter found for invalid explicit arguments");
5643 if (ParamD->getDeclName())
5644 S.Diag(Fn->getLocation(),
5645 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5646 << ParamD->getDeclName();
5647 else {
5648 int index = 0;
5649 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5650 index = TTP->getIndex();
5651 else if (NonTypeTemplateParmDecl *NTTP
5652 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5653 index = NTTP->getIndex();
5654 else
5655 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5656 S.Diag(Fn->getLocation(),
5657 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5658 << (index + 1);
5659 }
5660 return;
5661
Douglas Gregora18592e2010-05-08 18:13:28 +00005662 case Sema::TDK_TooManyArguments:
5663 case Sema::TDK_TooFewArguments:
5664 DiagnoseArityMismatch(S, Cand, NumArgs);
5665 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005666
5667 case Sema::TDK_InstantiationDepth:
5668 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5669 return;
5670
5671 case Sema::TDK_SubstitutionFailure: {
5672 std::string ArgString;
5673 if (TemplateArgumentList *Args
5674 = Cand->DeductionFailure.getTemplateArgumentList())
5675 ArgString = S.getTemplateArgumentBindingsText(
5676 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5677 *Args);
5678 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5679 << ArgString;
5680 return;
5681 }
Douglas Gregora9333192010-05-08 17:41:32 +00005682
John McCall342fec42010-02-01 18:53:26 +00005683 // TODO: diagnose these individually, then kill off
5684 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005685 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005686 case Sema::TDK_FailedOverloadResolution:
5687 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5688 return;
5689 }
5690}
5691
5692/// Generates a 'note' diagnostic for an overload candidate. We've
5693/// already generated a primary error at the call site.
5694///
5695/// It really does need to be a single diagnostic with its caret
5696/// pointed at the candidate declaration. Yes, this creates some
5697/// major challenges of technical writing. Yes, this makes pointing
5698/// out problems with specific arguments quite awkward. It's still
5699/// better than generating twenty screens of text for every failed
5700/// overload.
5701///
5702/// It would be great to be able to express per-candidate problems
5703/// more richly for those diagnostic clients that cared, but we'd
5704/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005705void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5706 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005707 FunctionDecl *Fn = Cand->Function;
5708
John McCall81201622010-01-08 04:41:39 +00005709 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005710 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005711 std::string FnDesc;
5712 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005713
5714 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005715 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005716 return;
John McCall81201622010-01-08 04:41:39 +00005717 }
5718
John McCall220ccbf2010-01-13 00:25:19 +00005719 // We don't really have anything else to say about viable candidates.
5720 if (Cand->Viable) {
5721 S.NoteOverloadCandidate(Fn);
5722 return;
5723 }
John McCall1d318332010-01-12 00:44:57 +00005724
John McCalladbb8f82010-01-13 09:16:55 +00005725 switch (Cand->FailureKind) {
5726 case ovl_fail_too_many_arguments:
5727 case ovl_fail_too_few_arguments:
5728 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005729
John McCalladbb8f82010-01-13 09:16:55 +00005730 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005731 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5732
John McCall717e8912010-01-23 05:17:32 +00005733 case ovl_fail_trivial_conversion:
5734 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005735 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005736 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005737
John McCallb1bdc622010-02-25 01:37:24 +00005738 case ovl_fail_bad_conversion: {
5739 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5740 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005741 if (Cand->Conversions[I].isBad())
5742 return DiagnoseBadConversion(S, Cand, I);
5743
5744 // FIXME: this currently happens when we're called from SemaInit
5745 // when user-conversion overload fails. Figure out how to handle
5746 // those conditions and diagnose them well.
5747 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005748 }
John McCallb1bdc622010-02-25 01:37:24 +00005749 }
John McCalla1d7d622010-01-08 00:58:21 +00005750}
5751
5752void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5753 // Desugar the type of the surrogate down to a function type,
5754 // retaining as many typedefs as possible while still showing
5755 // the function type (and, therefore, its parameter types).
5756 QualType FnType = Cand->Surrogate->getConversionType();
5757 bool isLValueReference = false;
5758 bool isRValueReference = false;
5759 bool isPointer = false;
5760 if (const LValueReferenceType *FnTypeRef =
5761 FnType->getAs<LValueReferenceType>()) {
5762 FnType = FnTypeRef->getPointeeType();
5763 isLValueReference = true;
5764 } else if (const RValueReferenceType *FnTypeRef =
5765 FnType->getAs<RValueReferenceType>()) {
5766 FnType = FnTypeRef->getPointeeType();
5767 isRValueReference = true;
5768 }
5769 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5770 FnType = FnTypePtr->getPointeeType();
5771 isPointer = true;
5772 }
5773 // Desugar down to a function type.
5774 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5775 // Reconstruct the pointer/reference as appropriate.
5776 if (isPointer) FnType = S.Context.getPointerType(FnType);
5777 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5778 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5779
5780 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5781 << FnType;
5782}
5783
5784void NoteBuiltinOperatorCandidate(Sema &S,
5785 const char *Opc,
5786 SourceLocation OpLoc,
5787 OverloadCandidate *Cand) {
5788 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5789 std::string TypeStr("operator");
5790 TypeStr += Opc;
5791 TypeStr += "(";
5792 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5793 if (Cand->Conversions.size() == 1) {
5794 TypeStr += ")";
5795 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5796 } else {
5797 TypeStr += ", ";
5798 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5799 TypeStr += ")";
5800 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5801 }
5802}
5803
5804void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5805 OverloadCandidate *Cand) {
5806 unsigned NoOperands = Cand->Conversions.size();
5807 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5808 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005809 if (ICS.isBad()) break; // all meaningless after first invalid
5810 if (!ICS.isAmbiguous()) continue;
5811
5812 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005813 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005814 }
5815}
5816
John McCall1b77e732010-01-15 23:32:50 +00005817SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5818 if (Cand->Function)
5819 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005820 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005821 return Cand->Surrogate->getLocation();
5822 return SourceLocation();
5823}
5824
John McCallbf65c0b2010-01-12 00:48:53 +00005825struct CompareOverloadCandidatesForDisplay {
5826 Sema &S;
5827 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005828
5829 bool operator()(const OverloadCandidate *L,
5830 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005831 // Fast-path this check.
5832 if (L == R) return false;
5833
John McCall81201622010-01-08 04:41:39 +00005834 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005835 if (L->Viable) {
5836 if (!R->Viable) return true;
5837
5838 // TODO: introduce a tri-valued comparison for overload
5839 // candidates. Would be more worthwhile if we had a sort
5840 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005841 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5842 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005843 } else if (R->Viable)
5844 return false;
John McCall81201622010-01-08 04:41:39 +00005845
John McCall1b77e732010-01-15 23:32:50 +00005846 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005847
John McCall1b77e732010-01-15 23:32:50 +00005848 // Criteria by which we can sort non-viable candidates:
5849 if (!L->Viable) {
5850 // 1. Arity mismatches come after other candidates.
5851 if (L->FailureKind == ovl_fail_too_many_arguments ||
5852 L->FailureKind == ovl_fail_too_few_arguments)
5853 return false;
5854 if (R->FailureKind == ovl_fail_too_many_arguments ||
5855 R->FailureKind == ovl_fail_too_few_arguments)
5856 return true;
John McCall81201622010-01-08 04:41:39 +00005857
John McCall717e8912010-01-23 05:17:32 +00005858 // 2. Bad conversions come first and are ordered by the number
5859 // of bad conversions and quality of good conversions.
5860 if (L->FailureKind == ovl_fail_bad_conversion) {
5861 if (R->FailureKind != ovl_fail_bad_conversion)
5862 return true;
5863
5864 // If there's any ordering between the defined conversions...
5865 // FIXME: this might not be transitive.
5866 assert(L->Conversions.size() == R->Conversions.size());
5867
5868 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005869 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5870 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005871 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5872 R->Conversions[I])) {
5873 case ImplicitConversionSequence::Better:
5874 leftBetter++;
5875 break;
5876
5877 case ImplicitConversionSequence::Worse:
5878 leftBetter--;
5879 break;
5880
5881 case ImplicitConversionSequence::Indistinguishable:
5882 break;
5883 }
5884 }
5885 if (leftBetter > 0) return true;
5886 if (leftBetter < 0) return false;
5887
5888 } else if (R->FailureKind == ovl_fail_bad_conversion)
5889 return false;
5890
John McCall1b77e732010-01-15 23:32:50 +00005891 // TODO: others?
5892 }
5893
5894 // Sort everything else by location.
5895 SourceLocation LLoc = GetLocationForCandidate(L);
5896 SourceLocation RLoc = GetLocationForCandidate(R);
5897
5898 // Put candidates without locations (e.g. builtins) at the end.
5899 if (LLoc.isInvalid()) return false;
5900 if (RLoc.isInvalid()) return true;
5901
5902 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005903 }
5904};
5905
John McCall717e8912010-01-23 05:17:32 +00005906/// CompleteNonViableCandidate - Normally, overload resolution only
5907/// computes up to the first
5908void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5909 Expr **Args, unsigned NumArgs) {
5910 assert(!Cand->Viable);
5911
5912 // Don't do anything on failures other than bad conversion.
5913 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5914
5915 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005916 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005917 unsigned ConvCount = Cand->Conversions.size();
5918 while (true) {
5919 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5920 ConvIdx++;
5921 if (Cand->Conversions[ConvIdx - 1].isBad())
5922 break;
5923 }
5924
5925 if (ConvIdx == ConvCount)
5926 return;
5927
John McCallb1bdc622010-02-25 01:37:24 +00005928 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5929 "remaining conversion is initialized?");
5930
Douglas Gregor23ef6c02010-04-16 17:45:54 +00005931 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00005932 // operation somehow.
5933 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00005934
5935 const FunctionProtoType* Proto;
5936 unsigned ArgIdx = ConvIdx;
5937
5938 if (Cand->IsSurrogate) {
5939 QualType ConvType
5940 = Cand->Surrogate->getConversionType().getNonReferenceType();
5941 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5942 ConvType = ConvPtrType->getPointeeType();
5943 Proto = ConvType->getAs<FunctionProtoType>();
5944 ArgIdx--;
5945 } else if (Cand->Function) {
5946 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5947 if (isa<CXXMethodDecl>(Cand->Function) &&
5948 !isa<CXXConstructorDecl>(Cand->Function))
5949 ArgIdx--;
5950 } else {
5951 // Builtin binary operator with a bad first conversion.
5952 assert(ConvCount <= 3);
5953 for (; ConvIdx != ConvCount; ++ConvIdx)
5954 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005955 = TryCopyInitialization(S, Args[ConvIdx],
5956 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5957 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005958 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00005959 return;
5960 }
5961
5962 // Fill in the rest of the conversions.
5963 unsigned NumArgsInProto = Proto->getNumArgs();
5964 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5965 if (ArgIdx < NumArgsInProto)
5966 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005967 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5968 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005969 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00005970 else
5971 Cand->Conversions[ConvIdx].setEllipsis();
5972 }
5973}
5974
John McCalla1d7d622010-01-08 00:58:21 +00005975} // end anonymous namespace
5976
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005977/// PrintOverloadCandidates - When overload resolution fails, prints
5978/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00005979/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00005980void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005981Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00005982 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00005983 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005984 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00005985 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00005986 // Sort the candidates by viability and position. Sorting directly would
5987 // be prohibitive, so we make a set of pointers and sort those.
5988 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5989 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5990 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5991 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00005992 Cand != LastCand; ++Cand) {
5993 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00005994 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00005995 else if (OCD == OCD_AllCandidates) {
5996 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005997 if (Cand->Function || Cand->IsSurrogate)
5998 Cands.push_back(Cand);
5999 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6000 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006001 }
6002 }
6003
John McCallbf65c0b2010-01-12 00:48:53 +00006004 std::sort(Cands.begin(), Cands.end(),
6005 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00006006
John McCall1d318332010-01-12 00:44:57 +00006007 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006008
John McCall81201622010-01-08 04:41:39 +00006009 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006010 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6011 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006012 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6013 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006014
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006015 // Set an arbitrary limit on the number of candidate functions we'll spam
6016 // the user with. FIXME: This limit should depend on details of the
6017 // candidate list.
6018 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6019 break;
6020 }
6021 ++CandsShown;
6022
John McCalla1d7d622010-01-08 00:58:21 +00006023 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00006024 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006025 else if (Cand->IsSurrogate)
6026 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006027 else {
6028 assert(Cand->Viable &&
6029 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006030 // Generally we only see ambiguities including viable builtin
6031 // operators if overload resolution got screwed up by an
6032 // ambiguous user-defined conversion.
6033 //
6034 // FIXME: It's quite possible for different conversions to see
6035 // different ambiguities, though.
6036 if (!ReportedAmbiguousConversions) {
6037 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6038 ReportedAmbiguousConversions = true;
6039 }
John McCalla1d7d622010-01-08 00:58:21 +00006040
John McCall1d318332010-01-12 00:44:57 +00006041 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00006042 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006043 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006044 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006045
6046 if (I != E)
Jeffrey Yasskin258de302010-06-11 06:58:43 +00006047 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006048}
6049
John McCall9aa472c2010-03-19 07:35:19 +00006050static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006051 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006052 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006053
John McCall9aa472c2010-03-19 07:35:19 +00006054 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006055}
6056
Douglas Gregor904eed32008-11-10 20:40:00 +00006057/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6058/// an overloaded function (C++ [over.over]), where @p From is an
6059/// expression with overloaded function type and @p ToType is the type
6060/// we're trying to resolve to. For example:
6061///
6062/// @code
6063/// int f(double);
6064/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006065///
Douglas Gregor904eed32008-11-10 20:40:00 +00006066/// int (*pfd)(double) = f; // selects f(double)
6067/// @endcode
6068///
6069/// This routine returns the resulting FunctionDecl if it could be
6070/// resolved, and NULL otherwise. When @p Complain is true, this
6071/// routine will emit diagnostics if there is an error.
6072FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006073Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006074 bool Complain,
6075 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006076 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006077 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006078 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006079 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006080 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006081 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006082 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006083 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006084 FunctionType = MemTypePtr->getPointeeType();
6085 IsMember = true;
6086 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006087
Douglas Gregor904eed32008-11-10 20:40:00 +00006088 // C++ [over.over]p1:
6089 // [...] [Note: any redundant set of parentheses surrounding the
6090 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006091 // C++ [over.over]p1:
6092 // [...] The overloaded function name can be preceded by the &
6093 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006094 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6095 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6096 if (OvlExpr->hasExplicitTemplateArgs()) {
6097 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6098 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00006099 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006100
6101 // We expect a pointer or reference to function, or a function pointer.
6102 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6103 if (!FunctionType->isFunctionType()) {
6104 if (Complain)
6105 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6106 << OvlExpr->getName() << ToType;
6107
6108 return 0;
6109 }
6110
6111 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006112
Douglas Gregor904eed32008-11-10 20:40:00 +00006113 // Look through all of the overloaded functions, searching for one
6114 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006115 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006116 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6117
Douglas Gregor00aeb522009-07-08 23:33:52 +00006118 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006119 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6120 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006121 // Look through any using declarations to find the underlying function.
6122 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6123
Douglas Gregor904eed32008-11-10 20:40:00 +00006124 // C++ [over.over]p3:
6125 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006126 // targets of type "pointer-to-function" or "reference-to-function."
6127 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006128 // type "pointer-to-member-function."
6129 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006130
Mike Stump1eb44332009-09-09 15:08:12 +00006131 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006132 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006133 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006134 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006135 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006136 // static when converting to member pointer.
6137 if (Method->isStatic() == IsMember)
6138 continue;
6139 } else if (IsMember)
6140 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006141
Douglas Gregor00aeb522009-07-08 23:33:52 +00006142 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006143 // If the name is a function template, template argument deduction is
6144 // done (14.8.2.2), and if the argument deduction succeeds, the
6145 // resulting template argument list is used to generate a single
6146 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006147 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006148 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00006149 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006150 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006151 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006152 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006153 FunctionType, Specialization, Info)) {
6154 // FIXME: make a note of the failed deduction for diagnostics.
6155 (void)Result;
6156 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006157 // FIXME: If the match isn't exact, shouldn't we just drop this as
6158 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00006159 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006160 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00006161 Matches.push_back(std::make_pair(I.getPair(),
6162 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006163 }
John McCallba135432009-11-21 08:51:07 +00006164
6165 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006166 }
Mike Stump1eb44332009-09-09 15:08:12 +00006167
Chandler Carruthbd647292009-12-29 06:17:27 +00006168 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006169 // Skip non-static functions when converting to pointer, and static
6170 // when converting to member pointer.
6171 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006172 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006173
6174 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006175 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006176 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006177 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006178 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006179
Chandler Carruthbd647292009-12-29 06:17:27 +00006180 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006181 QualType ResultTy;
6182 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6183 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6184 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006185 Matches.push_back(std::make_pair(I.getPair(),
6186 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006187 FoundNonTemplateFunction = true;
6188 }
Mike Stump1eb44332009-09-09 15:08:12 +00006189 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006190 }
6191
Douglas Gregor00aeb522009-07-08 23:33:52 +00006192 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006193 if (Matches.empty()) {
6194 if (Complain) {
6195 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6196 << OvlExpr->getName() << FunctionType;
6197 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6198 E = OvlExpr->decls_end();
6199 I != E; ++I)
6200 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6201 NoteOverloadCandidate(F);
6202 }
6203
Douglas Gregor00aeb522009-07-08 23:33:52 +00006204 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006205 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006206 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00006207 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006208 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00006209 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006210 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006211 return Result;
6212 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006213
6214 // C++ [over.over]p4:
6215 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006216 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006217 // [...] and any given function template specialization F1 is
6218 // eliminated if the set contains a second function template
6219 // specialization whose function template is more specialized
6220 // than the function template of F1 according to the partial
6221 // ordering rules of 14.5.5.2.
6222
6223 // The algorithm specified above is quadratic. We instead use a
6224 // two-pass algorithm (similar to the one used to identify the
6225 // best viable function in an overload set) that identifies the
6226 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006227
6228 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6229 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6230 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006231
6232 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006233 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006234 TPOC_Other, From->getLocStart(),
6235 PDiag(),
6236 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006237 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006238 PDiag(diag::note_ovl_candidate)
6239 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00006240 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00006241 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006242 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00006243 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006244 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00006245 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6246 }
John McCallc373d482010-01-27 01:50:18 +00006247 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006248 }
Mike Stump1eb44332009-09-09 15:08:12 +00006249
Douglas Gregor312a2022009-09-26 03:56:17 +00006250 // [...] any function template specializations in the set are
6251 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006252 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006253 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006254 ++I;
6255 else {
John McCall9aa472c2010-03-19 07:35:19 +00006256 Matches[I] = Matches[--N];
6257 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006258 }
6259 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006260
Mike Stump1eb44332009-09-09 15:08:12 +00006261 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006262 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006263 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006264 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006265 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00006266 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00006267 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00006268 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6269 }
John McCall9aa472c2010-03-19 07:35:19 +00006270 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006271 }
Mike Stump1eb44332009-09-09 15:08:12 +00006272
Douglas Gregor00aeb522009-07-08 23:33:52 +00006273 // FIXME: We should probably return the same thing that BestViableFunction
6274 // returns (even if we issue the diagnostics here).
6275 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006276 << Matches[0].second->getDeclName();
6277 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6278 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00006279 return 0;
6280}
6281
Douglas Gregor4b52e252009-12-21 23:17:24 +00006282/// \brief Given an expression that refers to an overloaded function, try to
6283/// resolve that overloaded function expression down to a single function.
6284///
6285/// This routine can only resolve template-ids that refer to a single function
6286/// template, where that template-id refers to a single template whose template
6287/// arguments are either provided by the template-id or have defaults,
6288/// as described in C++0x [temp.arg.explicit]p3.
6289FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6290 // C++ [over.over]p1:
6291 // [...] [Note: any redundant set of parentheses surrounding the
6292 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006293 // C++ [over.over]p1:
6294 // [...] The overloaded function name can be preceded by the &
6295 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006296
6297 if (From->getType() != Context.OverloadTy)
6298 return 0;
6299
6300 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00006301
6302 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006303 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006304 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006305
6306 TemplateArgumentListInfo ExplicitTemplateArgs;
6307 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006308
6309 // Look through all of the overloaded functions, searching for one
6310 // whose type matches exactly.
6311 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006312 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6313 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006314 // C++0x [temp.arg.explicit]p3:
6315 // [...] In contexts where deduction is done and fails, or in contexts
6316 // where deduction is not done, if a template argument list is
6317 // specified and it, along with any default template arguments,
6318 // identifies a single function template specialization, then the
6319 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006320 FunctionTemplateDecl *FunctionTemplate
6321 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006322
6323 // C++ [over.over]p2:
6324 // If the name is a function template, template argument deduction is
6325 // done (14.8.2.2), and if the argument deduction succeeds, the
6326 // resulting template argument list is used to generate a single
6327 // function template specialization, which is added to the set of
6328 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006329 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006330 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006331 if (TemplateDeductionResult Result
6332 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6333 Specialization, Info)) {
6334 // FIXME: make a note of the failed deduction for diagnostics.
6335 (void)Result;
6336 continue;
6337 }
6338
6339 // Multiple matches; we can't resolve to a single declaration.
6340 if (Matched)
6341 return 0;
6342
6343 Matched = Specialization;
6344 }
6345
6346 return Matched;
6347}
6348
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006349/// \brief Add a single candidate to the overload set.
6350static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006351 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006352 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006353 Expr **Args, unsigned NumArgs,
6354 OverloadCandidateSet &CandidateSet,
6355 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006356 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006357 if (isa<UsingShadowDecl>(Callee))
6358 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6359
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006360 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006361 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006362 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006363 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006364 return;
John McCallba135432009-11-21 08:51:07 +00006365 }
6366
6367 if (FunctionTemplateDecl *FuncTemplate
6368 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006369 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6370 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006371 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006372 return;
6373 }
6374
6375 assert(false && "unhandled case in overloaded call candidate");
6376
6377 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006378}
6379
6380/// \brief Add the overload candidates named by callee and/or found by argument
6381/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006382void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006383 Expr **Args, unsigned NumArgs,
6384 OverloadCandidateSet &CandidateSet,
6385 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006386
6387#ifndef NDEBUG
6388 // Verify that ArgumentDependentLookup is consistent with the rules
6389 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006390 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006391 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6392 // and let Y be the lookup set produced by argument dependent
6393 // lookup (defined as follows). If X contains
6394 //
6395 // -- a declaration of a class member, or
6396 //
6397 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006398 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006399 //
6400 // -- a declaration that is neither a function or a function
6401 // template
6402 //
6403 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006404
John McCall3b4294e2009-12-16 12:17:52 +00006405 if (ULE->requiresADL()) {
6406 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6407 E = ULE->decls_end(); I != E; ++I) {
6408 assert(!(*I)->getDeclContext()->isRecord());
6409 assert(isa<UsingShadowDecl>(*I) ||
6410 !(*I)->getDeclContext()->isFunctionOrMethod());
6411 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006412 }
6413 }
6414#endif
6415
John McCall3b4294e2009-12-16 12:17:52 +00006416 // It would be nice to avoid this copy.
6417 TemplateArgumentListInfo TABuffer;
6418 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6419 if (ULE->hasExplicitTemplateArgs()) {
6420 ULE->copyTemplateArgumentsInto(TABuffer);
6421 ExplicitTemplateArgs = &TABuffer;
6422 }
6423
6424 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6425 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006426 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006427 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006428 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006429
John McCall3b4294e2009-12-16 12:17:52 +00006430 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006431 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6432 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006433 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006434 CandidateSet,
6435 PartialOverloading);
6436}
John McCall578b69b2009-12-16 08:11:27 +00006437
6438/// Attempts to recover from a call where no functions were found.
6439///
6440/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00006441static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006442BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006443 UnresolvedLookupExpr *ULE,
6444 SourceLocation LParenLoc,
6445 Expr **Args, unsigned NumArgs,
6446 SourceLocation *CommaLocs,
6447 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006448
6449 CXXScopeSpec SS;
6450 if (ULE->getQualifier()) {
6451 SS.setScopeRep(ULE->getQualifier());
6452 SS.setRange(ULE->getQualifierRange());
6453 }
6454
John McCall3b4294e2009-12-16 12:17:52 +00006455 TemplateArgumentListInfo TABuffer;
6456 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6457 if (ULE->hasExplicitTemplateArgs()) {
6458 ULE->copyTemplateArgumentsInto(TABuffer);
6459 ExplicitTemplateArgs = &TABuffer;
6460 }
6461
John McCall578b69b2009-12-16 08:11:27 +00006462 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6463 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006464 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorff331c12010-07-25 18:17:45 +00006465 return SemaRef.ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006466
John McCall3b4294e2009-12-16 12:17:52 +00006467 assert(!R.empty() && "lookup results empty despite recovery");
6468
6469 // Build an implicit member call if appropriate. Just drop the
6470 // casts and such from the call, we don't really care.
6471 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6472 if ((*R.begin())->isCXXClassMember())
6473 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6474 else if (ExplicitTemplateArgs)
6475 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6476 else
6477 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6478
6479 if (NewFn.isInvalid())
Douglas Gregorff331c12010-07-25 18:17:45 +00006480 return SemaRef.ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006481
6482 // This shouldn't cause an infinite loop because we're giving it
6483 // an expression with non-empty lookup results, which should never
6484 // end up here.
6485 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6486 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6487 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006488}
Douglas Gregord7a95972010-06-08 17:35:15 +00006489
Douglas Gregorf6b89692008-11-26 05:54:23 +00006490/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006491/// (which eventually refers to the declaration Func) and the call
6492/// arguments Args/NumArgs, attempt to resolve the function call down
6493/// to a specific function. If overload resolution succeeds, returns
6494/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006495/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006496/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00006497Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006498Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006499 SourceLocation LParenLoc,
6500 Expr **Args, unsigned NumArgs,
6501 SourceLocation *CommaLocs,
6502 SourceLocation RParenLoc) {
6503#ifndef NDEBUG
6504 if (ULE->requiresADL()) {
6505 // To do ADL, we must have found an unqualified name.
6506 assert(!ULE->getQualifier() && "qualified name with ADL");
6507
6508 // We don't perform ADL for implicit declarations of builtins.
6509 // Verify that this was correctly set up.
6510 FunctionDecl *F;
6511 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6512 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6513 F->getBuiltinID() && F->isImplicit())
6514 assert(0 && "performing ADL for builtin");
6515
6516 // We don't perform ADL in C.
6517 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6518 }
6519#endif
6520
John McCall5769d612010-02-08 23:07:23 +00006521 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006522
John McCall3b4294e2009-12-16 12:17:52 +00006523 // Add the functions denoted by the callee to the set of candidate
6524 // functions, including those from argument-dependent lookup.
6525 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006526
6527 // If we found nothing, try to recover.
6528 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6529 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006530 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006531 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006532 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006533
Douglas Gregorf6b89692008-11-26 05:54:23 +00006534 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006535 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006536 case OR_Success: {
6537 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006538 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006539 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006540 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006541 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6542 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006543
6544 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006545 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006546 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006547 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006548 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006549 break;
6550
6551 case OR_Ambiguous:
6552 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006553 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006554 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006555 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006556
6557 case OR_Deleted:
6558 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6559 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006560 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006561 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006562 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006563 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006564 }
6565
Douglas Gregorff331c12010-07-25 18:17:45 +00006566 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00006567 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006568}
6569
John McCall6e266892010-01-26 03:27:55 +00006570static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006571 return Functions.size() > 1 ||
6572 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6573}
6574
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006575/// \brief Create a unary operation that may resolve to an overloaded
6576/// operator.
6577///
6578/// \param OpLoc The location of the operator itself (e.g., '*').
6579///
6580/// \param OpcIn The UnaryOperator::Opcode that describes this
6581/// operator.
6582///
6583/// \param Functions The set of non-member functions that will be
6584/// considered by overload resolution. The caller needs to build this
6585/// set based on the context using, e.g.,
6586/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6587/// set should not contain any member functions; those will be added
6588/// by CreateOverloadedUnaryOp().
6589///
6590/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00006591Sema::OwningExprResult
6592Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6593 const UnresolvedSetImpl &Fns,
6594 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006595 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6596 Expr *Input = (Expr *)input.get();
6597
6598 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6599 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6600 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6601
6602 Expr *Args[2] = { Input, 0 };
6603 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006604
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006605 // For post-increment and post-decrement, add the implicit '0' as
6606 // the second argument, so that we know this is a post-increment or
6607 // post-decrement.
6608 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6609 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006610 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006611 SourceLocation());
6612 NumArgs = 2;
6613 }
6614
6615 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006616 if (Fns.empty())
6617 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6618 Opc,
6619 Context.DependentTy,
6620 OpLoc));
6621
John McCallc373d482010-01-27 01:50:18 +00006622 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006623 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006624 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006625 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006626 /*ADL*/ true, IsOverloaded(Fns),
6627 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006628 input.release();
6629 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6630 &Args[0], NumArgs,
6631 Context.DependentTy,
6632 OpLoc));
6633 }
6634
6635 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006636 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006637
6638 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006639 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006640
6641 // Add operator candidates that are member functions.
6642 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6643
John McCall6e266892010-01-26 03:27:55 +00006644 // Add candidates from ADL.
6645 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006646 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006647 /*ExplicitTemplateArgs*/ 0,
6648 CandidateSet);
6649
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006650 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006651 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006652
6653 // Perform overload resolution.
6654 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006655 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006656 case OR_Success: {
6657 // We found a built-in operator or an overloaded operator.
6658 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006659
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006660 if (FnDecl) {
6661 // We matched an overloaded operator. Build a call to that
6662 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006663
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006664 // Convert the arguments.
6665 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006666 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006667
John McCall6bb80172010-03-30 21:47:33 +00006668 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6669 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006670 return ExprError();
6671 } else {
6672 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00006673 OwningExprResult InputInit
6674 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006675 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006676 SourceLocation(),
6677 move(input));
6678 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006679 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006680
Douglas Gregore1a5c172009-12-23 17:40:29 +00006681 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006682 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006683 }
6684
John McCallb697e082010-05-06 18:15:07 +00006685 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6686
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006687 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006688 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006689
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006690 // Build the actual expression node.
6691 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6692 SourceLocation());
6693 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006694
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006695 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00006696 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00006697 ExprOwningPtr<CallExpr> TheCall(this,
6698 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00006699 Args, NumArgs, ResultTy, OpLoc));
John McCallb697e082010-05-06 18:15:07 +00006700
Anders Carlsson26a2a072009-10-13 21:19:37 +00006701 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6702 FnDecl))
6703 return ExprError();
6704
6705 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006706 } else {
6707 // We matched a built-in operator. Convert the arguments, then
6708 // break out so that we will build the appropriate built-in
6709 // operator node.
6710 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006711 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006712 return ExprError();
6713
6714 break;
6715 }
6716 }
6717
6718 case OR_No_Viable_Function:
6719 // No viable function; fall through to handling this as a
6720 // built-in operator, which will produce an error message for us.
6721 break;
6722
6723 case OR_Ambiguous:
6724 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6725 << UnaryOperator::getOpcodeStr(Opc)
6726 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006727 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006728 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006729 return ExprError();
6730
6731 case OR_Deleted:
6732 Diag(OpLoc, diag::err_ovl_deleted_oper)
6733 << Best->Function->isDeleted()
6734 << UnaryOperator::getOpcodeStr(Opc)
6735 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006736 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006737 return ExprError();
6738 }
6739
6740 // Either we found no viable overloaded operator or we matched a
6741 // built-in operator. In either case, fall through to trying to
6742 // build a built-in operation.
6743 input.release();
6744 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6745}
6746
Douglas Gregor063daf62009-03-13 18:40:31 +00006747/// \brief Create a binary operation that may resolve to an overloaded
6748/// operator.
6749///
6750/// \param OpLoc The location of the operator itself (e.g., '+').
6751///
6752/// \param OpcIn The BinaryOperator::Opcode that describes this
6753/// operator.
6754///
6755/// \param Functions The set of non-member functions that will be
6756/// considered by overload resolution. The caller needs to build this
6757/// set based on the context using, e.g.,
6758/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6759/// set should not contain any member functions; those will be added
6760/// by CreateOverloadedBinOp().
6761///
6762/// \param LHS Left-hand argument.
6763/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006764Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006765Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006766 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006767 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006768 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006769 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006770 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006771
6772 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6773 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6774 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6775
6776 // If either side is type-dependent, create an appropriate dependent
6777 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006778 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006779 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006780 // If there are no functions to store, just build a dependent
6781 // BinaryOperator or CompoundAssignment.
6782 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6783 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6784 Context.DependentTy, OpLoc));
6785
6786 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6787 Context.DependentTy,
6788 Context.DependentTy,
6789 Context.DependentTy,
6790 OpLoc));
6791 }
John McCall6e266892010-01-26 03:27:55 +00006792
6793 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006794 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006795 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006796 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006797 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006798 /*ADL*/ true, IsOverloaded(Fns),
6799 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006800 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006801 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006802 Context.DependentTy,
6803 OpLoc));
6804 }
6805
6806 // If this is the .* operator, which is not overloadable, just
6807 // create a built-in binary operator.
6808 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006809 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006810
Sebastian Redl275c2b42009-11-18 23:10:33 +00006811 // If this is the assignment operator, we only perform overload resolution
6812 // if the left-hand side is a class or enumeration type. This is actually
6813 // a hack. The standard requires that we do overload resolution between the
6814 // various built-in candidates, but as DR507 points out, this can lead to
6815 // problems. So we do it this way, which pretty much follows what GCC does.
6816 // Note that we go the traditional code path for compound assignment forms.
6817 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006818 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006819
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006820 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006821 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006822
6823 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006824 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006825
6826 // Add operator candidates that are member functions.
6827 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6828
John McCall6e266892010-01-26 03:27:55 +00006829 // Add candidates from ADL.
6830 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6831 Args, 2,
6832 /*ExplicitTemplateArgs*/ 0,
6833 CandidateSet);
6834
Douglas Gregor063daf62009-03-13 18:40:31 +00006835 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006836 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006837
6838 // Perform overload resolution.
6839 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006840 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006841 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006842 // We found a built-in operator or an overloaded operator.
6843 FunctionDecl *FnDecl = Best->Function;
6844
6845 if (FnDecl) {
6846 // We matched an overloaded operator. Build a call to that
6847 // operator.
6848
6849 // Convert the arguments.
6850 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006851 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006852 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006853
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006854 OwningExprResult Arg1
6855 = PerformCopyInitialization(
6856 InitializedEntity::InitializeParameter(
6857 FnDecl->getParamDecl(0)),
6858 SourceLocation(),
6859 Owned(Args[1]));
6860 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006861 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006862
Douglas Gregor5fccd362010-03-03 23:55:11 +00006863 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006864 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006865 return ExprError();
6866
6867 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006868 } else {
6869 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006870 OwningExprResult Arg0
6871 = PerformCopyInitialization(
6872 InitializedEntity::InitializeParameter(
6873 FnDecl->getParamDecl(0)),
6874 SourceLocation(),
6875 Owned(Args[0]));
6876 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006877 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006878
6879 OwningExprResult Arg1
6880 = PerformCopyInitialization(
6881 InitializedEntity::InitializeParameter(
6882 FnDecl->getParamDecl(1)),
6883 SourceLocation(),
6884 Owned(Args[1]));
6885 if (Arg1.isInvalid())
6886 return ExprError();
6887 Args[0] = LHS = Arg0.takeAs<Expr>();
6888 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006889 }
6890
John McCallb697e082010-05-06 18:15:07 +00006891 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6892
Douglas Gregor063daf62009-03-13 18:40:31 +00006893 // Determine the result type
6894 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006895 = FnDecl->getType()->getAs<FunctionType>()
6896 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00006897
6898 // Build the actual expression node.
6899 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006900 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006901 UsualUnaryConversions(FnExpr);
6902
Anders Carlsson15ea3782009-10-13 22:43:21 +00006903 ExprOwningPtr<CXXOperatorCallExpr>
6904 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6905 Args, 2, ResultTy,
6906 OpLoc));
6907
6908 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6909 FnDecl))
6910 return ExprError();
6911
6912 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006913 } else {
6914 // We matched a built-in operator. Convert the arguments, then
6915 // break out so that we will build the appropriate built-in
6916 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006917 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006918 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006919 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006920 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00006921 return ExprError();
6922
6923 break;
6924 }
6925 }
6926
Douglas Gregor33074752009-09-30 21:46:01 +00006927 case OR_No_Viable_Function: {
6928 // C++ [over.match.oper]p9:
6929 // If the operator is the operator , [...] and there are no
6930 // viable functions, then the operator is assumed to be the
6931 // built-in operator and interpreted according to clause 5.
6932 if (Opc == BinaryOperator::Comma)
6933 break;
6934
Sebastian Redl8593c782009-05-21 11:50:50 +00006935 // For class as left operand for assignment or compound assigment operator
6936 // do not fall through to handling in built-in, but report that no overloaded
6937 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00006938 OwningExprResult Result = ExprError();
6939 if (Args[0]->getType()->isRecordType() &&
6940 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00006941 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6942 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006943 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00006944 } else {
6945 // No viable function; try to create a built-in operation, which will
6946 // produce an error. Then, show the non-viable candidates.
6947 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00006948 }
Douglas Gregor33074752009-09-30 21:46:01 +00006949 assert(Result.isInvalid() &&
6950 "C++ binary operator overloading is missing candidates!");
6951 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00006952 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006953 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00006954 return move(Result);
6955 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006956
6957 case OR_Ambiguous:
6958 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6959 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006960 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006961 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006962 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006963 return ExprError();
6964
6965 case OR_Deleted:
6966 Diag(OpLoc, diag::err_ovl_deleted_oper)
6967 << Best->Function->isDeleted()
6968 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006969 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006970 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00006971 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00006972 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006973
Douglas Gregor33074752009-09-30 21:46:01 +00006974 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006975 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006976}
6977
Sebastian Redlf322ed62009-10-29 20:17:01 +00006978Action::OwningExprResult
6979Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6980 SourceLocation RLoc,
6981 ExprArg Base, ExprArg Idx) {
6982 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6983 static_cast<Expr*>(Idx.get()) };
6984 DeclarationName OpName =
6985 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6986
6987 // If either side is type-dependent, create an appropriate dependent
6988 // expression.
6989 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6990
John McCallc373d482010-01-27 01:50:18 +00006991 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006992 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006993 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006994 0, SourceRange(), OpName, LLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006995 /*ADL*/ true, /*Overloaded*/ false,
6996 UnresolvedSetIterator(),
6997 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00006998 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00006999
7000 Base.release();
7001 Idx.release();
7002 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7003 Args, 2,
7004 Context.DependentTy,
7005 RLoc));
7006 }
7007
7008 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007009 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007010
7011 // Subscript can only be overloaded as a member function.
7012
7013 // Add operator candidates that are member functions.
7014 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7015
7016 // Add builtin operator candidates.
7017 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7018
7019 // Perform overload resolution.
7020 OverloadCandidateSet::iterator Best;
7021 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7022 case OR_Success: {
7023 // We found a built-in operator or an overloaded operator.
7024 FunctionDecl *FnDecl = Best->Function;
7025
7026 if (FnDecl) {
7027 // We matched an overloaded operator. Build a call to that
7028 // operator.
7029
John McCall9aa472c2010-03-19 07:35:19 +00007030 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007031 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007032
Sebastian Redlf322ed62009-10-29 20:17:01 +00007033 // Convert the arguments.
7034 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007035 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007036 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007037 return ExprError();
7038
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007039 // Convert the arguments.
7040 OwningExprResult InputInit
7041 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7042 FnDecl->getParamDecl(0)),
7043 SourceLocation(),
7044 Owned(Args[1]));
7045 if (InputInit.isInvalid())
7046 return ExprError();
7047
7048 Args[1] = InputInit.takeAs<Expr>();
7049
Sebastian Redlf322ed62009-10-29 20:17:01 +00007050 // Determine the result type
7051 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007052 = FnDecl->getType()->getAs<FunctionType>()
7053 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007054
7055 // Build the actual expression node.
7056 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7057 LLoc);
7058 UsualUnaryConversions(FnExpr);
7059
7060 Base.release();
7061 Idx.release();
7062 ExprOwningPtr<CXXOperatorCallExpr>
7063 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7064 FnExpr, Args, 2,
7065 ResultTy, RLoc));
7066
7067 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7068 FnDecl))
7069 return ExprError();
7070
7071 return MaybeBindToTemporary(TheCall.release());
7072 } else {
7073 // We matched a built-in operator. Convert the arguments, then
7074 // break out so that we will build the appropriate built-in
7075 // operator node.
7076 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007077 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007078 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007079 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007080 return ExprError();
7081
7082 break;
7083 }
7084 }
7085
7086 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007087 if (CandidateSet.empty())
7088 Diag(LLoc, diag::err_ovl_no_oper)
7089 << Args[0]->getType() << /*subscript*/ 0
7090 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7091 else
7092 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7093 << Args[0]->getType()
7094 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007095 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00007096 "[]", LLoc);
7097 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007098 }
7099
7100 case OR_Ambiguous:
7101 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7102 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007103 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007104 "[]", LLoc);
7105 return ExprError();
7106
7107 case OR_Deleted:
7108 Diag(LLoc, diag::err_ovl_deleted_oper)
7109 << Best->Function->isDeleted() << "[]"
7110 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007111 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00007112 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007113 return ExprError();
7114 }
7115
7116 // We matched a built-in operator; build it.
7117 Base.release();
7118 Idx.release();
7119 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7120 Owned(Args[1]), RLoc);
7121}
7122
Douglas Gregor88a35142008-12-22 05:46:06 +00007123/// BuildCallToMemberFunction - Build a call to a member
7124/// function. MemExpr is the expression that refers to the member
7125/// function (and includes the object parameter), Args/NumArgs are the
7126/// arguments to the function call (not including the object
7127/// parameter). The caller needs to validate that the member
7128/// expression refers to a member function or an overloaded member
7129/// function.
John McCallaa81e162009-12-01 22:10:20 +00007130Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007131Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7132 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00007133 unsigned NumArgs, SourceLocation *CommaLocs,
7134 SourceLocation RParenLoc) {
7135 // Dig out the member expression. This holds both the object
7136 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007137 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7138
John McCall129e2df2009-11-30 22:42:35 +00007139 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007140 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007141 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007142 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007143 if (isa<MemberExpr>(NakedMemExpr)) {
7144 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007145 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007146 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007147 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007148 } else {
7149 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007150 Qualifier = UnresExpr->getQualifier();
7151
John McCall701c89e2009-12-03 04:06:58 +00007152 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007153
Douglas Gregor88a35142008-12-22 05:46:06 +00007154 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007155 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007156
John McCallaa81e162009-12-01 22:10:20 +00007157 // FIXME: avoid copy.
7158 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7159 if (UnresExpr->hasExplicitTemplateArgs()) {
7160 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7161 TemplateArgs = &TemplateArgsBuffer;
7162 }
7163
John McCall129e2df2009-11-30 22:42:35 +00007164 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7165 E = UnresExpr->decls_end(); I != E; ++I) {
7166
John McCall701c89e2009-12-03 04:06:58 +00007167 NamedDecl *Func = *I;
7168 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7169 if (isa<UsingShadowDecl>(Func))
7170 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7171
John McCall129e2df2009-11-30 22:42:35 +00007172 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007173 // If explicit template arguments were provided, we can't call a
7174 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007175 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007176 continue;
7177
John McCall9aa472c2010-03-19 07:35:19 +00007178 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007179 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007180 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007181 } else {
John McCall129e2df2009-11-30 22:42:35 +00007182 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007183 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007184 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007185 CandidateSet,
7186 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007187 }
Douglas Gregordec06662009-08-21 18:42:58 +00007188 }
Mike Stump1eb44332009-09-09 15:08:12 +00007189
John McCall129e2df2009-11-30 22:42:35 +00007190 DeclarationName DeclName = UnresExpr->getMemberName();
7191
Douglas Gregor88a35142008-12-22 05:46:06 +00007192 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00007193 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007194 case OR_Success:
7195 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007196 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007197 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007198 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007199 break;
7200
7201 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007202 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007203 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007204 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007205 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007206 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007207 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007208
7209 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007210 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007211 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007212 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007213 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007214 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007215
7216 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007217 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007218 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007219 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007220 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007221 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007222 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007223 }
7224
John McCall6bb80172010-03-30 21:47:33 +00007225 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007226
John McCallaa81e162009-12-01 22:10:20 +00007227 // If overload resolution picked a static member, build a
7228 // non-member call based on that function.
7229 if (Method->isStatic()) {
7230 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7231 Args, NumArgs, RParenLoc);
7232 }
7233
John McCall129e2df2009-11-30 22:42:35 +00007234 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007235 }
7236
7237 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00007238 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00007239 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00007240 NumArgs,
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007241 Method->getCallResultType(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007242 RParenLoc));
7243
Anders Carlssoneed3e692009-10-10 00:06:20 +00007244 // Check for a valid return type.
7245 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7246 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00007247 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007248
Douglas Gregor88a35142008-12-22 05:46:06 +00007249 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007250 // We only need to do this if there was actually an overload; otherwise
7251 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007252 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007253 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007254 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7255 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007256 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007257 MemExpr->setBase(ObjectArg);
7258
7259 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007260 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007261 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007262 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007263 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007264
Anders Carlssond406bf02009-08-16 01:56:34 +00007265 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00007266 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007267
John McCallaa81e162009-12-01 22:10:20 +00007268 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00007269}
7270
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007271/// BuildCallToObjectOfClassType - Build a call to an object of class
7272/// type (C++ [over.call.object]), which can end up invoking an
7273/// overloaded function call operator (@c operator()) or performing a
7274/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00007275Sema::ExprResult
7276Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007277 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007278 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00007279 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007280 SourceLocation RParenLoc) {
7281 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007282 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007283
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007284 // C++ [over.call.object]p1:
7285 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007286 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007287 // candidate functions includes at least the function call
7288 // operators of T. The function call operators of T are obtained by
7289 // ordinary lookup of the name operator() in the context of
7290 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007291 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007292 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007293
7294 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007295 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007296 << Object->getSourceRange()))
7297 return true;
7298
John McCalla24dc2e2009-11-17 02:14:36 +00007299 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7300 LookupQualifiedName(R, Record->getDecl());
7301 R.suppressDiagnostics();
7302
Douglas Gregor593564b2009-11-15 07:48:03 +00007303 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007304 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007305 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007306 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007307 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007308 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007309
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007310 // C++ [over.call.object]p2:
7311 // In addition, for each conversion function declared in T of the
7312 // form
7313 //
7314 // operator conversion-type-id () cv-qualifier;
7315 //
7316 // where cv-qualifier is the same cv-qualification as, or a
7317 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007318 // denotes the type "pointer to function of (P1,...,Pn) returning
7319 // R", or the type "reference to pointer to function of
7320 // (P1,...,Pn) returning R", or the type "reference to function
7321 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007322 // is also considered as a candidate function. Similarly,
7323 // surrogate call functions are added to the set of candidate
7324 // functions for each conversion function declared in an
7325 // accessible base class provided the function is not hidden
7326 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007327 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007328 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007329 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007330 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007331 NamedDecl *D = *I;
7332 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7333 if (isa<UsingShadowDecl>(D))
7334 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7335
Douglas Gregor4a27d702009-10-21 06:18:39 +00007336 // Skip over templated conversion functions; they aren't
7337 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007338 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007339 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007340
John McCall701c89e2009-12-03 04:06:58 +00007341 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007342
Douglas Gregor4a27d702009-10-21 06:18:39 +00007343 // Strip the reference type (if any) and then the pointer type (if
7344 // any) to get down to what might be a function type.
7345 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7346 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7347 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007348
Douglas Gregor4a27d702009-10-21 06:18:39 +00007349 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007350 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007351 Object->getType(), Args, NumArgs,
7352 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007353 }
Mike Stump1eb44332009-09-09 15:08:12 +00007354
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007355 // Perform overload resolution.
7356 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007357 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007358 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007359 // Overload resolution succeeded; we'll build the appropriate call
7360 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007361 break;
7362
7363 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007364 if (CandidateSet.empty())
7365 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7366 << Object->getType() << /*call*/ 1
7367 << Object->getSourceRange();
7368 else
7369 Diag(Object->getSourceRange().getBegin(),
7370 diag::err_ovl_no_viable_object_call)
7371 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007372 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007373 break;
7374
7375 case OR_Ambiguous:
7376 Diag(Object->getSourceRange().getBegin(),
7377 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007378 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007379 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007380 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007381
7382 case OR_Deleted:
7383 Diag(Object->getSourceRange().getBegin(),
7384 diag::err_ovl_deleted_object_call)
7385 << Best->Function->isDeleted()
7386 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007387 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007388 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007389 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007390
Douglas Gregorff331c12010-07-25 18:17:45 +00007391 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007392 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007393
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007394 if (Best->Function == 0) {
7395 // Since there is no function declaration, this is one of the
7396 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007397 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007398 = cast<CXXConversionDecl>(
7399 Best->Conversions[0].UserDefined.ConversionFunction);
7400
John McCall9aa472c2010-03-19 07:35:19 +00007401 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007402 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007403
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007404 // We selected one of the surrogate functions that converts the
7405 // object parameter to a function pointer. Perform the conversion
7406 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007407
7408 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007409 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007410 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7411 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007412
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007413 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00007414 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00007415 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007416 }
7417
John McCall9aa472c2010-03-19 07:35:19 +00007418 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007419 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007420
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007421 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7422 // that calls this method, using Object for the implicit object
7423 // parameter and passing along the remaining arguments.
7424 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007425 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007426
7427 unsigned NumArgsInProto = Proto->getNumArgs();
7428 unsigned NumArgsToCheck = NumArgs;
7429
7430 // Build the full argument list for the method call (the
7431 // implicit object parameter is placed at the beginning of the
7432 // list).
7433 Expr **MethodArgs;
7434 if (NumArgs < NumArgsInProto) {
7435 NumArgsToCheck = NumArgsInProto;
7436 MethodArgs = new Expr*[NumArgsInProto + 1];
7437 } else {
7438 MethodArgs = new Expr*[NumArgs + 1];
7439 }
7440 MethodArgs[0] = Object;
7441 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7442 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007443
7444 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007445 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007446 UsualUnaryConversions(NewFn);
7447
7448 // Once we've built TheCall, all of the expressions are properly
7449 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007450 QualType ResultTy = Method->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00007451 ExprOwningPtr<CXXOperatorCallExpr>
7452 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00007453 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00007454 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007455 delete [] MethodArgs;
7456
Anders Carlsson07d68f12009-10-13 21:49:31 +00007457 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7458 Method))
7459 return true;
7460
Douglas Gregor518fda12009-01-13 05:10:00 +00007461 // We may have default arguments. If so, we need to allocate more
7462 // slots in the call for them.
7463 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007464 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007465 else if (NumArgs > NumArgsInProto)
7466 NumArgsToCheck = NumArgsInProto;
7467
Chris Lattner312531a2009-04-12 08:11:20 +00007468 bool IsError = false;
7469
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007470 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007471 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007472 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007473 TheCall->setArg(0, Object);
7474
Chris Lattner312531a2009-04-12 08:11:20 +00007475
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007476 // Check the argument types.
7477 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007478 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007479 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007480 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007481
Douglas Gregor518fda12009-01-13 05:10:00 +00007482 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007483
7484 OwningExprResult InputInit
7485 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7486 Method->getParamDecl(i)),
7487 SourceLocation(), Owned(Arg));
7488
7489 IsError |= InputInit.isInvalid();
7490 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007491 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00007492 OwningExprResult DefArg
7493 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7494 if (DefArg.isInvalid()) {
7495 IsError = true;
7496 break;
7497 }
7498
7499 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007500 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007501
7502 TheCall->setArg(i + 1, Arg);
7503 }
7504
7505 // If this is a variadic call, handle args passed through "...".
7506 if (Proto->isVariadic()) {
7507 // Promote the arguments (C99 6.5.2.2p7).
7508 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7509 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007510 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007511 TheCall->setArg(i + 1, Arg);
7512 }
7513 }
7514
Chris Lattner312531a2009-04-12 08:11:20 +00007515 if (IsError) return true;
7516
Anders Carlssond406bf02009-08-16 01:56:34 +00007517 if (CheckFunctionCall(Method, TheCall.get()))
7518 return true;
7519
Douglas Gregoraa0be172010-04-13 15:50:39 +00007520 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007521}
7522
Douglas Gregor8ba10742008-11-20 16:27:02 +00007523/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007524/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007525/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007526Sema::OwningExprResult
7527Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7528 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007529 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007530
John McCall5769d612010-02-08 23:07:23 +00007531 SourceLocation Loc = Base->getExprLoc();
7532
Douglas Gregor8ba10742008-11-20 16:27:02 +00007533 // C++ [over.ref]p1:
7534 //
7535 // [...] An expression x->m is interpreted as (x.operator->())->m
7536 // for a class object x of type T if T::operator->() exists and if
7537 // the operator is selected as the best match function by the
7538 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007539 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007540 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007541 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007542
John McCall5769d612010-02-08 23:07:23 +00007543 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007544 PDiag(diag::err_typecheck_incomplete_tag)
7545 << Base->getSourceRange()))
7546 return ExprError();
7547
John McCalla24dc2e2009-11-17 02:14:36 +00007548 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7549 LookupQualifiedName(R, BaseRecord->getDecl());
7550 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007551
7552 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007553 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007554 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007555 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007556 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007557
7558 // Perform overload resolution.
7559 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007560 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007561 case OR_Success:
7562 // Overload resolution succeeded; we'll build the call below.
7563 break;
7564
7565 case OR_No_Viable_Function:
7566 if (CandidateSet.empty())
7567 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007568 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007569 else
7570 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007571 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007572 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007573 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007574
7575 case OR_Ambiguous:
7576 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007577 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007578 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007579 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007580
7581 case OR_Deleted:
7582 Diag(OpLoc, diag::err_ovl_deleted_oper)
7583 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007584 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007585 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007586 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007587 }
7588
John McCall9aa472c2010-03-19 07:35:19 +00007589 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007590 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007591
Douglas Gregor8ba10742008-11-20 16:27:02 +00007592 // Convert the object parameter.
7593 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007594 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7595 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007596 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007597
7598 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007599 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007600
7601 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007602 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7603 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007604 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007605
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007606 QualType ResultTy = Method->getCallResultType();
Anders Carlsson15ea3782009-10-13 22:43:21 +00007607 ExprOwningPtr<CXXOperatorCallExpr>
7608 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7609 &Base, 1, ResultTy, OpLoc));
7610
7611 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7612 Method))
7613 return ExprError();
7614 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007615}
7616
Douglas Gregor904eed32008-11-10 20:40:00 +00007617/// FixOverloadedFunctionReference - E is an expression that refers to
7618/// a C++ overloaded function (possibly with some parentheses and
7619/// perhaps a '&' around it). We have resolved the overloaded function
7620/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007621/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007622Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007623 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007624 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007625 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7626 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007627 if (SubExpr == PE->getSubExpr())
7628 return PE->Retain();
7629
7630 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7631 }
7632
7633 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007634 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7635 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007636 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007637 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007638 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00007639 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00007640 if (SubExpr == ICE->getSubExpr())
7641 return ICE->Retain();
7642
John McCallf871d0c2010-08-07 06:22:56 +00007643 return ImplicitCastExpr::Create(Context, ICE->getType(),
7644 ICE->getCastKind(),
7645 SubExpr, 0,
7646 ICE->getCategory());
Douglas Gregor699ee522009-11-20 19:42:02 +00007647 }
7648
7649 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007650 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007651 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7653 if (Method->isStatic()) {
7654 // Do nothing: static member functions aren't any different
7655 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007656 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007657 // Fix the sub expression, which really has to be an
7658 // UnresolvedLookupExpr holding an overloaded member function
7659 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007660 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7661 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007662 if (SubExpr == UnOp->getSubExpr())
7663 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007664
John McCallba135432009-11-21 08:51:07 +00007665 assert(isa<DeclRefExpr>(SubExpr)
7666 && "fixed to something other than a decl ref");
7667 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7668 && "fixed to a member ref with no nested name qualifier");
7669
7670 // We have taken the address of a pointer to member
7671 // function. Perform the computation here so that we get the
7672 // appropriate pointer to member type.
7673 QualType ClassType
7674 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7675 QualType MemPtrType
7676 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7677
7678 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7679 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007680 }
7681 }
John McCall6bb80172010-03-30 21:47:33 +00007682 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7683 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007684 if (SubExpr == UnOp->getSubExpr())
7685 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007686
Douglas Gregor699ee522009-11-20 19:42:02 +00007687 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7688 Context.getPointerType(SubExpr->getType()),
7689 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007690 }
John McCallba135432009-11-21 08:51:07 +00007691
7692 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007693 // FIXME: avoid copy.
7694 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007695 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007696 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7697 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007698 }
7699
John McCallba135432009-11-21 08:51:07 +00007700 return DeclRefExpr::Create(Context,
7701 ULE->getQualifier(),
7702 ULE->getQualifierRange(),
7703 Fn,
7704 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007705 Fn->getType(),
7706 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007707 }
7708
John McCall129e2df2009-11-30 22:42:35 +00007709 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007710 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007711 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7712 if (MemExpr->hasExplicitTemplateArgs()) {
7713 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7714 TemplateArgs = &TemplateArgsBuffer;
7715 }
John McCalld5532b62009-11-23 01:53:49 +00007716
John McCallaa81e162009-12-01 22:10:20 +00007717 Expr *Base;
7718
7719 // If we're filling in
7720 if (MemExpr->isImplicitAccess()) {
7721 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7722 return DeclRefExpr::Create(Context,
7723 MemExpr->getQualifier(),
7724 MemExpr->getQualifierRange(),
7725 Fn,
7726 MemExpr->getMemberLoc(),
7727 Fn->getType(),
7728 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007729 } else {
7730 SourceLocation Loc = MemExpr->getMemberLoc();
7731 if (MemExpr->getQualifier())
7732 Loc = MemExpr->getQualifierRange().getBegin();
7733 Base = new (Context) CXXThisExpr(Loc,
7734 MemExpr->getBaseType(),
7735 /*isImplicit=*/true);
7736 }
John McCallaa81e162009-12-01 22:10:20 +00007737 } else
7738 Base = MemExpr->getBase()->Retain();
7739
7740 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007741 MemExpr->isArrow(),
7742 MemExpr->getQualifier(),
7743 MemExpr->getQualifierRange(),
7744 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007745 Found,
John McCalld5532b62009-11-23 01:53:49 +00007746 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007747 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007748 Fn->getType());
7749 }
7750
Douglas Gregor699ee522009-11-20 19:42:02 +00007751 assert(false && "Invalid reference to overloaded function");
7752 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007753}
7754
Douglas Gregor20093b42009-12-09 23:02:17 +00007755Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00007756 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00007757 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007758 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007759}
7760
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007761} // end namespace clang