blob: 24fdff375721df26a183b4aad2e08de5ea4d59f7 [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:
318 case Sema::TDK_InconsistentQuals: {
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:
351 case Sema::TDK_InconsistentQuals:
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:
383 case Sema::TDK_InconsistentQuals:
384 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:
405 case Sema::TDK_InconsistentQuals:
406 return 0;
407
408 case Sema::TDK_SubstitutionFailure:
409 return static_cast<TemplateArgumentList*>(Data);
410
411 // Unhandled
412 case Sema::TDK_NonDeducedMismatch:
413 case Sema::TDK_FailedOverloadResolution:
414 break;
415 }
416
417 return 0;
418}
419
Douglas 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:
432 case Sema::TDK_InconsistentQuals:
433 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:
457 case Sema::TDK_InconsistentQuals:
458 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 McCall871b2e72009-12-09 03:35:25 +0000503Sema::OverloadKind
John McCall9f54ad42009-12-10 09:41:52 +0000504Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
505 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000506 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000507 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000508 NamedDecl *OldD = (*I)->getUnderlyingDecl();
509 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000510 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000511 Match = *I;
512 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000513 }
John McCall51fa86f2009-12-02 08:47:38 +0000514 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000515 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000516 Match = *I;
517 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000518 }
John McCall9f54ad42009-12-10 09:41:52 +0000519 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
520 // We can overload with these, which can show up when doing
521 // redeclaration checks for UsingDecls.
522 assert(Old.getLookupKind() == LookupUsingDeclName);
523 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
524 // Optimistically assume that an unresolved using decl will
525 // overload; if it doesn't, we'll have to diagnose during
526 // template instantiation.
527 } else {
John McCall68263142009-11-18 22:49:29 +0000528 // (C++ 13p1):
529 // Only function declarations can be overloaded; object and type
530 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000531 Match = *I;
532 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000533 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534 }
John McCall68263142009-11-18 22:49:29 +0000535
John McCall871b2e72009-12-09 03:35:25 +0000536 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000537}
538
539bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
540 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
541 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
542
543 // C++ [temp.fct]p2:
544 // A function template can be overloaded with other function templates
545 // and with normal (non-template) functions.
546 if ((OldTemplate == 0) != (NewTemplate == 0))
547 return true;
548
549 // Is the function New an overload of the function Old?
550 QualType OldQType = Context.getCanonicalType(Old->getType());
551 QualType NewQType = Context.getCanonicalType(New->getType());
552
553 // Compare the signatures (C++ 1.3.10) of the two functions to
554 // determine whether they are overloads. If we find any mismatch
555 // in the signature, they are overloads.
556
557 // If either of these functions is a K&R-style function (no
558 // prototype), then we consider them to have matching signatures.
559 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
560 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
561 return false;
562
563 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
564 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
565
566 // The signature of a function includes the types of its
567 // parameters (C++ 1.3.10), which includes the presence or absence
568 // of the ellipsis; see C++ DR 357).
569 if (OldQType != NewQType &&
570 (OldType->getNumArgs() != NewType->getNumArgs() ||
571 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000572 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000573 return true;
574
575 // C++ [temp.over.link]p4:
576 // The signature of a function template consists of its function
577 // signature, its return type and its template parameter list. The names
578 // of the template parameters are significant only for establishing the
579 // relationship between the template parameters and the rest of the
580 // signature.
581 //
582 // We check the return type and template parameter lists for function
583 // templates first; the remaining checks follow.
584 if (NewTemplate &&
585 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
586 OldTemplate->getTemplateParameters(),
587 false, TPL_TemplateMatch) ||
588 OldType->getResultType() != NewType->getResultType()))
589 return true;
590
591 // If the function is a class member, its signature includes the
592 // cv-qualifiers (if any) on the function itself.
593 //
594 // As part of this, also check whether one of the member functions
595 // is static, in which case they are not overloads (C++
596 // 13.1p2). While not part of the definition of the signature,
597 // this check is important to determine whether these functions
598 // can be overloaded.
599 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
600 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
601 if (OldMethod && NewMethod &&
602 !OldMethod->isStatic() && !NewMethod->isStatic() &&
603 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
604 return true;
605
606 // The signatures match; this is not an overload.
607 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000608}
609
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000610/// TryImplicitConversion - Attempt to perform an implicit conversion
611/// from the given expression (Expr) to the given type (ToType). This
612/// function returns an implicit conversion sequence that can be used
613/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614///
615/// void f(float f);
616/// void g(int i) { f(i); }
617///
618/// this routine would produce an implicit conversion sequence to
619/// describe the initialization of f from i, which will be a standard
620/// conversion sequence containing an lvalue-to-rvalue conversion (C++
621/// 4.1) followed by a floating-integral conversion (C++ 4.9).
622//
623/// Note that this routine only determines how the conversion can be
624/// performed; it does not actually perform the conversion. As such,
625/// it will not produce any diagnostics if no conversion is available,
626/// but will instead return an implicit conversion sequence of kind
627/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000628///
629/// If @p SuppressUserConversions, then user-defined conversions are
630/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000631/// If @p AllowExplicit, then explicit user-defined conversions are
632/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000633ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000634Sema::TryImplicitConversion(Expr* From, QualType ToType,
635 bool SuppressUserConversions,
Douglas Gregor74e386e2010-04-16 18:00:29 +0000636 bool AllowExplicit,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000637 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000638 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000639 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000640 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000641 return ICS;
642 }
643
644 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000645 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000646 return ICS;
647 }
648
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000649 if (SuppressUserConversions) {
650 // C++ [over.ics.user]p4:
651 // A conversion of an expression of class type to the same class
652 // type is given Exact Match rank, and a conversion of an
653 // expression of class type to a base class of that type is
654 // given Conversion rank, in spite of the fact that a copy/move
655 // constructor (i.e., a user-defined conversion function) is
656 // called for those cases.
657 QualType FromType = From->getType();
658 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
659 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
660 IsDerivedFrom(FromType, ToType))) {
661 // We're not in the case above, so there is no conversion that
662 // we can perform.
663 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
664 return ICS;
665 }
666
667 ICS.setStandard();
668 ICS.Standard.setAsIdentityConversion();
669 ICS.Standard.setFromType(FromType);
670 ICS.Standard.setAllToTypes(ToType);
671
672 // We don't actually check at this point whether there is a valid
673 // copy/move constructor, since overloading just assumes that it
674 // exists. When we actually perform initialization, we'll find the
675 // appropriate constructor to copy the returned object, if needed.
676 ICS.Standard.CopyConstructor = 0;
677
678 // Determine whether this is considered a derived-to-base conversion.
679 if (!Context.hasSameUnqualifiedType(FromType, ToType))
680 ICS.Standard.Second = ICK_Derived_To_Base;
681
682 return ICS;
683 }
684
685 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000686 OverloadCandidateSet Conversions(From->getExprLoc());
687 OverloadingResult UserDefResult
688 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000689 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000690
691 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000692 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000693 // C++ [over.ics.user]p4:
694 // A conversion of an expression of class type to the same class
695 // type is given Exact Match rank, and a conversion of an
696 // expression of class type to a base class of that type is
697 // given Conversion rank, in spite of the fact that a copy
698 // constructor (i.e., a user-defined conversion function) is
699 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000700 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000701 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000702 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000703 = Context.getCanonicalType(From->getType().getUnqualifiedType());
704 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000705 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000706 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000707 // Turn this into a "standard" conversion sequence, so that it
708 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000709 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000710 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000711 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000712 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000713 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000714 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000715 ICS.Standard.Second = ICK_Derived_To_Base;
716 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000717 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000718
719 // C++ [over.best.ics]p4:
720 // However, when considering the argument of a user-defined
721 // conversion function that is a candidate by 13.3.1.3 when
722 // invoked for the copying of the temporary in the second step
723 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
724 // 13.3.1.6 in all cases, only standard conversion sequences and
725 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000726 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000727 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000728 }
John McCallcefd3ad2010-01-13 22:30:33 +0000729 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000730 ICS.setAmbiguous();
731 ICS.Ambiguous.setFromType(From->getType());
732 ICS.Ambiguous.setToType(ToType);
733 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
734 Cand != Conversions.end(); ++Cand)
735 if (Cand->Viable)
736 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000737 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000738 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000739 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000740
741 return ICS;
742}
743
Douglas Gregor575c63a2010-04-16 22:27:05 +0000744/// PerformImplicitConversion - Perform an implicit conversion of the
745/// expression From to the type ToType. Returns true if there was an
746/// error, false otherwise. The expression From is replaced with the
747/// converted expression. Flavor is the kind of conversion we're
748/// performing, used in the error message. If @p AllowExplicit,
749/// explicit user-defined conversions are permitted.
750bool
751Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
752 AssignmentAction Action, bool AllowExplicit) {
753 ImplicitConversionSequence ICS;
754 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
755}
756
757bool
758Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
759 AssignmentAction Action, bool AllowExplicit,
760 ImplicitConversionSequence& ICS) {
761 ICS = TryImplicitConversion(From, ToType,
762 /*SuppressUserConversions=*/false,
763 AllowExplicit,
764 /*InOverloadResolution=*/false);
765 return PerformImplicitConversion(From, ToType, ICS, Action);
766}
767
Douglas Gregor43c79c22009-12-09 00:47:37 +0000768/// \brief Determine whether the conversion from FromType to ToType is a valid
769/// conversion that strips "noreturn" off the nested function type.
770static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
771 QualType ToType, QualType &ResultTy) {
772 if (Context.hasSameUnqualifiedType(FromType, ToType))
773 return false;
774
775 // Strip the noreturn off the type we're converting from; noreturn can
776 // safely be removed.
777 FromType = Context.getNoReturnType(FromType, false);
778 if (!Context.hasSameUnqualifiedType(FromType, ToType))
779 return false;
780
781 ResultTy = FromType;
782 return true;
783}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000784
785/// \brief Determine whether the conversion from FromType to ToType is a valid
786/// vector conversion.
787///
788/// \param ICK Will be set to the vector conversion kind, if this is a vector
789/// conversion.
790static bool IsVectorConversion(ASTContext &Context, QualType FromType,
791 QualType ToType, ImplicitConversionKind &ICK) {
792 // We need at least one of these types to be a vector type to have a vector
793 // conversion.
794 if (!ToType->isVectorType() && !FromType->isVectorType())
795 return false;
796
797 // Identical types require no conversions.
798 if (Context.hasSameUnqualifiedType(FromType, ToType))
799 return false;
800
801 // There are no conversions between extended vector types, only identity.
802 if (ToType->isExtVectorType()) {
803 // There are no conversions between extended vector types other than the
804 // identity conversion.
805 if (FromType->isExtVectorType())
806 return false;
807
808 // Vector splat from any arithmetic type to a vector.
809 if (!FromType->isVectorType() && FromType->isArithmeticType()) {
810 ICK = ICK_Vector_Splat;
811 return true;
812 }
813 }
814
815 // If lax vector conversions are permitted and the vector types are of the
816 // same size, we can perform the conversion.
817 if (Context.getLangOptions().LaxVectorConversions &&
818 FromType->isVectorType() && ToType->isVectorType() &&
819 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
820 ICK = ICK_Vector_Conversion;
821 return true;
822 }
823
824 return false;
825}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000826
Douglas Gregor60d62c22008-10-31 16:23:19 +0000827/// IsStandardConversion - Determines whether there is a standard
828/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
829/// expression From to the type ToType. Standard conversion sequences
830/// only consider non-class types; for conversions that involve class
831/// types, use TryImplicitConversion. If a conversion exists, SCS will
832/// contain the standard conversion sequence required to perform this
833/// conversion and this routine will return true. Otherwise, this
834/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000835bool
836Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000837 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000838 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000839 QualType FromType = From->getType();
840
Douglas Gregor60d62c22008-10-31 16:23:19 +0000841 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000842 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000843 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000844 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000845 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000846 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000847
Douglas Gregorf9201e02009-02-11 23:02:49 +0000848 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000849 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000850 if (FromType->isRecordType() || ToType->isRecordType()) {
851 if (getLangOptions().CPlusPlus)
852 return false;
853
Mike Stump1eb44332009-09-09 15:08:12 +0000854 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000855 }
856
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000857 // The first conversion can be an lvalue-to-rvalue conversion,
858 // array-to-pointer conversion, or function-to-pointer conversion
859 // (C++ 4p1).
860
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000861 if (FromType == Context.OverloadTy) {
862 DeclAccessPair AccessPair;
863 if (FunctionDecl *Fn
864 = ResolveAddressOfOverloadedFunction(From, ToType, false,
865 AccessPair)) {
866 // We were able to resolve the address of the overloaded function,
867 // so we can convert to the type of that function.
868 FromType = Fn->getType();
869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
870 if (!Method->isStatic()) {
871 Type *ClassType
872 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
873 FromType = Context.getMemberPointerType(FromType, ClassType);
874 }
875 }
876
877 // If the "from" expression takes the address of the overloaded
878 // function, update the type of the resulting expression accordingly.
879 if (FromType->getAs<FunctionType>())
880 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
881 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
882 FromType = Context.getPointerType(FromType);
883
884 // Check that we've computed the proper type after overload resolution.
885 assert(Context.hasSameType(FromType,
886 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
887 } else {
888 return false;
889 }
890 }
Mike Stump1eb44332009-09-09 15:08:12 +0000891 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000892 // An lvalue (3.10) of a non-function, non-array type T can be
893 // converted to an rvalue.
894 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000895 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000896 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000897 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000898 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000899
900 // If T is a non-class type, the type of the rvalue is the
901 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000902 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
903 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000904 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000905 } else if (FromType->isArrayType()) {
906 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000907 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000908
909 // An lvalue or rvalue of type "array of N T" or "array of unknown
910 // bound of T" can be converted to an rvalue of type "pointer to
911 // T" (C++ 4.2p1).
912 FromType = Context.getArrayDecayedType(FromType);
913
914 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
915 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000916 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000917
918 // For the purpose of ranking in overload resolution
919 // (13.3.3.1.1), this conversion is considered an
920 // array-to-pointer conversion followed by a qualification
921 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000922 SCS.Second = ICK_Identity;
923 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000924 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000925 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000926 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000927 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
928 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000929 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000930
931 // An lvalue of function type T can be converted to an rvalue of
932 // type "pointer to T." The result is a pointer to the
933 // function. (C++ 4.3p1).
934 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000935 } else {
936 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000937 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000938 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000939 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000940
941 // The second conversion can be an integral promotion, floating
942 // point promotion, integral conversion, floating point conversion,
943 // floating-integral conversion, pointer conversion,
944 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000945 // For overloading in C, this can also be a "compatible-type"
946 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000947 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000948 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000949 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000950 // The unqualified versions of the types are the same: there's no
951 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000952 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000953 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000954 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000955 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000956 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000957 } else if (IsFloatingPointPromotion(FromType, ToType)) {
958 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000959 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000960 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000961 } else if (IsComplexPromotion(FromType, ToType)) {
962 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000963 SCS.Second = ICK_Complex_Promotion;
964 FromType = ToType.getUnqualifiedType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000965 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +0000966 ToType->isIntegralType(Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000967 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000968 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000969 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000970 } else if (FromType->isComplexType() && ToType->isComplexType()) {
971 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000972 SCS.Second = ICK_Complex_Conversion;
973 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +0000974 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
975 (ToType->isComplexType() && FromType->isArithmeticType())) {
976 // Complex-real conversions (C99 6.3.1.7)
977 SCS.Second = ICK_Complex_Real;
978 FromType = ToType.getUnqualifiedType();
979 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
980 // Floating point conversions (C++ 4.8).
981 SCS.Second = ICK_Floating_Conversion;
982 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000983 } else if ((FromType->isFloatingType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +0000984 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000985 (FromType->isIntegralOrEnumerationType() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000986 ToType->isFloatingType())) {
987 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000988 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000989 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000990 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
991 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000992 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000993 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000994 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000995 } else if (IsMemberPointerConversion(From, FromType, ToType,
996 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000997 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000998 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000999 } else if (ToType->isBooleanType() &&
1000 (FromType->isArithmeticType() ||
1001 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001002 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001003 FromType->isBlockPointerType() ||
1004 FromType->isMemberPointerType() ||
1005 FromType->isNullPtrType())) {
1006 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001007 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001008 FromType = Context.BoolTy;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001009 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1010 SCS.Second = SecondICK;
1011 FromType = ToType.getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001012 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001013 Context.typesAreCompatible(ToType, FromType)) {
1014 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001015 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001016 FromType = ToType.getUnqualifiedType();
Douglas Gregor43c79c22009-12-09 00:47:37 +00001017 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1018 // Treat a conversion that strips "noreturn" as an identity conversion.
1019 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001020 } else {
1021 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001022 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001023 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001024 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001025
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001026 QualType CanonFrom;
1027 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +00001029 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001030 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001031 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001032 CanonFrom = Context.getCanonicalType(FromType);
1033 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001034 } else {
1035 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001036 SCS.Third = ICK_Identity;
1037
Mike Stump1eb44332009-09-09 15:08:12 +00001038 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001039 // [...] Any difference in top-level cv-qualification is
1040 // subsumed by the initialization itself and does not constitute
1041 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001042 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +00001043 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001044 if (CanonFrom.getLocalUnqualifiedType()
1045 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001046 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1047 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001048 FromType = ToType;
1049 CanonFrom = CanonTo;
1050 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001051 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001052 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001053
1054 // If we have not converted the argument type to the parameter type,
1055 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001056 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001057 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001058
Douglas Gregor60d62c22008-10-31 16:23:19 +00001059 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001060}
1061
1062/// IsIntegralPromotion - Determines whether the conversion from the
1063/// expression From (whose potentially-adjusted type is FromType) to
1064/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1065/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001066bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001067 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001068 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001069 if (!To) {
1070 return false;
1071 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001072
1073 // An rvalue of type char, signed char, unsigned char, short int, or
1074 // unsigned short int can be converted to an rvalue of type int if
1075 // int can represent all the values of the source type; otherwise,
1076 // the source rvalue can be converted to an rvalue of type unsigned
1077 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001078 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1079 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001080 if (// We can promote any signed, promotable integer type to an int
1081 (FromType->isSignedIntegerType() ||
1082 // We can promote any unsigned integer type whose size is
1083 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001084 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001085 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001086 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001087 }
1088
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001089 return To->getKind() == BuiltinType::UInt;
1090 }
1091
1092 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1093 // can be converted to an rvalue of the first of the following types
1094 // that can represent all the values of its underlying type: int,
1095 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001096
1097 // We pre-calculate the promotion type for enum types.
1098 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1099 if (ToType->isIntegerType())
1100 return Context.hasSameUnqualifiedType(ToType,
1101 FromEnumType->getDecl()->getPromotionType());
1102
1103 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001104 // Determine whether the type we're converting from is signed or
1105 // unsigned.
1106 bool FromIsSigned;
1107 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001108
1109 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1110 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001111
1112 // The types we'll try to promote to, in the appropriate
1113 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001114 QualType PromoteTypes[6] = {
1115 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001116 Context.LongTy, Context.UnsignedLongTy ,
1117 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001118 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001119 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001120 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1121 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001122 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001123 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1124 // We found the type that we can promote to. If this is the
1125 // type we wanted, we have a promotion. Otherwise, no
1126 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001127 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001128 }
1129 }
1130 }
1131
1132 // An rvalue for an integral bit-field (9.6) can be converted to an
1133 // rvalue of type int if int can represent all the values of the
1134 // bit-field; otherwise, it can be converted to unsigned int if
1135 // unsigned int can represent all the values of the bit-field. If
1136 // the bit-field is larger yet, no integral promotion applies to
1137 // it. If the bit-field has an enumerated type, it is treated as any
1138 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001139 // FIXME: We should delay checking of bit-fields until we actually perform the
1140 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001141 using llvm::APSInt;
1142 if (From)
1143 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001144 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001145 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001146 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1147 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1148 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Douglas Gregor86f19402008-12-20 23:49:58 +00001150 // Are we promoting to an int from a bitfield that fits in an int?
1151 if (BitWidth < ToSize ||
1152 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1153 return To->getKind() == BuiltinType::Int;
1154 }
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Douglas Gregor86f19402008-12-20 23:49:58 +00001156 // Are we promoting to an unsigned int from an unsigned bitfield
1157 // that fits into an unsigned int?
1158 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1159 return To->getKind() == BuiltinType::UInt;
1160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Douglas Gregor86f19402008-12-20 23:49:58 +00001162 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001163 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001166 // An rvalue of type bool can be converted to an rvalue of type int,
1167 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001168 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001169 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001170 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171
1172 return false;
1173}
1174
1175/// IsFloatingPointPromotion - Determines whether the conversion from
1176/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1177/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001178bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001179 /// An rvalue of type float can be converted to an rvalue of type
1180 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001181 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1182 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001183 if (FromBuiltin->getKind() == BuiltinType::Float &&
1184 ToBuiltin->getKind() == BuiltinType::Double)
1185 return true;
1186
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001187 // C99 6.3.1.5p1:
1188 // When a float is promoted to double or long double, or a
1189 // double is promoted to long double [...].
1190 if (!getLangOptions().CPlusPlus &&
1191 (FromBuiltin->getKind() == BuiltinType::Float ||
1192 FromBuiltin->getKind() == BuiltinType::Double) &&
1193 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1194 return true;
1195 }
1196
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001197 return false;
1198}
1199
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001200/// \brief Determine if a conversion is a complex promotion.
1201///
1202/// A complex promotion is defined as a complex -> complex conversion
1203/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001204/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001205bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001206 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001207 if (!FromComplex)
1208 return false;
1209
John McCall183700f2009-09-21 23:43:11 +00001210 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001211 if (!ToComplex)
1212 return false;
1213
1214 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001215 ToComplex->getElementType()) ||
1216 IsIntegralPromotion(0, FromComplex->getElementType(),
1217 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001218}
1219
Douglas Gregorcb7de522008-11-26 23:31:11 +00001220/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1221/// the pointer type FromPtr to a pointer to type ToPointee, with the
1222/// same type qualifiers as FromPtr has on its pointee type. ToType,
1223/// if non-empty, will be a pointer to ToType that may or may not have
1224/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001225static QualType
1226BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001227 QualType ToPointee, QualType ToType,
1228 ASTContext &Context) {
1229 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1230 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001231 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001232
1233 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001234 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001235 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001236 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001237 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001238
1239 // Build a pointer to ToPointee. It has the right qualifiers
1240 // already.
1241 return Context.getPointerType(ToPointee);
1242 }
1243
1244 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001245 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001246 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1247 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001248}
1249
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001250/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1251/// the FromType, which is an objective-c pointer, to ToType, which may or may
1252/// not have the right set of qualifiers.
1253static QualType
1254BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1255 QualType ToType,
1256 ASTContext &Context) {
1257 QualType CanonFromType = Context.getCanonicalType(FromType);
1258 QualType CanonToType = Context.getCanonicalType(ToType);
1259 Qualifiers Quals = CanonFromType.getQualifiers();
1260
1261 // Exact qualifier match -> return the pointer type we're converting to.
1262 if (CanonToType.getLocalQualifiers() == Quals)
1263 return ToType;
1264
1265 // Just build a canonical type that has the right qualifiers.
1266 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1267}
1268
Mike Stump1eb44332009-09-09 15:08:12 +00001269static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001270 bool InOverloadResolution,
1271 ASTContext &Context) {
1272 // Handle value-dependent integral null pointer constants correctly.
1273 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1274 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001275 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001276 return !InOverloadResolution;
1277
Douglas Gregorce940492009-09-25 04:25:58 +00001278 return Expr->isNullPointerConstant(Context,
1279 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1280 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001281}
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001283/// IsPointerConversion - Determines whether the conversion of the
1284/// expression From, which has the (possibly adjusted) type FromType,
1285/// can be converted to the type ToType via a pointer conversion (C++
1286/// 4.10). If so, returns true and places the converted type (that
1287/// might differ from ToType in its cv-qualifiers at some level) into
1288/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001289///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001290/// This routine also supports conversions to and from block pointers
1291/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1292/// pointers to interfaces. FIXME: Once we've determined the
1293/// appropriate overloading rules for Objective-C, we may want to
1294/// split the Objective-C checks into a different routine; however,
1295/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001296/// conversions, so for now they live here. IncompatibleObjC will be
1297/// set if the conversion is an allowed Objective-C conversion that
1298/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001299bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001300 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001301 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001302 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001303 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001304 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1305 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001306
Mike Stump1eb44332009-09-09 15:08:12 +00001307 // Conversion from a null pointer constant to any Objective-C pointer type.
1308 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001309 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001310 ConvertedType = ToType;
1311 return true;
1312 }
1313
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001314 // Blocks: Block pointers can be converted to void*.
1315 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001316 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001317 ConvertedType = ToType;
1318 return true;
1319 }
1320 // Blocks: A null pointer constant can be converted to a block
1321 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001322 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001323 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001324 ConvertedType = ToType;
1325 return true;
1326 }
1327
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001328 // If the left-hand-side is nullptr_t, the right side can be a null
1329 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001330 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001331 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001332 ConvertedType = ToType;
1333 return true;
1334 }
1335
Ted Kremenek6217b802009-07-29 21:53:49 +00001336 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001337 if (!ToTypePtr)
1338 return false;
1339
1340 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001341 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001342 ConvertedType = ToType;
1343 return true;
1344 }
Sebastian Redl07779722008-10-31 14:43:28 +00001345
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001346 // Beyond this point, both types need to be pointers
1347 // , including objective-c pointers.
1348 QualType ToPointeeType = ToTypePtr->getPointeeType();
1349 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1350 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1351 ToType, Context);
1352 return true;
1353
1354 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001355 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001356 if (!FromTypePtr)
1357 return false;
1358
1359 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001360
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001361 // An rvalue of type "pointer to cv T," where T is an object type,
1362 // can be converted to an rvalue of type "pointer to cv void" (C++
1363 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001364 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001365 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001366 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001367 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001368 return true;
1369 }
1370
Douglas Gregorf9201e02009-02-11 23:02:49 +00001371 // When we're overloading in C, we allow a special kind of pointer
1372 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001373 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001374 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001375 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001376 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001377 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001378 return true;
1379 }
1380
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001381 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001382 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001383 // An rvalue of type "pointer to cv D," where D is a class type,
1384 // can be converted to an rvalue of type "pointer to cv B," where
1385 // B is a base class (clause 10) of D. If B is an inaccessible
1386 // (clause 11) or ambiguous (10.2) base class of D, a program that
1387 // necessitates this conversion is ill-formed. The result of the
1388 // conversion is a pointer to the base class sub-object of the
1389 // derived class object. The null pointer value is converted to
1390 // the null pointer value of the destination type.
1391 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001392 // Note that we do not check for ambiguity or inaccessibility
1393 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001394 if (getLangOptions().CPlusPlus &&
1395 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001396 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001397 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001398 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001399 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001400 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001401 ToType, Context);
1402 return true;
1403 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001404
Douglas Gregorc7887512008-12-19 19:13:09 +00001405 return false;
1406}
1407
1408/// isObjCPointerConversion - Determines whether this is an
1409/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1410/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001411bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001412 QualType& ConvertedType,
1413 bool &IncompatibleObjC) {
1414 if (!getLangOptions().ObjC1)
1415 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001416
Steve Naroff14108da2009-07-10 23:34:53 +00001417 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001418 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001419 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001420 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001421
Steve Naroff14108da2009-07-10 23:34:53 +00001422 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001423 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001424 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001425 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001426 ConvertedType = ToType;
1427 return true;
1428 }
1429 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001430 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001431 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001432 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001433 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001434 ConvertedType = ToType;
1435 return true;
1436 }
1437 // Objective C++: We're able to convert from a pointer to an
1438 // interface to a pointer to a different interface.
1439 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001440 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1441 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1442 if (getLangOptions().CPlusPlus && LHS && RHS &&
1443 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1444 FromObjCPtr->getPointeeType()))
1445 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001446 ConvertedType = ToType;
1447 return true;
1448 }
1449
1450 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1451 // Okay: this is some kind of implicit downcast of Objective-C
1452 // interfaces, which is permitted. However, we're going to
1453 // complain about it.
1454 IncompatibleObjC = true;
1455 ConvertedType = FromType;
1456 return true;
1457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458 }
Steve Naroff14108da2009-07-10 23:34:53 +00001459 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001460 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001461 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001462 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001463 else if (const BlockPointerType *ToBlockPtr =
1464 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001465 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001466 // to a block pointer type.
1467 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1468 ConvertedType = ToType;
1469 return true;
1470 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001471 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001472 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001473 else if (FromType->getAs<BlockPointerType>() &&
1474 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1475 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001476 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001477 ConvertedType = ToType;
1478 return true;
1479 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001480 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001481 return false;
1482
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001483 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001484 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001485 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001486 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001487 FromPointeeType = FromBlockPtr->getPointeeType();
1488 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001489 return false;
1490
Douglas Gregorc7887512008-12-19 19:13:09 +00001491 // If we have pointers to pointers, recursively check whether this
1492 // is an Objective-C conversion.
1493 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1494 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1495 IncompatibleObjC)) {
1496 // We always complain about this conversion.
1497 IncompatibleObjC = true;
1498 ConvertedType = ToType;
1499 return true;
1500 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001501 // Allow conversion of pointee being objective-c pointer to another one;
1502 // as in I* to id.
1503 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1504 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1505 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1506 IncompatibleObjC)) {
1507 ConvertedType = ToType;
1508 return true;
1509 }
1510
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001511 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001512 // differences in the argument and result types are in Objective-C
1513 // pointer conversions. If so, we permit the conversion (but
1514 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001515 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001516 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001517 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001518 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001519 if (FromFunctionType && ToFunctionType) {
1520 // If the function types are exactly the same, this isn't an
1521 // Objective-C pointer conversion.
1522 if (Context.getCanonicalType(FromPointeeType)
1523 == Context.getCanonicalType(ToPointeeType))
1524 return false;
1525
1526 // Perform the quick checks that will tell us whether these
1527 // function types are obviously different.
1528 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1529 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1530 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1531 return false;
1532
1533 bool HasObjCConversion = false;
1534 if (Context.getCanonicalType(FromFunctionType->getResultType())
1535 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1536 // Okay, the types match exactly. Nothing to do.
1537 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1538 ToFunctionType->getResultType(),
1539 ConvertedType, IncompatibleObjC)) {
1540 // Okay, we have an Objective-C pointer conversion.
1541 HasObjCConversion = true;
1542 } else {
1543 // Function types are too different. Abort.
1544 return false;
1545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Douglas Gregorc7887512008-12-19 19:13:09 +00001547 // Check argument types.
1548 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1549 ArgIdx != NumArgs; ++ArgIdx) {
1550 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1551 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1552 if (Context.getCanonicalType(FromArgType)
1553 == Context.getCanonicalType(ToArgType)) {
1554 // Okay, the types match exactly. Nothing to do.
1555 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1556 ConvertedType, IncompatibleObjC)) {
1557 // Okay, we have an Objective-C pointer conversion.
1558 HasObjCConversion = true;
1559 } else {
1560 // Argument types are too different. Abort.
1561 return false;
1562 }
1563 }
1564
1565 if (HasObjCConversion) {
1566 // We had an Objective-C conversion. Allow this pointer
1567 // conversion, but complain about it.
1568 ConvertedType = ToType;
1569 IncompatibleObjC = true;
1570 return true;
1571 }
1572 }
1573
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001574 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001575}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001576
1577/// FunctionArgTypesAreEqual - This routine checks two function proto types
1578/// for equlity of their argument types. Caller has already checked that
1579/// they have same number of arguments. This routine assumes that Objective-C
1580/// pointer types which only differ in their protocol qualifiers are equal.
1581bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1582 FunctionProtoType* NewType){
1583 if (!getLangOptions().ObjC1)
1584 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1585 NewType->arg_type_begin());
1586
1587 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1588 N = NewType->arg_type_begin(),
1589 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1590 QualType ToType = (*O);
1591 QualType FromType = (*N);
1592 if (ToType != FromType) {
1593 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1594 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001595 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1596 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1597 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1598 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001599 continue;
1600 }
John McCallc12c5bb2010-05-15 11:32:37 +00001601 else if (const ObjCObjectPointerType *PTTo =
1602 ToType->getAs<ObjCObjectPointerType>()) {
1603 if (const ObjCObjectPointerType *PTFr =
1604 FromType->getAs<ObjCObjectPointerType>())
1605 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1606 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001607 }
1608 return false;
1609 }
1610 }
1611 return true;
1612}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001613
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001614/// CheckPointerConversion - Check the pointer conversion from the
1615/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001616/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001617/// conversions for which IsPointerConversion has already returned
1618/// true. It returns true and produces a diagnostic if there was an
1619/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001620bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001621 CastExpr::CastKind &Kind,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001622 CXXBaseSpecifierArray& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001623 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001624 QualType FromType = From->getType();
1625
Douglas Gregord7a95972010-06-08 17:35:15 +00001626 if (CXXBoolLiteralExpr* LitBool
1627 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1628 if (LitBool->getValue() == false)
1629 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1630 << ToType;
1631
Ted Kremenek6217b802009-07-29 21:53:49 +00001632 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1633 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001634 QualType FromPointeeType = FromPtrType->getPointeeType(),
1635 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001636
Douglas Gregor5fccd362010-03-03 23:55:11 +00001637 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1638 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001639 // We must have a derived-to-base conversion. Check an
1640 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001641 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1642 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001643 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001644 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001645 return true;
1646
1647 // The conversion was successful.
1648 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001649 }
1650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001652 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001653 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001654 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001655 // Objective-C++ conversions are always okay.
1656 // FIXME: We should have a different class of conversions for the
1657 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001658 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001659 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001660
Steve Naroff14108da2009-07-10 23:34:53 +00001661 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001662 return false;
1663}
1664
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001665/// IsMemberPointerConversion - Determines whether the conversion of the
1666/// expression From, which has the (possibly adjusted) type FromType, can be
1667/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1668/// If so, returns true and places the converted type (that might differ from
1669/// ToType in its cv-qualifiers at some level) into ConvertedType.
1670bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001671 QualType ToType,
1672 bool InOverloadResolution,
1673 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001674 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001675 if (!ToTypePtr)
1676 return false;
1677
1678 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001679 if (From->isNullPointerConstant(Context,
1680 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1681 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001682 ConvertedType = ToType;
1683 return true;
1684 }
1685
1686 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001687 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001688 if (!FromTypePtr)
1689 return false;
1690
1691 // A pointer to member of B can be converted to a pointer to member of D,
1692 // where D is derived from B (C++ 4.11p2).
1693 QualType FromClass(FromTypePtr->getClass(), 0);
1694 QualType ToClass(ToTypePtr->getClass(), 0);
1695 // FIXME: What happens when these are dependent? Is this function even called?
1696
1697 if (IsDerivedFrom(ToClass, FromClass)) {
1698 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1699 ToClass.getTypePtr());
1700 return true;
1701 }
1702
1703 return false;
1704}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001705
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001706/// CheckMemberPointerConversion - Check the member pointer conversion from the
1707/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001708/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001709/// for which IsMemberPointerConversion has already returned true. It returns
1710/// true and produces a diagnostic if there was an error, or returns false
1711/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001712bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001713 CastExpr::CastKind &Kind,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001714 CXXBaseSpecifierArray &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001715 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001716 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001717 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001718 if (!FromPtrType) {
1719 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001720 assert(From->isNullPointerConstant(Context,
1721 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001722 "Expr must be null pointer constant!");
1723 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001724 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001725 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001726
Ted Kremenek6217b802009-07-29 21:53:49 +00001727 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001728 assert(ToPtrType && "No member pointer cast has a target type "
1729 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001730
Sebastian Redl21593ac2009-01-28 18:33:18 +00001731 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1732 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001733
Sebastian Redl21593ac2009-01-28 18:33:18 +00001734 // FIXME: What about dependent types?
1735 assert(FromClass->isRecordType() && "Pointer into non-class.");
1736 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001737
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001738 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001739 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001740 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1741 assert(DerivationOkay &&
1742 "Should not have been called if derivation isn't OK.");
1743 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001744
Sebastian Redl21593ac2009-01-28 18:33:18 +00001745 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1746 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001747 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1748 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1749 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1750 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001751 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001752
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001753 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001754 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1755 << FromClass << ToClass << QualType(VBase, 0)
1756 << From->getSourceRange();
1757 return true;
1758 }
1759
John McCall6b2accb2010-02-10 09:31:12 +00001760 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001761 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1762 Paths.front(),
1763 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001764
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001765 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001766 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001767 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001768 return false;
1769}
1770
Douglas Gregor98cd5992008-10-21 23:43:52 +00001771/// IsQualificationConversion - Determines whether the conversion from
1772/// an rvalue of type FromType to ToType is a qualification conversion
1773/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001774bool
1775Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001776 FromType = Context.getCanonicalType(FromType);
1777 ToType = Context.getCanonicalType(ToType);
1778
1779 // If FromType and ToType are the same type, this is not a
1780 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001781 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001782 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001783
Douglas Gregor98cd5992008-10-21 23:43:52 +00001784 // (C++ 4.4p4):
1785 // A conversion can add cv-qualifiers at levels other than the first
1786 // in multi-level pointers, subject to the following rules: [...]
1787 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001788 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001789 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001790 // Within each iteration of the loop, we check the qualifiers to
1791 // determine if this still looks like a qualification
1792 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001793 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001794 // until there are no more pointers or pointers-to-members left to
1795 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001796 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001797
1798 // -- for every j > 0, if const is in cv 1,j then const is in cv
1799 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001800 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001801 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Douglas Gregor98cd5992008-10-21 23:43:52 +00001803 // -- if the cv 1,j and cv 2,j are different, then const is in
1804 // every cv for 0 < k < j.
1805 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001806 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001807 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Douglas Gregor98cd5992008-10-21 23:43:52 +00001809 // Keep track of whether all prior cv-qualifiers in the "to" type
1810 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001811 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001812 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001813 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001814
1815 // We are left with FromType and ToType being the pointee types
1816 // after unwrapping the original FromType and ToType the same number
1817 // of types. If we unwrapped any pointers, and if FromType and
1818 // ToType have the same unqualified type (since we checked
1819 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001820 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001821}
1822
Douglas Gregor734d9862009-01-30 23:27:23 +00001823/// Determines whether there is a user-defined conversion sequence
1824/// (C++ [over.ics.user]) that converts expression From to the type
1825/// ToType. If such a conversion exists, User will contain the
1826/// user-defined conversion sequence that performs such a conversion
1827/// and this routine will return true. Otherwise, this routine returns
1828/// false and User is unspecified.
1829///
Douglas Gregor734d9862009-01-30 23:27:23 +00001830/// \param AllowExplicit true if the conversion should consider C++0x
1831/// "explicit" conversion functions as well as non-explicit conversion
1832/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor20093b42009-12-09 23:02:17 +00001833OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1834 UserDefinedConversionSequence& User,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001835 OverloadCandidateSet& CandidateSet,
1836 bool AllowExplicit) {
1837 // Whether we will only visit constructors.
1838 bool ConstructorsOnly = false;
1839
1840 // If the type we are conversion to is a class type, enumerate its
1841 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001842 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001843 // C++ [over.match.ctor]p1:
1844 // When objects of class type are direct-initialized (8.5), or
1845 // copy-initialized from an expression of the same or a
1846 // derived class type (8.5), overload resolution selects the
1847 // constructor. [...] For copy-initialization, the candidate
1848 // functions are all the converting constructors (12.3.1) of
1849 // that class. The argument list is the expression-list within
1850 // the parentheses of the initializer.
1851 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1852 (From->getType()->getAs<RecordType>() &&
1853 IsDerivedFrom(From->getType(), ToType)))
1854 ConstructorsOnly = true;
1855
Douglas Gregor393896f2009-11-05 13:06:35 +00001856 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1857 // We're not going to find any constructors.
1858 } else if (CXXRecordDecl *ToRecordDecl
1859 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001860 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001861 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001862 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001863 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001864 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001865 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001866 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001867 NamedDecl *D = *Con;
1868 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1869
Douglas Gregordec06662009-08-21 18:42:58 +00001870 // Find the constructor (which may be a template).
1871 CXXConstructorDecl *Constructor = 0;
1872 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001873 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001874 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001875 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001876 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1877 else
John McCall9aa472c2010-03-19 07:35:19 +00001878 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001879
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001880 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001881 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001882 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001883 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001884 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001885 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001886 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001887 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001888 // Allow one user-defined conversion when user specifies a
1889 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001890 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001891 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001892 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001893 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001894 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001895 }
1896 }
1897
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001898 // Enumerate conversion functions, if we're allowed to.
1899 if (ConstructorsOnly) {
Mike Stump1eb44332009-09-09 15:08:12 +00001900 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001901 PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001902 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001903 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001904 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001905 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001906 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1907 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001908 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001909 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001910 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001911 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001912 DeclAccessPair FoundDecl = I.getPair();
1913 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001914 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1915 if (isa<UsingShadowDecl>(D))
1916 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1917
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001918 CXXConversionDecl *Conv;
1919 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001920 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1921 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001922 else
John McCall32daa422010-03-31 01:36:47 +00001923 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001924
1925 if (AllowExplicit || !Conv->isExplicit()) {
1926 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001927 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001928 ActingContext, From, ToType,
1929 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001930 else
John McCall9aa472c2010-03-19 07:35:19 +00001931 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001932 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001933 }
1934 }
1935 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001936 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001937
1938 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001939 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001940 case OR_Success:
1941 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001942 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001943 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1944 // C++ [over.ics.user]p1:
1945 // If the user-defined conversion is specified by a
1946 // constructor (12.3.1), the initial standard conversion
1947 // sequence converts the source type to the type required by
1948 // the argument of the constructor.
1949 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001950 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001951 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001952 User.EllipsisConversion = true;
1953 else {
1954 User.Before = Best->Conversions[0].Standard;
1955 User.EllipsisConversion = false;
1956 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001957 User.ConversionFunction = Constructor;
1958 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001959 User.After.setFromType(
1960 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001961 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001962 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001963 } else if (CXXConversionDecl *Conversion
1964 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1965 // C++ [over.ics.user]p1:
1966 //
1967 // [...] If the user-defined conversion is specified by a
1968 // conversion function (12.3.2), the initial standard
1969 // conversion sequence converts the source type to the
1970 // implicit object parameter of the conversion function.
1971 User.Before = Best->Conversions[0].Standard;
1972 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001973 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001974
1975 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001976 // The second standard conversion sequence converts the
1977 // result of the user-defined conversion to the target type
1978 // for the sequence. Since an implicit conversion sequence
1979 // is an initialization, the special rules for
1980 // initialization by user-defined conversion apply when
1981 // selecting the best user-defined conversion for a
1982 // user-defined conversion sequence (see 13.3.3 and
1983 // 13.3.3.1).
1984 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001985 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001986 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001987 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001988 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001989 }
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Douglas Gregor60d62c22008-10-31 16:23:19 +00001991 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001992 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001993 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001994 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001995 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001996
1997 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001998 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001999 }
2000
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002001 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002002}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002003
2004bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002005Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002006 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002007 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002008 OverloadingResult OvResult =
2009 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002010 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002011 if (OvResult == OR_Ambiguous)
2012 Diag(From->getSourceRange().getBegin(),
2013 diag::err_typecheck_ambiguous_condition)
2014 << From->getType() << ToType << From->getSourceRange();
2015 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2016 Diag(From->getSourceRange().getBegin(),
2017 diag::err_typecheck_nonviable_condition)
2018 << From->getType() << ToType << From->getSourceRange();
2019 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002020 return false;
John McCallcbce6062010-01-12 07:18:19 +00002021 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002022 return true;
2023}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002024
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002025/// CompareImplicitConversionSequences - Compare two implicit
2026/// conversion sequences to determine whether one is better than the
2027/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00002028ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002029Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2030 const ImplicitConversionSequence& ICS2)
2031{
2032 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2033 // conversion sequences (as defined in 13.3.3.1)
2034 // -- a standard conversion sequence (13.3.3.1.1) is a better
2035 // conversion sequence than a user-defined conversion sequence or
2036 // an ellipsis conversion sequence, and
2037 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2038 // conversion sequence than an ellipsis conversion sequence
2039 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002040 //
John McCall1d318332010-01-12 00:44:57 +00002041 // C++0x [over.best.ics]p10:
2042 // For the purpose of ranking implicit conversion sequences as
2043 // described in 13.3.3.2, the ambiguous conversion sequence is
2044 // treated as a user-defined sequence that is indistinguishable
2045 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002046 if (ICS1.getKindRank() < ICS2.getKindRank())
2047 return ImplicitConversionSequence::Better;
2048 else if (ICS2.getKindRank() < ICS1.getKindRank())
2049 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002050
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002051 // The following checks require both conversion sequences to be of
2052 // the same kind.
2053 if (ICS1.getKind() != ICS2.getKind())
2054 return ImplicitConversionSequence::Indistinguishable;
2055
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002056 // Two implicit conversion sequences of the same form are
2057 // indistinguishable conversion sequences unless one of the
2058 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002059 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002060 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002061 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002062 // User-defined conversion sequence U1 is a better conversion
2063 // sequence than another user-defined conversion sequence U2 if
2064 // they contain the same user-defined conversion function or
2065 // constructor and if the second standard conversion sequence of
2066 // U1 is better than the second standard conversion sequence of
2067 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002068 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002069 ICS2.UserDefined.ConversionFunction)
2070 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2071 ICS2.UserDefined.After);
2072 }
2073
2074 return ImplicitConversionSequence::Indistinguishable;
2075}
2076
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002077static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2078 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2079 Qualifiers Quals;
2080 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2081 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2082 }
2083
2084 return Context.hasSameUnqualifiedType(T1, T2);
2085}
2086
Douglas Gregorad323a82010-01-27 03:51:04 +00002087// Per 13.3.3.2p3, compare the given standard conversion sequences to
2088// determine if one is a proper subset of the other.
2089static ImplicitConversionSequence::CompareKind
2090compareStandardConversionSubsets(ASTContext &Context,
2091 const StandardConversionSequence& SCS1,
2092 const StandardConversionSequence& SCS2) {
2093 ImplicitConversionSequence::CompareKind Result
2094 = ImplicitConversionSequence::Indistinguishable;
2095
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002096 // the identity conversion sequence is considered to be a subsequence of
2097 // any non-identity conversion sequence
2098 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2099 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2100 return ImplicitConversionSequence::Better;
2101 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2102 return ImplicitConversionSequence::Worse;
2103 }
2104
Douglas Gregorad323a82010-01-27 03:51:04 +00002105 if (SCS1.Second != SCS2.Second) {
2106 if (SCS1.Second == ICK_Identity)
2107 Result = ImplicitConversionSequence::Better;
2108 else if (SCS2.Second == ICK_Identity)
2109 Result = ImplicitConversionSequence::Worse;
2110 else
2111 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002112 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002113 return ImplicitConversionSequence::Indistinguishable;
2114
2115 if (SCS1.Third == SCS2.Third) {
2116 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2117 : ImplicitConversionSequence::Indistinguishable;
2118 }
2119
2120 if (SCS1.Third == ICK_Identity)
2121 return Result == ImplicitConversionSequence::Worse
2122 ? ImplicitConversionSequence::Indistinguishable
2123 : ImplicitConversionSequence::Better;
2124
2125 if (SCS2.Third == ICK_Identity)
2126 return Result == ImplicitConversionSequence::Better
2127 ? ImplicitConversionSequence::Indistinguishable
2128 : ImplicitConversionSequence::Worse;
2129
2130 return ImplicitConversionSequence::Indistinguishable;
2131}
2132
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002133/// CompareStandardConversionSequences - Compare two standard
2134/// conversion sequences to determine whether one is better than the
2135/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002136ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002137Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2138 const StandardConversionSequence& SCS2)
2139{
2140 // Standard conversion sequence S1 is a better conversion sequence
2141 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2142
2143 // -- S1 is a proper subsequence of S2 (comparing the conversion
2144 // sequences in the canonical form defined by 13.3.3.1.1,
2145 // excluding any Lvalue Transformation; the identity conversion
2146 // sequence is considered to be a subsequence of any
2147 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002148 if (ImplicitConversionSequence::CompareKind CK
2149 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2150 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002151
2152 // -- the rank of S1 is better than the rank of S2 (by the rules
2153 // defined below), or, if not that,
2154 ImplicitConversionRank Rank1 = SCS1.getRank();
2155 ImplicitConversionRank Rank2 = SCS2.getRank();
2156 if (Rank1 < Rank2)
2157 return ImplicitConversionSequence::Better;
2158 else if (Rank2 < Rank1)
2159 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002160
Douglas Gregor57373262008-10-22 14:17:15 +00002161 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2162 // are indistinguishable unless one of the following rules
2163 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Douglas Gregor57373262008-10-22 14:17:15 +00002165 // A conversion that is not a conversion of a pointer, or
2166 // pointer to member, to bool is better than another conversion
2167 // that is such a conversion.
2168 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2169 return SCS2.isPointerConversionToBool()
2170 ? ImplicitConversionSequence::Better
2171 : ImplicitConversionSequence::Worse;
2172
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002173 // C++ [over.ics.rank]p4b2:
2174 //
2175 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002176 // conversion of B* to A* is better than conversion of B* to
2177 // void*, and conversion of A* to void* is better than conversion
2178 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002179 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002180 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002181 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002182 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002183 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2184 // Exactly one of the conversion sequences is a conversion to
2185 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002186 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2187 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002188 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2189 // Neither conversion sequence converts to a void pointer; compare
2190 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002191 if (ImplicitConversionSequence::CompareKind DerivedCK
2192 = CompareDerivedToBaseConversions(SCS1, SCS2))
2193 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002194 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2195 // Both conversion sequences are conversions to void
2196 // pointers. Compare the source types to determine if there's an
2197 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002198 QualType FromType1 = SCS1.getFromType();
2199 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002200
2201 // Adjust the types we're converting from via the array-to-pointer
2202 // conversion, if we need to.
2203 if (SCS1.First == ICK_Array_To_Pointer)
2204 FromType1 = Context.getArrayDecayedType(FromType1);
2205 if (SCS2.First == ICK_Array_To_Pointer)
2206 FromType2 = Context.getArrayDecayedType(FromType2);
2207
Douglas Gregor01919692009-12-13 21:37:05 +00002208 QualType FromPointee1
2209 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2210 QualType FromPointee2
2211 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002212
Douglas Gregor01919692009-12-13 21:37:05 +00002213 if (IsDerivedFrom(FromPointee2, FromPointee1))
2214 return ImplicitConversionSequence::Better;
2215 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2216 return ImplicitConversionSequence::Worse;
2217
2218 // Objective-C++: If one interface is more specific than the
2219 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002220 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2221 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002222 if (FromIface1 && FromIface1) {
2223 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2224 return ImplicitConversionSequence::Better;
2225 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2226 return ImplicitConversionSequence::Worse;
2227 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002228 }
Douglas Gregor57373262008-10-22 14:17:15 +00002229
2230 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2231 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002232 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00002233 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002234 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002235
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002236 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002237 // C++0x [over.ics.rank]p3b4:
2238 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2239 // implicit object parameter of a non-static member function declared
2240 // without a ref-qualifier, and S1 binds an rvalue reference to an
2241 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002242 // FIXME: We don't know if we're dealing with the implicit object parameter,
2243 // or if the member function in this case has a ref qualifier.
2244 // (Of course, we don't have ref qualifiers yet.)
2245 if (SCS1.RRefBinding != SCS2.RRefBinding)
2246 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2247 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002248
2249 // C++ [over.ics.rank]p3b4:
2250 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2251 // which the references refer are the same type except for
2252 // top-level cv-qualifiers, and the type to which the reference
2253 // initialized by S2 refers is more cv-qualified than the type
2254 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002255 QualType T1 = SCS1.getToType(2);
2256 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002257 T1 = Context.getCanonicalType(T1);
2258 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002259 Qualifiers T1Quals, T2Quals;
2260 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2261 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2262 if (UnqualT1 == UnqualT2) {
2263 // If the type is an array type, promote the element qualifiers to the type
2264 // for comparison.
2265 if (isa<ArrayType>(T1) && T1Quals)
2266 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2267 if (isa<ArrayType>(T2) && T2Quals)
2268 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002269 if (T2.isMoreQualifiedThan(T1))
2270 return ImplicitConversionSequence::Better;
2271 else if (T1.isMoreQualifiedThan(T2))
2272 return ImplicitConversionSequence::Worse;
2273 }
2274 }
Douglas Gregor57373262008-10-22 14:17:15 +00002275
2276 return ImplicitConversionSequence::Indistinguishable;
2277}
2278
2279/// CompareQualificationConversions - Compares two standard conversion
2280/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002281/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2282ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00002283Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00002284 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002285 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002286 // -- S1 and S2 differ only in their qualification conversion and
2287 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2288 // cv-qualification signature of type T1 is a proper subset of
2289 // the cv-qualification signature of type T2, and S1 is not the
2290 // deprecated string literal array-to-pointer conversion (4.2).
2291 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2292 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2293 return ImplicitConversionSequence::Indistinguishable;
2294
2295 // FIXME: the example in the standard doesn't use a qualification
2296 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002297 QualType T1 = SCS1.getToType(2);
2298 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00002299 T1 = Context.getCanonicalType(T1);
2300 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002301 Qualifiers T1Quals, T2Quals;
2302 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2303 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002304
2305 // If the types are the same, we won't learn anything by unwrapped
2306 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002307 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002308 return ImplicitConversionSequence::Indistinguishable;
2309
Chandler Carruth28e318c2009-12-29 07:16:59 +00002310 // If the type is an array type, promote the element qualifiers to the type
2311 // for comparison.
2312 if (isa<ArrayType>(T1) && T1Quals)
2313 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2314 if (isa<ArrayType>(T2) && T2Quals)
2315 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2316
Mike Stump1eb44332009-09-09 15:08:12 +00002317 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002318 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002319 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002320 // Within each iteration of the loop, we check the qualifiers to
2321 // determine if this still looks like a qualification
2322 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002323 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002324 // until there are no more pointers or pointers-to-members left
2325 // to unwrap. This essentially mimics what
2326 // IsQualificationConversion does, but here we're checking for a
2327 // strict subset of qualifiers.
2328 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2329 // The qualifiers are the same, so this doesn't tell us anything
2330 // about how the sequences rank.
2331 ;
2332 else if (T2.isMoreQualifiedThan(T1)) {
2333 // T1 has fewer qualifiers, so it could be the better sequence.
2334 if (Result == ImplicitConversionSequence::Worse)
2335 // Neither has qualifiers that are a subset of the other's
2336 // qualifiers.
2337 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Douglas Gregor57373262008-10-22 14:17:15 +00002339 Result = ImplicitConversionSequence::Better;
2340 } else if (T1.isMoreQualifiedThan(T2)) {
2341 // T2 has fewer qualifiers, so it could be the better sequence.
2342 if (Result == ImplicitConversionSequence::Better)
2343 // Neither has qualifiers that are a subset of the other's
2344 // qualifiers.
2345 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Douglas Gregor57373262008-10-22 14:17:15 +00002347 Result = ImplicitConversionSequence::Worse;
2348 } else {
2349 // Qualifiers are disjoint.
2350 return ImplicitConversionSequence::Indistinguishable;
2351 }
2352
2353 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002354 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002355 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002356 }
2357
Douglas Gregor57373262008-10-22 14:17:15 +00002358 // Check that the winning standard conversion sequence isn't using
2359 // the deprecated string literal array to pointer conversion.
2360 switch (Result) {
2361 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002362 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002363 Result = ImplicitConversionSequence::Indistinguishable;
2364 break;
2365
2366 case ImplicitConversionSequence::Indistinguishable:
2367 break;
2368
2369 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002370 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002371 Result = ImplicitConversionSequence::Indistinguishable;
2372 break;
2373 }
2374
2375 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002376}
2377
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002378/// CompareDerivedToBaseConversions - Compares two standard conversion
2379/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002380/// various kinds of derived-to-base conversions (C++
2381/// [over.ics.rank]p4b3). As part of these checks, we also look at
2382/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002383ImplicitConversionSequence::CompareKind
2384Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2385 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002386 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002387 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002388 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002389 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002390
2391 // Adjust the types we're converting from via the array-to-pointer
2392 // conversion, if we need to.
2393 if (SCS1.First == ICK_Array_To_Pointer)
2394 FromType1 = Context.getArrayDecayedType(FromType1);
2395 if (SCS2.First == ICK_Array_To_Pointer)
2396 FromType2 = Context.getArrayDecayedType(FromType2);
2397
2398 // Canonicalize all of the types.
2399 FromType1 = Context.getCanonicalType(FromType1);
2400 ToType1 = Context.getCanonicalType(ToType1);
2401 FromType2 = Context.getCanonicalType(FromType2);
2402 ToType2 = Context.getCanonicalType(ToType2);
2403
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002404 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002405 //
2406 // If class B is derived directly or indirectly from class A and
2407 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002408 //
2409 // For Objective-C, we let A, B, and C also be Objective-C
2410 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002411
2412 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002413 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002414 SCS2.Second == ICK_Pointer_Conversion &&
2415 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2416 FromType1->isPointerType() && FromType2->isPointerType() &&
2417 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002418 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002419 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002420 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002421 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002422 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002423 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002424 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002425 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002426
John McCallc12c5bb2010-05-15 11:32:37 +00002427 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2428 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2429 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2430 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002431
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002432 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002433 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2434 if (IsDerivedFrom(ToPointee1, ToPointee2))
2435 return ImplicitConversionSequence::Better;
2436 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2437 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002438
2439 if (ToIface1 && ToIface2) {
2440 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2441 return ImplicitConversionSequence::Better;
2442 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2443 return ImplicitConversionSequence::Worse;
2444 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002445 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002446
2447 // -- conversion of B* to A* is better than conversion of C* to A*,
2448 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2449 if (IsDerivedFrom(FromPointee2, FromPointee1))
2450 return ImplicitConversionSequence::Better;
2451 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2452 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002453
Douglas Gregorcb7de522008-11-26 23:31:11 +00002454 if (FromIface1 && FromIface2) {
2455 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2456 return ImplicitConversionSequence::Better;
2457 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2458 return ImplicitConversionSequence::Worse;
2459 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002460 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002461 }
2462
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002463 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002464 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2465 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2466 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2467 const MemberPointerType * FromMemPointer1 =
2468 FromType1->getAs<MemberPointerType>();
2469 const MemberPointerType * ToMemPointer1 =
2470 ToType1->getAs<MemberPointerType>();
2471 const MemberPointerType * FromMemPointer2 =
2472 FromType2->getAs<MemberPointerType>();
2473 const MemberPointerType * ToMemPointer2 =
2474 ToType2->getAs<MemberPointerType>();
2475 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2476 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2477 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2478 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2479 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2480 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2481 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2482 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002483 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002484 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2485 if (IsDerivedFrom(ToPointee1, ToPointee2))
2486 return ImplicitConversionSequence::Worse;
2487 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2488 return ImplicitConversionSequence::Better;
2489 }
2490 // conversion of B::* to C::* is better than conversion of A::* to C::*
2491 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2492 if (IsDerivedFrom(FromPointee1, FromPointee2))
2493 return ImplicitConversionSequence::Better;
2494 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2495 return ImplicitConversionSequence::Worse;
2496 }
2497 }
2498
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002499 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002500 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002501 // -- binding of an expression of type C to a reference of type
2502 // B& is better than binding an expression of type C to a
2503 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002504 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2505 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002506 if (IsDerivedFrom(ToType1, ToType2))
2507 return ImplicitConversionSequence::Better;
2508 else if (IsDerivedFrom(ToType2, ToType1))
2509 return ImplicitConversionSequence::Worse;
2510 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002511
Douglas Gregor225c41e2008-11-03 19:09:14 +00002512 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002513 // -- binding of an expression of type B to a reference of type
2514 // A& is better than binding an expression of type C to a
2515 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002516 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2517 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002518 if (IsDerivedFrom(FromType2, FromType1))
2519 return ImplicitConversionSequence::Better;
2520 else if (IsDerivedFrom(FromType1, FromType2))
2521 return ImplicitConversionSequence::Worse;
2522 }
2523 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002524
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002525 return ImplicitConversionSequence::Indistinguishable;
2526}
2527
Douglas Gregorabe183d2010-04-13 16:31:36 +00002528/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2529/// determine whether they are reference-related,
2530/// reference-compatible, reference-compatible with added
2531/// qualification, or incompatible, for use in C++ initialization by
2532/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2533/// type, and the first type (T1) is the pointee type of the reference
2534/// type being initialized.
2535Sema::ReferenceCompareResult
2536Sema::CompareReferenceRelationship(SourceLocation Loc,
2537 QualType OrigT1, QualType OrigT2,
2538 bool& DerivedToBase) {
2539 assert(!OrigT1->isReferenceType() &&
2540 "T1 must be the pointee type of the reference type");
2541 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2542
2543 QualType T1 = Context.getCanonicalType(OrigT1);
2544 QualType T2 = Context.getCanonicalType(OrigT2);
2545 Qualifiers T1Quals, T2Quals;
2546 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2547 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2548
2549 // C++ [dcl.init.ref]p4:
2550 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2551 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2552 // T1 is a base class of T2.
2553 if (UnqualT1 == UnqualT2)
2554 DerivedToBase = false;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002555 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002556 IsDerivedFrom(UnqualT2, UnqualT1))
2557 DerivedToBase = true;
2558 else
2559 return Ref_Incompatible;
2560
2561 // At this point, we know that T1 and T2 are reference-related (at
2562 // least).
2563
2564 // If the type is an array type, promote the element qualifiers to the type
2565 // for comparison.
2566 if (isa<ArrayType>(T1) && T1Quals)
2567 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2568 if (isa<ArrayType>(T2) && T2Quals)
2569 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2570
2571 // C++ [dcl.init.ref]p4:
2572 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2573 // reference-related to T2 and cv1 is the same cv-qualification
2574 // as, or greater cv-qualification than, cv2. For purposes of
2575 // overload resolution, cases for which cv1 is greater
2576 // cv-qualification than cv2 are identified as
2577 // reference-compatible with added qualification (see 13.3.3.2).
2578 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2579 return Ref_Compatible;
2580 else if (T1.isMoreQualifiedThan(T2))
2581 return Ref_Compatible_With_Added_Qualification;
2582 else
2583 return Ref_Related;
2584}
2585
2586/// \brief Compute an implicit conversion sequence for reference
2587/// initialization.
2588static ImplicitConversionSequence
2589TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2590 SourceLocation DeclLoc,
2591 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002592 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002593 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2594
2595 // Most paths end in a failed conversion.
2596 ImplicitConversionSequence ICS;
2597 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2598
2599 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2600 QualType T2 = Init->getType();
2601
2602 // If the initializer is the address of an overloaded function, try
2603 // to resolve the overloaded function. If all goes well, T2 is the
2604 // type of the resulting function.
2605 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2606 DeclAccessPair Found;
2607 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2608 false, Found))
2609 T2 = Fn->getType();
2610 }
2611
2612 // Compute some basic properties of the types and the initializer.
2613 bool isRValRef = DeclType->isRValueReferenceType();
2614 bool DerivedToBase = false;
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002615 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002616 Sema::ReferenceCompareResult RefRelationship
2617 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2618
Douglas Gregorabe183d2010-04-13 16:31:36 +00002619
2620 // C++ [over.ics.ref]p3:
2621 // Except for an implicit object parameter, for which see 13.3.1,
2622 // a standard conversion sequence cannot be formed if it requires
2623 // binding an lvalue reference to non-const to an rvalue or
2624 // binding an rvalue reference to an lvalue.
Douglas Gregor66821b52010-04-18 09:22:00 +00002625 //
2626 // FIXME: DPG doesn't trust this code. It seems far too early to
2627 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregorabe183d2010-04-13 16:31:36 +00002628 if (isRValRef && InitLvalue == Expr::LV_Valid)
2629 return ICS;
2630
Douglas Gregor66821b52010-04-18 09:22:00 +00002631 // C++0x [dcl.init.ref]p16:
2632 // A reference to type "cv1 T1" is initialized by an expression
2633 // of type "cv2 T2" as follows:
2634
2635 // -- If the initializer expression
Douglas Gregorabe183d2010-04-13 16:31:36 +00002636 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2637 // reference-compatible with "cv2 T2," or
2638 //
2639 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2640 if (InitLvalue == Expr::LV_Valid &&
2641 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2642 // C++ [over.ics.ref]p1:
2643 // When a parameter of reference type binds directly (8.5.3)
2644 // to an argument expression, the implicit conversion sequence
2645 // is the identity conversion, unless the argument expression
2646 // has a type that is a derived class of the parameter type,
2647 // in which case the implicit conversion sequence is a
2648 // derived-to-base Conversion (13.3.3.1).
2649 ICS.setStandard();
2650 ICS.Standard.First = ICK_Identity;
2651 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2652 ICS.Standard.Third = ICK_Identity;
2653 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2654 ICS.Standard.setToType(0, T2);
2655 ICS.Standard.setToType(1, T1);
2656 ICS.Standard.setToType(2, T1);
2657 ICS.Standard.ReferenceBinding = true;
2658 ICS.Standard.DirectBinding = true;
2659 ICS.Standard.RRefBinding = false;
2660 ICS.Standard.CopyConstructor = 0;
2661
2662 // Nothing more to do: the inaccessibility/ambiguity check for
2663 // derived-to-base conversions is suppressed when we're
2664 // computing the implicit conversion sequence (C++
2665 // [over.best.ics]p2).
2666 return ICS;
2667 }
2668
2669 // -- has a class type (i.e., T2 is a class type), where T1 is
2670 // not reference-related to T2, and can be implicitly
2671 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2672 // is reference-compatible with "cv3 T3" 92) (this
2673 // conversion is selected by enumerating the applicable
2674 // conversion functions (13.3.1.6) and choosing the best
2675 // one through overload resolution (13.3)),
2676 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2677 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2678 RefRelationship == Sema::Ref_Incompatible) {
2679 CXXRecordDecl *T2RecordDecl
2680 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2681
2682 OverloadCandidateSet CandidateSet(DeclLoc);
2683 const UnresolvedSetImpl *Conversions
2684 = T2RecordDecl->getVisibleConversionFunctions();
2685 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2686 E = Conversions->end(); I != E; ++I) {
2687 NamedDecl *D = *I;
2688 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2689 if (isa<UsingShadowDecl>(D))
2690 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2691
2692 FunctionTemplateDecl *ConvTemplate
2693 = dyn_cast<FunctionTemplateDecl>(D);
2694 CXXConversionDecl *Conv;
2695 if (ConvTemplate)
2696 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2697 else
2698 Conv = cast<CXXConversionDecl>(D);
2699
2700 // If the conversion function doesn't return a reference type,
2701 // it can't be considered for this conversion.
2702 if (Conv->getConversionType()->isLValueReferenceType() &&
2703 (AllowExplicit || !Conv->isExplicit())) {
2704 if (ConvTemplate)
2705 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2706 Init, DeclType, CandidateSet);
2707 else
2708 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2709 DeclType, CandidateSet);
2710 }
2711 }
2712
2713 OverloadCandidateSet::iterator Best;
2714 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2715 case OR_Success:
2716 // C++ [over.ics.ref]p1:
2717 //
2718 // [...] If the parameter binds directly to the result of
2719 // applying a conversion function to the argument
2720 // expression, the implicit conversion sequence is a
2721 // user-defined conversion sequence (13.3.3.1.2), with the
2722 // second standard conversion sequence either an identity
2723 // conversion or, if the conversion function returns an
2724 // entity of a type that is a derived class of the parameter
2725 // type, a derived-to-base Conversion.
2726 if (!Best->FinalConversion.DirectBinding)
2727 break;
2728
2729 ICS.setUserDefined();
2730 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2731 ICS.UserDefined.After = Best->FinalConversion;
2732 ICS.UserDefined.ConversionFunction = Best->Function;
2733 ICS.UserDefined.EllipsisConversion = false;
2734 assert(ICS.UserDefined.After.ReferenceBinding &&
2735 ICS.UserDefined.After.DirectBinding &&
2736 "Expected a direct reference binding!");
2737 return ICS;
2738
2739 case OR_Ambiguous:
2740 ICS.setAmbiguous();
2741 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2742 Cand != CandidateSet.end(); ++Cand)
2743 if (Cand->Viable)
2744 ICS.Ambiguous.addConversion(Cand->Function);
2745 return ICS;
2746
2747 case OR_No_Viable_Function:
2748 case OR_Deleted:
2749 // There was no suitable conversion, or we found a deleted
2750 // conversion; continue with other checks.
2751 break;
2752 }
2753 }
2754
2755 // -- Otherwise, the reference shall be to a non-volatile const
2756 // type (i.e., cv1 shall be const), or the reference shall be an
2757 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor66821b52010-04-18 09:22:00 +00002758 //
2759 // We actually handle one oddity of C++ [over.ics.ref] at this
2760 // point, which is that, due to p2 (which short-circuits reference
2761 // binding by only attempting a simple conversion for non-direct
2762 // bindings) and p3's strange wording, we allow a const volatile
2763 // reference to bind to an rvalue. Hence the check for the presence
2764 // of "const" rather than checking for "const" being the only
2765 // qualifier.
2766 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00002767 return ICS;
2768
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002769 // -- if T2 is a class type and
2770 // -- the initializer expression is an rvalue and "cv1 T1"
2771 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002772 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002773 // -- T1 is not reference-related to T2 and the initializer
2774 // expression can be implicitly converted to an rvalue
2775 // of type "cv3 T3" (this conversion is selected by
2776 // enumerating the applicable conversion functions
2777 // (13.3.1.6) and choosing the best one through overload
2778 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002779 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002780 // then the reference is bound to the initializer
2781 // expression rvalue in the first case and to the object
2782 // that is the result of the conversion in the second case
2783 // (or, in either case, to the appropriate base class
2784 // subobject of the object).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002785 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002786 // We're only checking the first case here, which is a direct
2787 // binding in C++0x but not in C++03.
Douglas Gregorabe183d2010-04-13 16:31:36 +00002788 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2789 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2790 ICS.setStandard();
2791 ICS.Standard.First = ICK_Identity;
2792 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2793 ICS.Standard.Third = ICK_Identity;
2794 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2795 ICS.Standard.setToType(0, T2);
2796 ICS.Standard.setToType(1, T1);
2797 ICS.Standard.setToType(2, T1);
2798 ICS.Standard.ReferenceBinding = true;
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002799 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002800 ICS.Standard.RRefBinding = isRValRef;
2801 ICS.Standard.CopyConstructor = 0;
2802 return ICS;
2803 }
2804
2805 // -- Otherwise, a temporary of type "cv1 T1" is created and
2806 // initialized from the initializer expression using the
2807 // rules for a non-reference copy initialization (8.5). The
2808 // reference is then bound to the temporary. If T1 is
2809 // reference-related to T2, cv1 must be the same
2810 // cv-qualification as, or greater cv-qualification than,
2811 // cv2; otherwise, the program is ill-formed.
2812 if (RefRelationship == Sema::Ref_Related) {
2813 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2814 // we would be reference-compatible or reference-compatible with
2815 // added qualification. But that wasn't the case, so the reference
2816 // initialization fails.
2817 return ICS;
2818 }
2819
2820 // If at least one of the types is a class type, the types are not
2821 // related, and we aren't allowed any user conversions, the
2822 // reference binding fails. This case is important for breaking
2823 // recursion, since TryImplicitConversion below will attempt to
2824 // create a temporary through the use of a copy constructor.
2825 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2826 (T1->isRecordType() || T2->isRecordType()))
2827 return ICS;
2828
2829 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00002830 // When a parameter of reference type is not bound directly to
2831 // an argument expression, the conversion sequence is the one
2832 // required to convert the argument expression to the
2833 // underlying type of the reference according to
2834 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2835 // to copy-initializing a temporary of the underlying type with
2836 // the argument expression. Any difference in top-level
2837 // cv-qualification is subsumed by the initialization itself
2838 // and does not constitute a conversion.
2839 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2840 /*AllowExplicit=*/false,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002841 /*InOverloadResolution=*/false);
2842
2843 // Of course, that's still a reference binding.
2844 if (ICS.isStandard()) {
2845 ICS.Standard.ReferenceBinding = true;
2846 ICS.Standard.RRefBinding = isRValRef;
2847 } else if (ICS.isUserDefined()) {
2848 ICS.UserDefined.After.ReferenceBinding = true;
2849 ICS.UserDefined.After.RRefBinding = isRValRef;
2850 }
2851 return ICS;
2852}
2853
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002854/// TryCopyInitialization - Try to copy-initialize a value of type
2855/// ToType from the expression From. Return the implicit conversion
2856/// sequence required to pass this argument, which may be a bad
2857/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002858/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00002859/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00002860static ImplicitConversionSequence
2861TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00002862 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002863 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002864 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00002865 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002866 /*FIXME:*/From->getLocStart(),
2867 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002868 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002869
Douglas Gregor74eb6582010-04-16 17:51:22 +00002870 return S.TryImplicitConversion(From, ToType,
2871 SuppressUserConversions,
2872 /*AllowExplicit=*/false,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002873 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002874}
2875
Douglas Gregor96176b32008-11-18 23:14:02 +00002876/// TryObjectArgumentInitialization - Try to initialize the object
2877/// parameter of the given member function (@c Method) from the
2878/// expression @p From.
2879ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002880Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002881 CXXMethodDecl *Method,
2882 CXXRecordDecl *ActingContext) {
2883 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002884 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2885 // const volatile object.
2886 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2887 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2888 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002889
2890 // Set up the conversion sequence as a "bad" conversion, to allow us
2891 // to exit early.
2892 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002893
2894 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002895 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002896 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002897 FromType = PT->getPointeeType();
2898
2899 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002900
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002901 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002902 // where X is the class of which the function is a member
2903 // (C++ [over.match.funcs]p4). However, when finding an implicit
2904 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002905 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002906 // (C++ [over.match.funcs]p5). We perform a simplified version of
2907 // reference binding here, that allows class rvalues to bind to
2908 // non-constant references.
2909
2910 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2911 // with the implicit object parameter (C++ [over.match.funcs]p5).
2912 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002913 if (ImplicitParamType.getCVRQualifiers()
2914 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002915 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002916 ICS.setBad(BadConversionSequence::bad_qualifiers,
2917 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002918 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002919 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002920
2921 // Check that we have either the same type or a derived type. It
2922 // affects the conversion rank.
2923 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002924 ImplicitConversionKind SecondKind;
2925 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2926 SecondKind = ICK_Identity;
2927 } else if (IsDerivedFrom(FromType, ClassType))
2928 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002929 else {
John McCallb1bdc622010-02-25 01:37:24 +00002930 ICS.setBad(BadConversionSequence::unrelated_class,
2931 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002932 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002933 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002934
2935 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002936 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00002937 ICS.Standard.setAsIdentityConversion();
2938 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00002939 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002940 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002941 ICS.Standard.ReferenceBinding = true;
2942 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002943 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002944 return ICS;
2945}
2946
2947/// PerformObjectArgumentInitialization - Perform initialization of
2948/// the implicit object parameter for the given Method with the given
2949/// expression.
2950bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00002951Sema::PerformObjectArgumentInitialization(Expr *&From,
2952 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002953 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002954 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002955 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002956 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002957 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Ted Kremenek6217b802009-07-29 21:53:49 +00002959 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002960 FromRecordType = PT->getPointeeType();
2961 DestType = Method->getThisType(Context);
2962 } else {
2963 FromRecordType = From->getType();
2964 DestType = ImplicitParamRecordType;
2965 }
2966
John McCall701c89e2009-12-03 04:06:58 +00002967 // Note that we always use the true parent context when performing
2968 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002969 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002970 = TryObjectArgumentInitialization(From->getType(), Method,
2971 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002972 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002973 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002974 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002975 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Douglas Gregor5fccd362010-03-03 23:55:11 +00002977 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00002978 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00002979
Douglas Gregor5fccd362010-03-03 23:55:11 +00002980 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00002981 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2982 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002983 return false;
2984}
2985
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002986/// TryContextuallyConvertToBool - Attempt to contextually convert the
2987/// expression From to bool (C++0x [conv]p3).
2988ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00002989 // FIXME: This is pretty broken.
Mike Stump1eb44332009-09-09 15:08:12 +00002990 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002991 // FIXME: Are these flags correct?
2992 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002993 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002994 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002995}
2996
2997/// PerformContextuallyConvertToBool - Perform a contextual conversion
2998/// of the expression From to bool (C++0x [conv]p3).
2999bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3000 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00003001 if (!ICS.isBad())
3002 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003003
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003004 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003005 return Diag(From->getSourceRange().getBegin(),
3006 diag::err_typecheck_bool_condition)
3007 << From->getType() << From->getSourceRange();
3008 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003009}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003010
3011/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3012/// expression From to 'id'.
3013ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003014 QualType Ty = Context.getObjCIdType();
3015 return TryImplicitConversion(From, Ty,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003016 // FIXME: Are these flags correct?
3017 /*SuppressUserConversions=*/false,
3018 /*AllowExplicit=*/true,
3019 /*InOverloadResolution=*/false);
3020}
3021
3022/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3023/// of the expression From to 'id'.
3024bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003025 QualType Ty = Context.getObjCIdType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003026 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3027 if (!ICS.isBad())
3028 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3029 return true;
3030}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003031
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003032/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003033/// candidate functions, using the given function call arguments. If
3034/// @p SuppressUserConversions, then don't allow user-defined
3035/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003036///
3037/// \para PartialOverloading true if we are performing "partial" overloading
3038/// based on an incomplete set of function arguments. This feature is used by
3039/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003040void
3041Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003042 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003043 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003044 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003045 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003046 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003047 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003048 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003049 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003050 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003051 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Douglas Gregor88a35142008-12-22 05:46:06 +00003053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003054 if (!isa<CXXConstructorDecl>(Method)) {
3055 // If we get here, it's because we're calling a member function
3056 // that is named without a member access expression (e.g.,
3057 // "this->f") that was either written explicitly or created
3058 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003059 // function, e.g., X::f(). We use an empty type for the implied
3060 // object argument (C++ [over.call.func]p3), and the acting context
3061 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003062 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003063 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003064 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003065 return;
3066 }
3067 // We treat a constructor like a non-member function, since its object
3068 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003069 }
3070
Douglas Gregorfd476482009-11-13 23:59:09 +00003071 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003072 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003073
Douglas Gregor7edfb692009-11-23 12:27:39 +00003074 // Overload resolution is always an unevaluated context.
3075 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3076
Douglas Gregor66724ea2009-11-14 01:20:54 +00003077 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3078 // C++ [class.copy]p3:
3079 // A member function template is never instantiated to perform the copy
3080 // of a class object to an object of its class type.
3081 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3082 if (NumArgs == 1 &&
3083 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003084 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3085 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003086 return;
3087 }
3088
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003089 // Add this candidate
3090 CandidateSet.push_back(OverloadCandidate());
3091 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003092 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003093 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003094 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003095 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003096 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003097
3098 unsigned NumArgsInProto = Proto->getNumArgs();
3099
3100 // (C++ 13.3.2p2): A candidate function having fewer than m
3101 // parameters is viable only if it has an ellipsis in its parameter
3102 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003103 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3104 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003105 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003106 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003107 return;
3108 }
3109
3110 // (C++ 13.3.2p2): A candidate function having more than m parameters
3111 // is viable only if the (m+1)st parameter has a default argument
3112 // (8.3.6). For the purposes of overload resolution, the
3113 // parameter list is truncated on the right, so that there are
3114 // exactly m parameters.
3115 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003116 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003117 // Not enough arguments.
3118 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003119 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003120 return;
3121 }
3122
3123 // Determine the implicit conversion sequences for each of the
3124 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003125 Candidate.Conversions.resize(NumArgs);
3126 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3127 if (ArgIdx < NumArgsInProto) {
3128 // (C++ 13.3.2p3): for F to be a viable function, there shall
3129 // exist for each argument an implicit conversion sequence
3130 // (13.3.3.1) that converts that argument to the corresponding
3131 // parameter of F.
3132 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003133 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003134 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003135 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003136 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003137 if (Candidate.Conversions[ArgIdx].isBad()) {
3138 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003139 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003140 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003141 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003142 } else {
3143 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3144 // argument for which there is no corresponding parameter is
3145 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003146 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003147 }
3148 }
3149}
3150
Douglas Gregor063daf62009-03-13 18:40:31 +00003151/// \brief Add all of the function declarations in the given function set to
3152/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003153void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003154 Expr **Args, unsigned NumArgs,
3155 OverloadCandidateSet& CandidateSet,
3156 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003157 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003158 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3159 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003160 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003161 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003162 cast<CXXMethodDecl>(FD)->getParent(),
3163 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003164 CandidateSet, SuppressUserConversions);
3165 else
John McCall9aa472c2010-03-19 07:35:19 +00003166 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003167 SuppressUserConversions);
3168 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003169 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003170 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3171 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003172 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003173 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003174 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003175 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003176 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003177 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003178 else
John McCall9aa472c2010-03-19 07:35:19 +00003179 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003180 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003181 Args, NumArgs, CandidateSet,
3182 SuppressUserConversions);
3183 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003184 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003185}
3186
John McCall314be4e2009-11-17 07:50:12 +00003187/// AddMethodCandidate - Adds a named decl (which is some kind of
3188/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003189void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003190 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003191 Expr **Args, unsigned NumArgs,
3192 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003193 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003194 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003195 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003196
3197 if (isa<UsingShadowDecl>(Decl))
3198 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3199
3200 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3201 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3202 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003203 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3204 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003205 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003206 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003207 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003208 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003209 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003210 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003211 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003212 }
3213}
3214
Douglas Gregor96176b32008-11-18 23:14:02 +00003215/// AddMethodCandidate - Adds the given C++ member function to the set
3216/// of candidate functions, using the given function call arguments
3217/// and the object argument (@c Object). For example, in a call
3218/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3219/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3220/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003221/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003222void
John McCall9aa472c2010-03-19 07:35:19 +00003223Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003224 CXXRecordDecl *ActingContext, QualType ObjectType,
3225 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003226 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003227 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003228 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003229 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003230 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003231 assert(!isa<CXXConstructorDecl>(Method) &&
3232 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003233
Douglas Gregor3f396022009-09-28 04:47:19 +00003234 if (!CandidateSet.isNewCandidate(Method))
3235 return;
3236
Douglas Gregor7edfb692009-11-23 12:27:39 +00003237 // Overload resolution is always an unevaluated context.
3238 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3239
Douglas Gregor96176b32008-11-18 23:14:02 +00003240 // Add this candidate
3241 CandidateSet.push_back(OverloadCandidate());
3242 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003243 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003244 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003245 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003246 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003247
3248 unsigned NumArgsInProto = Proto->getNumArgs();
3249
3250 // (C++ 13.3.2p2): A candidate function having fewer than m
3251 // parameters is viable only if it has an ellipsis in its parameter
3252 // list (8.3.5).
3253 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3254 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003255 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003256 return;
3257 }
3258
3259 // (C++ 13.3.2p2): A candidate function having more than m parameters
3260 // is viable only if the (m+1)st parameter has a default argument
3261 // (8.3.6). For the purposes of overload resolution, the
3262 // parameter list is truncated on the right, so that there are
3263 // exactly m parameters.
3264 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3265 if (NumArgs < MinRequiredArgs) {
3266 // Not enough arguments.
3267 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003268 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003269 return;
3270 }
3271
3272 Candidate.Viable = true;
3273 Candidate.Conversions.resize(NumArgs + 1);
3274
John McCall701c89e2009-12-03 04:06:58 +00003275 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003276 // The implicit object argument is ignored.
3277 Candidate.IgnoreObjectArgument = true;
3278 else {
3279 // Determine the implicit conversion sequence for the object
3280 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003281 Candidate.Conversions[0]
3282 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003283 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003284 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003285 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003286 return;
3287 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003288 }
3289
3290 // Determine the implicit conversion sequences for each of the
3291 // arguments.
3292 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3293 if (ArgIdx < NumArgsInProto) {
3294 // (C++ 13.3.2p3): for F to be a viable function, there shall
3295 // exist for each argument an implicit conversion sequence
3296 // (13.3.3.1) that converts that argument to the corresponding
3297 // parameter of F.
3298 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003299 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003300 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003301 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003302 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003303 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003304 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003305 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003306 break;
3307 }
3308 } else {
3309 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3310 // argument for which there is no corresponding parameter is
3311 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003312 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003313 }
3314 }
3315}
Douglas Gregora9333192010-05-08 17:41:32 +00003316
Douglas Gregor6b906862009-08-21 00:16:32 +00003317/// \brief Add a C++ member function template as a candidate to the candidate
3318/// set, using template argument deduction to produce an appropriate member
3319/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003320void
Douglas Gregor6b906862009-08-21 00:16:32 +00003321Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003322 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003323 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003324 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003325 QualType ObjectType,
3326 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003327 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003328 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003329 if (!CandidateSet.isNewCandidate(MethodTmpl))
3330 return;
3331
Douglas Gregor6b906862009-08-21 00:16:32 +00003332 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003333 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003334 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003335 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003336 // candidate functions in the usual way.113) A given name can refer to one
3337 // or more function templates and also to a set of overloaded non-template
3338 // functions. In such a case, the candidate functions generated from each
3339 // function template are combined with the set of non-template candidate
3340 // functions.
John McCall5769d612010-02-08 23:07:23 +00003341 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003342 FunctionDecl *Specialization = 0;
3343 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003344 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003345 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003346 CandidateSet.push_back(OverloadCandidate());
3347 OverloadCandidate &Candidate = CandidateSet.back();
3348 Candidate.FoundDecl = FoundDecl;
3349 Candidate.Function = MethodTmpl->getTemplatedDecl();
3350 Candidate.Viable = false;
3351 Candidate.FailureKind = ovl_fail_bad_deduction;
3352 Candidate.IsSurrogate = false;
3353 Candidate.IgnoreObjectArgument = false;
3354 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3355 Info);
3356 return;
3357 }
Mike Stump1eb44332009-09-09 15:08:12 +00003358
Douglas Gregor6b906862009-08-21 00:16:32 +00003359 // Add the function template specialization produced by template argument
3360 // deduction as a candidate.
3361 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003362 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003363 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003364 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003365 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003366 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003367}
3368
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003369/// \brief Add a C++ function template specialization as a candidate
3370/// in the candidate set, using template argument deduction to produce
3371/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003372void
Douglas Gregore53060f2009-06-25 22:08:12 +00003373Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003374 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003375 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003376 Expr **Args, unsigned NumArgs,
3377 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003378 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003379 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3380 return;
3381
Douglas Gregore53060f2009-06-25 22:08:12 +00003382 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003383 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003384 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003385 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003386 // candidate functions in the usual way.113) A given name can refer to one
3387 // or more function templates and also to a set of overloaded non-template
3388 // functions. In such a case, the candidate functions generated from each
3389 // function template are combined with the set of non-template candidate
3390 // functions.
John McCall5769d612010-02-08 23:07:23 +00003391 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003392 FunctionDecl *Specialization = 0;
3393 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003394 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003395 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003396 CandidateSet.push_back(OverloadCandidate());
3397 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003398 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003399 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3400 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003401 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003402 Candidate.IsSurrogate = false;
3403 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003404 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3405 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003406 return;
3407 }
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Douglas Gregore53060f2009-06-25 22:08:12 +00003409 // Add the function template specialization produced by template argument
3410 // deduction as a candidate.
3411 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003412 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003413 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003414}
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003416/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003417/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003418/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003419/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003420/// (which may or may not be the same type as the type that the
3421/// conversion function produces).
3422void
3423Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003424 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003425 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003426 Expr *From, QualType ToType,
3427 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003428 assert(!Conversion->getDescribedFunctionTemplate() &&
3429 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003430 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003431 if (!CandidateSet.isNewCandidate(Conversion))
3432 return;
3433
Douglas Gregor7edfb692009-11-23 12:27:39 +00003434 // Overload resolution is always an unevaluated context.
3435 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3436
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003437 // Add this candidate
3438 CandidateSet.push_back(OverloadCandidate());
3439 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003440 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003441 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003442 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003443 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003444 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003445 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003446 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003447
Douglas Gregor96176b32008-11-18 23:14:02 +00003448 // Determine the implicit conversion sequence for the implicit
3449 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003450 Candidate.Viable = true;
3451 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00003452 Candidate.Conversions[0]
3453 = TryObjectArgumentInitialization(From->getType(), Conversion,
3454 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003455 // Conversion functions to a different type in the base class is visible in
3456 // the derived class. So, a derived to base conversion should not participate
3457 // in overload resolution.
3458 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3459 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00003460 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003461 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003462 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003463 return;
3464 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003465
3466 // We won't go through a user-define type conversion function to convert a
3467 // derived to base as such conversions are given Conversion Rank. They only
3468 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3469 QualType FromCanon
3470 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3471 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3472 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3473 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003474 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003475 return;
3476 }
3477
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003478 // To determine what the conversion from the result of calling the
3479 // conversion function to the type we're eventually trying to
3480 // convert to (ToType), we need to synthesize a call to the
3481 // conversion function and attempt copy initialization from it. This
3482 // makes sure that we get the right semantics with respect to
3483 // lvalues/rvalues and the type. Fortunately, we can allocate this
3484 // call on the stack and we don't need its arguments to be
3485 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003486 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003487 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003488 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003489 CastExpr::CK_FunctionToPointerDecay,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003490 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump1eb44332009-09-09 15:08:12 +00003491
3492 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003493 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3494 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003495 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003496 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003497 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003498 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003499 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003500 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003501 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003502
John McCall1d318332010-01-12 00:44:57 +00003503 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003504 case ImplicitConversionSequence::StandardConversion:
3505 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003506
3507 // C++ [over.ics.user]p3:
3508 // If the user-defined conversion is specified by a specialization of a
3509 // conversion function template, the second standard conversion sequence
3510 // shall have exact match rank.
3511 if (Conversion->getPrimaryTemplate() &&
3512 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3513 Candidate.Viable = false;
3514 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3515 }
3516
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003517 break;
3518
3519 case ImplicitConversionSequence::BadConversion:
3520 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003521 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003522 break;
3523
3524 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003525 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003526 "Can only end up with a standard conversion sequence or failure");
3527 }
3528}
3529
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003530/// \brief Adds a conversion function template specialization
3531/// candidate to the overload set, using template argument deduction
3532/// to deduce the template arguments of the conversion function
3533/// template from the type that we are converting to (C++
3534/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003535void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003536Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003537 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003538 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003539 Expr *From, QualType ToType,
3540 OverloadCandidateSet &CandidateSet) {
3541 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3542 "Only conversion function templates permitted here");
3543
Douglas Gregor3f396022009-09-28 04:47:19 +00003544 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3545 return;
3546
John McCall5769d612010-02-08 23:07:23 +00003547 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003548 CXXConversionDecl *Specialization = 0;
3549 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003550 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003551 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003552 CandidateSet.push_back(OverloadCandidate());
3553 OverloadCandidate &Candidate = CandidateSet.back();
3554 Candidate.FoundDecl = FoundDecl;
3555 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3556 Candidate.Viable = false;
3557 Candidate.FailureKind = ovl_fail_bad_deduction;
3558 Candidate.IsSurrogate = false;
3559 Candidate.IgnoreObjectArgument = false;
3560 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3561 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003562 return;
3563 }
Mike Stump1eb44332009-09-09 15:08:12 +00003564
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003565 // Add the conversion function template specialization produced by
3566 // template argument deduction as a candidate.
3567 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003568 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003569 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003570}
3571
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003572/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3573/// converts the given @c Object to a function pointer via the
3574/// conversion function @c Conversion, and then attempts to call it
3575/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3576/// the type of function that we'll eventually be calling.
3577void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003578 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003579 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003580 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003581 QualType ObjectType,
3582 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003583 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003584 if (!CandidateSet.isNewCandidate(Conversion))
3585 return;
3586
Douglas Gregor7edfb692009-11-23 12:27:39 +00003587 // Overload resolution is always an unevaluated context.
3588 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3589
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003590 CandidateSet.push_back(OverloadCandidate());
3591 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003592 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003593 Candidate.Function = 0;
3594 Candidate.Surrogate = Conversion;
3595 Candidate.Viable = true;
3596 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003597 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003598 Candidate.Conversions.resize(NumArgs + 1);
3599
3600 // Determine the implicit conversion sequence for the implicit
3601 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003602 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003603 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003604 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003605 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003606 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003607 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003608 return;
3609 }
3610
3611 // The first conversion is actually a user-defined conversion whose
3612 // first conversion is ObjectInit's standard conversion (which is
3613 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003614 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003615 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003616 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003617 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003618 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003619 = Candidate.Conversions[0].UserDefined.Before;
3620 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3621
Mike Stump1eb44332009-09-09 15:08:12 +00003622 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003623 unsigned NumArgsInProto = Proto->getNumArgs();
3624
3625 // (C++ 13.3.2p2): A candidate function having fewer than m
3626 // parameters is viable only if it has an ellipsis in its parameter
3627 // list (8.3.5).
3628 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3629 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003630 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003631 return;
3632 }
3633
3634 // Function types don't have any default arguments, so just check if
3635 // we have enough arguments.
3636 if (NumArgs < NumArgsInProto) {
3637 // Not enough arguments.
3638 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003639 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003640 return;
3641 }
3642
3643 // Determine the implicit conversion sequences for each of the
3644 // arguments.
3645 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3646 if (ArgIdx < NumArgsInProto) {
3647 // (C++ 13.3.2p3): for F to be a viable function, there shall
3648 // exist for each argument an implicit conversion sequence
3649 // (13.3.3.1) that converts that argument to the corresponding
3650 // parameter of F.
3651 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003652 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003653 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003654 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003655 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003656 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003657 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003658 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003659 break;
3660 }
3661 } else {
3662 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3663 // argument for which there is no corresponding parameter is
3664 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003665 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003666 }
3667 }
3668}
3669
Douglas Gregor063daf62009-03-13 18:40:31 +00003670/// \brief Add overload candidates for overloaded operators that are
3671/// member functions.
3672///
3673/// Add the overloaded operator candidates that are member functions
3674/// for the operator Op that was used in an operator expression such
3675/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3676/// CandidateSet will store the added overload candidates. (C++
3677/// [over.match.oper]).
3678void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3679 SourceLocation OpLoc,
3680 Expr **Args, unsigned NumArgs,
3681 OverloadCandidateSet& CandidateSet,
3682 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003683 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3684
3685 // C++ [over.match.oper]p3:
3686 // For a unary operator @ with an operand of a type whose
3687 // cv-unqualified version is T1, and for a binary operator @ with
3688 // a left operand of a type whose cv-unqualified version is T1 and
3689 // a right operand of a type whose cv-unqualified version is T2,
3690 // three sets of candidate functions, designated member
3691 // candidates, non-member candidates and built-in candidates, are
3692 // constructed as follows:
3693 QualType T1 = Args[0]->getType();
3694 QualType T2;
3695 if (NumArgs > 1)
3696 T2 = Args[1]->getType();
3697
3698 // -- If T1 is a class type, the set of member candidates is the
3699 // result of the qualified lookup of T1::operator@
3700 // (13.3.1.1.1); otherwise, the set of member candidates is
3701 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003702 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003703 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003704 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003705 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003706
John McCalla24dc2e2009-11-17 02:14:36 +00003707 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3708 LookupQualifiedName(Operators, T1Rec->getDecl());
3709 Operators.suppressDiagnostics();
3710
Mike Stump1eb44332009-09-09 15:08:12 +00003711 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003712 OperEnd = Operators.end();
3713 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003714 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003715 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003716 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003717 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003718 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003719}
3720
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003721/// AddBuiltinCandidate - Add a candidate for a built-in
3722/// operator. ResultTy and ParamTys are the result and parameter types
3723/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003724/// arguments being passed to the candidate. IsAssignmentOperator
3725/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003726/// operator. NumContextualBoolArguments is the number of arguments
3727/// (at the beginning of the argument list) that will be contextually
3728/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003729void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003730 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003731 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003732 bool IsAssignmentOperator,
3733 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003734 // Overload resolution is always an unevaluated context.
3735 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3736
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003737 // Add this candidate
3738 CandidateSet.push_back(OverloadCandidate());
3739 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003740 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003741 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003742 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003743 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003744 Candidate.BuiltinTypes.ResultTy = ResultTy;
3745 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3746 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3747
3748 // Determine the implicit conversion sequences for each of the
3749 // arguments.
3750 Candidate.Viable = true;
3751 Candidate.Conversions.resize(NumArgs);
3752 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003753 // C++ [over.match.oper]p4:
3754 // For the built-in assignment operators, conversions of the
3755 // left operand are restricted as follows:
3756 // -- no temporaries are introduced to hold the left operand, and
3757 // -- no user-defined conversions are applied to the left
3758 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003759 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003760 //
3761 // We block these conversions by turning off user-defined
3762 // conversions, since that is the only way that initialization of
3763 // a reference to a non-class type can occur from something that
3764 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003765 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003766 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003767 "Contextual conversion to bool requires bool type");
3768 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3769 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003770 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003771 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003772 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003773 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003774 }
John McCall1d318332010-01-12 00:44:57 +00003775 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003776 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003777 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003778 break;
3779 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003780 }
3781}
3782
3783/// BuiltinCandidateTypeSet - A set of types that will be used for the
3784/// candidate operator functions for built-in operators (C++
3785/// [over.built]). The types are separated into pointer types and
3786/// enumeration types.
3787class BuiltinCandidateTypeSet {
3788 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003789 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003790
3791 /// PointerTypes - The set of pointer types that will be used in the
3792 /// built-in candidates.
3793 TypeSet PointerTypes;
3794
Sebastian Redl78eb8742009-04-19 21:53:20 +00003795 /// MemberPointerTypes - The set of member pointer types that will be
3796 /// used in the built-in candidates.
3797 TypeSet MemberPointerTypes;
3798
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003799 /// EnumerationTypes - The set of enumeration types that will be
3800 /// used in the built-in candidates.
3801 TypeSet EnumerationTypes;
3802
Douglas Gregor26bcf672010-05-19 03:21:00 +00003803 /// \brief The set of vector types that will be used in the built-in
3804 /// candidates.
3805 TypeSet VectorTypes;
3806
Douglas Gregor5842ba92009-08-24 15:23:48 +00003807 /// Sema - The semantic analysis instance where we are building the
3808 /// candidate type set.
3809 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003810
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003811 /// Context - The AST context in which we will build the type sets.
3812 ASTContext &Context;
3813
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003814 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3815 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003816 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003817
3818public:
3819 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003820 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003821
Mike Stump1eb44332009-09-09 15:08:12 +00003822 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003823 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003824
Douglas Gregor573d9c32009-10-21 23:19:44 +00003825 void AddTypesConvertedFrom(QualType Ty,
3826 SourceLocation Loc,
3827 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003828 bool AllowExplicitConversions,
3829 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003830
3831 /// pointer_begin - First pointer type found;
3832 iterator pointer_begin() { return PointerTypes.begin(); }
3833
Sebastian Redl78eb8742009-04-19 21:53:20 +00003834 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003835 iterator pointer_end() { return PointerTypes.end(); }
3836
Sebastian Redl78eb8742009-04-19 21:53:20 +00003837 /// member_pointer_begin - First member pointer type found;
3838 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3839
3840 /// member_pointer_end - Past the last member pointer type found;
3841 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3842
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003843 /// enumeration_begin - First enumeration type found;
3844 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3845
Sebastian Redl78eb8742009-04-19 21:53:20 +00003846 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003847 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00003848
3849 iterator vector_begin() { return VectorTypes.begin(); }
3850 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003851};
3852
Sebastian Redl78eb8742009-04-19 21:53:20 +00003853/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003854/// the set of pointer types along with any more-qualified variants of
3855/// that type. For example, if @p Ty is "int const *", this routine
3856/// will add "int const *", "int const volatile *", "int const
3857/// restrict *", and "int const volatile restrict *" to the set of
3858/// pointer types. Returns true if the add of @p Ty itself succeeded,
3859/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003860///
3861/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003862bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003863BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3864 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003865
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003866 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003867 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003868 return false;
3869
John McCall0953e762009-09-24 19:53:00 +00003870 const PointerType *PointerTy = Ty->getAs<PointerType>();
3871 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003872
John McCall0953e762009-09-24 19:53:00 +00003873 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003874 // Don't add qualified variants of arrays. For one, they're not allowed
3875 // (the qualifier would sink to the element type), and for another, the
3876 // only overload situation where it matters is subscript or pointer +- int,
3877 // and those shouldn't have qualifier variants anyway.
3878 if (PointeeTy->isArrayType())
3879 return true;
John McCall0953e762009-09-24 19:53:00 +00003880 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003881 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003882 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003883 bool hasVolatile = VisibleQuals.hasVolatile();
3884 bool hasRestrict = VisibleQuals.hasRestrict();
3885
John McCall0953e762009-09-24 19:53:00 +00003886 // Iterate through all strict supersets of BaseCVR.
3887 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3888 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003889 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3890 // in the types.
3891 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3892 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003893 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3894 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003895 }
3896
3897 return true;
3898}
3899
Sebastian Redl78eb8742009-04-19 21:53:20 +00003900/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3901/// to the set of pointer types along with any more-qualified variants of
3902/// that type. For example, if @p Ty is "int const *", this routine
3903/// will add "int const *", "int const volatile *", "int const
3904/// restrict *", and "int const volatile restrict *" to the set of
3905/// pointer types. Returns true if the add of @p Ty itself succeeded,
3906/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003907///
3908/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003909bool
3910BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3911 QualType Ty) {
3912 // Insert this type.
3913 if (!MemberPointerTypes.insert(Ty))
3914 return false;
3915
John McCall0953e762009-09-24 19:53:00 +00003916 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3917 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003918
John McCall0953e762009-09-24 19:53:00 +00003919 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003920 // Don't add qualified variants of arrays. For one, they're not allowed
3921 // (the qualifier would sink to the element type), and for another, the
3922 // only overload situation where it matters is subscript or pointer +- int,
3923 // and those shouldn't have qualifier variants anyway.
3924 if (PointeeTy->isArrayType())
3925 return true;
John McCall0953e762009-09-24 19:53:00 +00003926 const Type *ClassTy = PointerTy->getClass();
3927
3928 // Iterate through all strict supersets of the pointee type's CVR
3929 // qualifiers.
3930 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3931 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3932 if ((CVR | BaseCVR) != CVR) continue;
3933
3934 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3935 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003936 }
3937
3938 return true;
3939}
3940
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003941/// AddTypesConvertedFrom - Add each of the types to which the type @p
3942/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003943/// primarily interested in pointer types and enumeration types. We also
3944/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003945/// AllowUserConversions is true if we should look at the conversion
3946/// functions of a class type, and AllowExplicitConversions if we
3947/// should also include the explicit conversion functions of a class
3948/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003949void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003950BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003951 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003952 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003953 bool AllowExplicitConversions,
3954 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003955 // Only deal with canonical types.
3956 Ty = Context.getCanonicalType(Ty);
3957
3958 // Look through reference types; they aren't part of the type of an
3959 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003960 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003961 Ty = RefTy->getPointeeType();
3962
3963 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003964 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003965
Sebastian Redla65b5512009-11-05 16:36:20 +00003966 // If we're dealing with an array type, decay to the pointer.
3967 if (Ty->isArrayType())
3968 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3969
Ted Kremenek6217b802009-07-29 21:53:49 +00003970 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003971 QualType PointeeTy = PointerTy->getPointeeType();
3972
3973 // Insert our type, and its more-qualified variants, into the set
3974 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003975 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003976 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003977 } else if (Ty->isMemberPointerType()) {
3978 // Member pointers are far easier, since the pointee can't be converted.
3979 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3980 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003981 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003982 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00003983 } else if (Ty->isVectorType()) {
3984 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003985 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003986 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003987 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003988 // No conversion functions in incomplete types.
3989 return;
3990 }
Mike Stump1eb44332009-09-09 15:08:12 +00003991
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003992 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003993 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003994 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003995 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003996 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00003997 NamedDecl *D = I.getDecl();
3998 if (isa<UsingShadowDecl>(D))
3999 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004000
Mike Stump1eb44332009-09-09 15:08:12 +00004001 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004002 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004003 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004004 continue;
4005
John McCall32daa422010-03-31 01:36:47 +00004006 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004007 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004008 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004009 VisibleQuals);
4010 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004011 }
4012 }
4013 }
4014}
4015
Douglas Gregor19b7b152009-08-24 13:43:27 +00004016/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4017/// the volatile- and non-volatile-qualified assignment operators for the
4018/// given type to the candidate set.
4019static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4020 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004021 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004022 unsigned NumArgs,
4023 OverloadCandidateSet &CandidateSet) {
4024 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Douglas Gregor19b7b152009-08-24 13:43:27 +00004026 // T& operator=(T&, T)
4027 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4028 ParamTypes[1] = T;
4029 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4030 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004031
Douglas Gregor19b7b152009-08-24 13:43:27 +00004032 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4033 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004034 ParamTypes[0]
4035 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004036 ParamTypes[1] = T;
4037 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004038 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004039 }
4040}
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Sebastian Redl9994a342009-10-25 17:03:50 +00004042/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4043/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004044static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4045 Qualifiers VRQuals;
4046 const RecordType *TyRec;
4047 if (const MemberPointerType *RHSMPType =
4048 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004049 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004050 else
4051 TyRec = ArgExpr->getType()->getAs<RecordType>();
4052 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004053 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004054 VRQuals.addVolatile();
4055 VRQuals.addRestrict();
4056 return VRQuals;
4057 }
4058
4059 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004060 if (!ClassDecl->hasDefinition())
4061 return VRQuals;
4062
John McCalleec51cf2010-01-20 00:46:10 +00004063 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004064 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004065
John McCalleec51cf2010-01-20 00:46:10 +00004066 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004067 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004068 NamedDecl *D = I.getDecl();
4069 if (isa<UsingShadowDecl>(D))
4070 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4071 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004072 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4073 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4074 CanTy = ResTypeRef->getPointeeType();
4075 // Need to go down the pointer/mempointer chain and add qualifiers
4076 // as see them.
4077 bool done = false;
4078 while (!done) {
4079 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4080 CanTy = ResTypePtr->getPointeeType();
4081 else if (const MemberPointerType *ResTypeMPtr =
4082 CanTy->getAs<MemberPointerType>())
4083 CanTy = ResTypeMPtr->getPointeeType();
4084 else
4085 done = true;
4086 if (CanTy.isVolatileQualified())
4087 VRQuals.addVolatile();
4088 if (CanTy.isRestrictQualified())
4089 VRQuals.addRestrict();
4090 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4091 return VRQuals;
4092 }
4093 }
4094 }
4095 return VRQuals;
4096}
4097
Douglas Gregor74253732008-11-19 15:42:04 +00004098/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4099/// operator overloads to the candidate set (C++ [over.built]), based
4100/// on the operator @p Op and the arguments given. For example, if the
4101/// operator is a binary '+', this routine might add "int
4102/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004103void
Mike Stump1eb44332009-09-09 15:08:12 +00004104Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004105 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004106 Expr **Args, unsigned NumArgs,
4107 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004108 // The set of "promoted arithmetic types", which are the arithmetic
4109 // types are that preserved by promotion (C++ [over.built]p2). Note
4110 // that the first few of these types are the promoted integral
4111 // types; these types need to be first.
4112 // FIXME: What about complex?
4113 const unsigned FirstIntegralType = 0;
4114 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004115 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004116 LastPromotedIntegralType = 13;
4117 const unsigned FirstPromotedArithmeticType = 7,
4118 LastPromotedArithmeticType = 16;
4119 const unsigned NumArithmeticTypes = 16;
4120 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004121 Context.BoolTy, Context.CharTy, Context.WCharTy,
4122// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004123 Context.SignedCharTy, Context.ShortTy,
4124 Context.UnsignedCharTy, Context.UnsignedShortTy,
4125 Context.IntTy, Context.LongTy, Context.LongLongTy,
4126 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4127 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4128 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004129 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4130 "Invalid first promoted integral type");
4131 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4132 == Context.UnsignedLongLongTy &&
4133 "Invalid last promoted integral type");
4134 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4135 "Invalid first promoted arithmetic type");
4136 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4137 == Context.LongDoubleTy &&
4138 "Invalid last promoted arithmetic type");
4139
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004140 // Find all of the types that the arguments can convert to, but only
4141 // if the operator we're looking at has built-in operator candidates
4142 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004143 Qualifiers VisibleTypeConversionsQuals;
4144 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004145 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4146 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4147
Douglas Gregor5842ba92009-08-24 15:23:48 +00004148 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004149 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4150 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4151 OpLoc,
4152 true,
4153 (Op == OO_Exclaim ||
4154 Op == OO_AmpAmp ||
4155 Op == OO_PipePipe),
4156 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004157
4158 bool isComparison = false;
4159 switch (Op) {
4160 case OO_None:
4161 case NUM_OVERLOADED_OPERATORS:
4162 assert(false && "Expected an overloaded operator");
4163 break;
4164
Douglas Gregor74253732008-11-19 15:42:04 +00004165 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004166 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004167 goto UnaryStar;
4168 else
4169 goto BinaryStar;
4170 break;
4171
4172 case OO_Plus: // '+' is either unary or binary
4173 if (NumArgs == 1)
4174 goto UnaryPlus;
4175 else
4176 goto BinaryPlus;
4177 break;
4178
4179 case OO_Minus: // '-' is either unary or binary
4180 if (NumArgs == 1)
4181 goto UnaryMinus;
4182 else
4183 goto BinaryMinus;
4184 break;
4185
4186 case OO_Amp: // '&' is either unary or binary
4187 if (NumArgs == 1)
4188 goto UnaryAmp;
4189 else
4190 goto BinaryAmp;
4191
4192 case OO_PlusPlus:
4193 case OO_MinusMinus:
4194 // C++ [over.built]p3:
4195 //
4196 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4197 // is either volatile or empty, there exist candidate operator
4198 // functions of the form
4199 //
4200 // VQ T& operator++(VQ T&);
4201 // T operator++(VQ T&, int);
4202 //
4203 // C++ [over.built]p4:
4204 //
4205 // For every pair (T, VQ), where T is an arithmetic type other
4206 // than bool, and VQ is either volatile or empty, there exist
4207 // candidate operator functions of the form
4208 //
4209 // VQ T& operator--(VQ T&);
4210 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004211 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004212 Arith < NumArithmeticTypes; ++Arith) {
4213 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004214 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004215 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004216
4217 // Non-volatile version.
4218 if (NumArgs == 1)
4219 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4220 else
4221 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004222 // heuristic to reduce number of builtin candidates in the set.
4223 // Add volatile version only if there are conversions to a volatile type.
4224 if (VisibleTypeConversionsQuals.hasVolatile()) {
4225 // Volatile version
4226 ParamTypes[0]
4227 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4228 if (NumArgs == 1)
4229 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4230 else
4231 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4232 }
Douglas Gregor74253732008-11-19 15:42:04 +00004233 }
4234
4235 // C++ [over.built]p5:
4236 //
4237 // For every pair (T, VQ), where T is a cv-qualified or
4238 // cv-unqualified object type, and VQ is either volatile or
4239 // empty, there exist candidate operator functions of the form
4240 //
4241 // T*VQ& operator++(T*VQ&);
4242 // T*VQ& operator--(T*VQ&);
4243 // T* operator++(T*VQ&, int);
4244 // T* operator--(T*VQ&, int);
4245 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4246 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4247 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00004248 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004249 continue;
4250
Mike Stump1eb44332009-09-09 15:08:12 +00004251 QualType ParamTypes[2] = {
4252 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004253 };
Mike Stump1eb44332009-09-09 15:08:12 +00004254
Douglas Gregor74253732008-11-19 15:42:04 +00004255 // Without volatile
4256 if (NumArgs == 1)
4257 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4258 else
4259 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4260
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004261 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4262 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004263 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004264 ParamTypes[0]
4265 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004266 if (NumArgs == 1)
4267 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4268 else
4269 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4270 }
4271 }
4272 break;
4273
4274 UnaryStar:
4275 // C++ [over.built]p6:
4276 // For every cv-qualified or cv-unqualified object type T, there
4277 // exist candidate operator functions of the form
4278 //
4279 // T& operator*(T*);
4280 //
4281 // C++ [over.built]p7:
4282 // For every function type T, there exist candidate operator
4283 // functions of the form
4284 // T& operator*(T*);
4285 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4286 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4287 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00004288 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004289 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004290 &ParamTy, Args, 1, CandidateSet);
4291 }
4292 break;
4293
4294 UnaryPlus:
4295 // C++ [over.built]p8:
4296 // For every type T, there exist candidate operator functions of
4297 // the form
4298 //
4299 // T* operator+(T*);
4300 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4301 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4302 QualType ParamTy = *Ptr;
4303 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4304 }
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Douglas Gregor74253732008-11-19 15:42:04 +00004306 // Fall through
4307
4308 UnaryMinus:
4309 // C++ [over.built]p9:
4310 // For every promoted arithmetic type T, there exist candidate
4311 // operator functions of the form
4312 //
4313 // T operator+(T);
4314 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004315 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004316 Arith < LastPromotedArithmeticType; ++Arith) {
4317 QualType ArithTy = ArithmeticTypes[Arith];
4318 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4319 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004320
4321 // Extension: We also add these operators for vector types.
4322 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4323 VecEnd = CandidateTypes.vector_end();
4324 Vec != VecEnd; ++Vec) {
4325 QualType VecTy = *Vec;
4326 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4327 }
Douglas Gregor74253732008-11-19 15:42:04 +00004328 break;
4329
4330 case OO_Tilde:
4331 // C++ [over.built]p10:
4332 // For every promoted integral type T, there exist candidate
4333 // operator functions of the form
4334 //
4335 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004336 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004337 Int < LastPromotedIntegralType; ++Int) {
4338 QualType IntTy = ArithmeticTypes[Int];
4339 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4340 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004341
4342 // Extension: We also add this operator for vector types.
4343 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4344 VecEnd = CandidateTypes.vector_end();
4345 Vec != VecEnd; ++Vec) {
4346 QualType VecTy = *Vec;
4347 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4348 }
Douglas Gregor74253732008-11-19 15:42:04 +00004349 break;
4350
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004351 case OO_New:
4352 case OO_Delete:
4353 case OO_Array_New:
4354 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004355 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004356 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004357 break;
4358
4359 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004360 UnaryAmp:
4361 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004362 // C++ [over.match.oper]p3:
4363 // -- For the operator ',', the unary operator '&', or the
4364 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004365 break;
4366
Douglas Gregor19b7b152009-08-24 13:43:27 +00004367 case OO_EqualEqual:
4368 case OO_ExclaimEqual:
4369 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004370 // For every pointer to member type T, there exist candidate operator
4371 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004372 //
4373 // bool operator==(T,T);
4374 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004375 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004376 MemPtr = CandidateTypes.member_pointer_begin(),
4377 MemPtrEnd = CandidateTypes.member_pointer_end();
4378 MemPtr != MemPtrEnd;
4379 ++MemPtr) {
4380 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4381 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4382 }
Mike Stump1eb44332009-09-09 15:08:12 +00004383
Douglas Gregor19b7b152009-08-24 13:43:27 +00004384 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004386 case OO_Less:
4387 case OO_Greater:
4388 case OO_LessEqual:
4389 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004390 // C++ [over.built]p15:
4391 //
4392 // For every pointer or enumeration type T, there exist
4393 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004394 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004395 // bool operator<(T, T);
4396 // bool operator>(T, T);
4397 // bool operator<=(T, T);
4398 // bool operator>=(T, T);
4399 // bool operator==(T, T);
4400 // bool operator!=(T, T);
4401 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4402 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4403 QualType ParamTypes[2] = { *Ptr, *Ptr };
4404 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4405 }
Mike Stump1eb44332009-09-09 15:08:12 +00004406 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004407 = CandidateTypes.enumeration_begin();
4408 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4409 QualType ParamTypes[2] = { *Enum, *Enum };
4410 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4411 }
4412
4413 // Fall through.
4414 isComparison = true;
4415
Douglas Gregor74253732008-11-19 15:42:04 +00004416 BinaryPlus:
4417 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004418 if (!isComparison) {
4419 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4420
4421 // C++ [over.built]p13:
4422 //
4423 // For every cv-qualified or cv-unqualified object type T
4424 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004425 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004426 // T* operator+(T*, ptrdiff_t);
4427 // T& operator[](T*, ptrdiff_t); [BELOW]
4428 // T* operator-(T*, ptrdiff_t);
4429 // T* operator+(ptrdiff_t, T*);
4430 // T& operator[](ptrdiff_t, T*); [BELOW]
4431 //
4432 // C++ [over.built]p14:
4433 //
4434 // For every T, where T is a pointer to object type, there
4435 // exist candidate operator functions of the form
4436 //
4437 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004438 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004439 = CandidateTypes.pointer_begin();
4440 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4441 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4442
4443 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4444 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4445
4446 if (Op == OO_Plus) {
4447 // T* operator+(ptrdiff_t, T*);
4448 ParamTypes[0] = ParamTypes[1];
4449 ParamTypes[1] = *Ptr;
4450 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4451 } else {
4452 // ptrdiff_t operator-(T, T);
4453 ParamTypes[1] = *Ptr;
4454 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4455 Args, 2, CandidateSet);
4456 }
4457 }
4458 }
4459 // Fall through
4460
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004461 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004462 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004463 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004464 // C++ [over.built]p12:
4465 //
4466 // For every pair of promoted arithmetic types L and R, there
4467 // exist candidate operator functions of the form
4468 //
4469 // LR operator*(L, R);
4470 // LR operator/(L, R);
4471 // LR operator+(L, R);
4472 // LR operator-(L, R);
4473 // bool operator<(L, R);
4474 // bool operator>(L, R);
4475 // bool operator<=(L, R);
4476 // bool operator>=(L, R);
4477 // bool operator==(L, R);
4478 // bool operator!=(L, R);
4479 //
4480 // where LR is the result of the usual arithmetic conversions
4481 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004482 //
4483 // C++ [over.built]p24:
4484 //
4485 // For every pair of promoted arithmetic types L and R, there exist
4486 // candidate operator functions of the form
4487 //
4488 // LR operator?(bool, L, R);
4489 //
4490 // where LR is the result of the usual arithmetic conversions
4491 // between types L and R.
4492 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004493 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004494 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004495 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004496 Right < LastPromotedArithmeticType; ++Right) {
4497 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004498 QualType Result
4499 = isComparison
4500 ? Context.BoolTy
4501 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004502 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4503 }
4504 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004505
4506 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4507 // conditional operator for vector types.
4508 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4509 Vec1End = CandidateTypes.vector_end();
4510 Vec1 != Vec1End; ++Vec1)
4511 for (BuiltinCandidateTypeSet::iterator
4512 Vec2 = CandidateTypes.vector_begin(),
4513 Vec2End = CandidateTypes.vector_end();
4514 Vec2 != Vec2End; ++Vec2) {
4515 QualType LandR[2] = { *Vec1, *Vec2 };
4516 QualType Result;
4517 if (isComparison)
4518 Result = Context.BoolTy;
4519 else {
4520 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4521 Result = *Vec1;
4522 else
4523 Result = *Vec2;
4524 }
4525
4526 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4527 }
4528
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004529 break;
4530
4531 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004532 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004533 case OO_Caret:
4534 case OO_Pipe:
4535 case OO_LessLess:
4536 case OO_GreaterGreater:
4537 // C++ [over.built]p17:
4538 //
4539 // For every pair of promoted integral types L and R, there
4540 // exist candidate operator functions of the form
4541 //
4542 // LR operator%(L, R);
4543 // LR operator&(L, R);
4544 // LR operator^(L, R);
4545 // LR operator|(L, R);
4546 // L operator<<(L, R);
4547 // L operator>>(L, R);
4548 //
4549 // where LR is the result of the usual arithmetic conversions
4550 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004551 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004552 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004553 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004554 Right < LastPromotedIntegralType; ++Right) {
4555 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4556 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4557 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004558 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004559 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4560 }
4561 }
4562 break;
4563
4564 case OO_Equal:
4565 // C++ [over.built]p20:
4566 //
4567 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004568 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004569 // empty, there exist candidate operator functions of the form
4570 //
4571 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004572 for (BuiltinCandidateTypeSet::iterator
4573 Enum = CandidateTypes.enumeration_begin(),
4574 EnumEnd = CandidateTypes.enumeration_end();
4575 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004576 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004577 CandidateSet);
4578 for (BuiltinCandidateTypeSet::iterator
4579 MemPtr = CandidateTypes.member_pointer_begin(),
4580 MemPtrEnd = CandidateTypes.member_pointer_end();
4581 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004582 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004583 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004584
4585 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004586
4587 case OO_PlusEqual:
4588 case OO_MinusEqual:
4589 // C++ [over.built]p19:
4590 //
4591 // For every pair (T, VQ), where T is any type and VQ is either
4592 // volatile or empty, there exist candidate operator functions
4593 // of the form
4594 //
4595 // T*VQ& operator=(T*VQ&, T*);
4596 //
4597 // C++ [over.built]p21:
4598 //
4599 // For every pair (T, VQ), where T is a cv-qualified or
4600 // cv-unqualified object type and VQ is either volatile or
4601 // empty, there exist candidate operator functions of the form
4602 //
4603 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4604 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4605 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4606 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4607 QualType ParamTypes[2];
4608 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4609
4610 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004611 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004612 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4613 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004614
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004615 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4616 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004617 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004618 ParamTypes[0]
4619 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004620 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4621 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004622 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004623 }
4624 // Fall through.
4625
4626 case OO_StarEqual:
4627 case OO_SlashEqual:
4628 // C++ [over.built]p18:
4629 //
4630 // For every triple (L, VQ, R), where L is an arithmetic type,
4631 // VQ is either volatile or empty, and R is a promoted
4632 // arithmetic type, there exist candidate operator functions of
4633 // the form
4634 //
4635 // VQ L& operator=(VQ L&, R);
4636 // VQ L& operator*=(VQ L&, R);
4637 // VQ L& operator/=(VQ L&, R);
4638 // VQ L& operator+=(VQ L&, R);
4639 // VQ L& operator-=(VQ L&, R);
4640 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004641 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004642 Right < LastPromotedArithmeticType; ++Right) {
4643 QualType ParamTypes[2];
4644 ParamTypes[1] = ArithmeticTypes[Right];
4645
4646 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004647 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004648 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4649 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004650
4651 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004652 if (VisibleTypeConversionsQuals.hasVolatile()) {
4653 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4654 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4655 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4656 /*IsAssigmentOperator=*/Op == OO_Equal);
4657 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004658 }
4659 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004660
4661 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4662 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4663 Vec1End = CandidateTypes.vector_end();
4664 Vec1 != Vec1End; ++Vec1)
4665 for (BuiltinCandidateTypeSet::iterator
4666 Vec2 = CandidateTypes.vector_begin(),
4667 Vec2End = CandidateTypes.vector_end();
4668 Vec2 != Vec2End; ++Vec2) {
4669 QualType ParamTypes[2];
4670 ParamTypes[1] = *Vec2;
4671 // Add this built-in operator as a candidate (VQ is empty).
4672 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4673 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4674 /*IsAssigmentOperator=*/Op == OO_Equal);
4675
4676 // Add this built-in operator as a candidate (VQ is 'volatile').
4677 if (VisibleTypeConversionsQuals.hasVolatile()) {
4678 ParamTypes[0] = Context.getVolatileType(*Vec1);
4679 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4680 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4681 /*IsAssigmentOperator=*/Op == OO_Equal);
4682 }
4683 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004684 break;
4685
4686 case OO_PercentEqual:
4687 case OO_LessLessEqual:
4688 case OO_GreaterGreaterEqual:
4689 case OO_AmpEqual:
4690 case OO_CaretEqual:
4691 case OO_PipeEqual:
4692 // C++ [over.built]p22:
4693 //
4694 // For every triple (L, VQ, R), where L is an integral type, VQ
4695 // is either volatile or empty, and R is a promoted integral
4696 // type, there exist candidate operator functions of the form
4697 //
4698 // VQ L& operator%=(VQ L&, R);
4699 // VQ L& operator<<=(VQ L&, R);
4700 // VQ L& operator>>=(VQ L&, R);
4701 // VQ L& operator&=(VQ L&, R);
4702 // VQ L& operator^=(VQ L&, R);
4703 // VQ L& operator|=(VQ L&, R);
4704 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004705 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004706 Right < LastPromotedIntegralType; ++Right) {
4707 QualType ParamTypes[2];
4708 ParamTypes[1] = ArithmeticTypes[Right];
4709
4710 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004711 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004712 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00004713 if (VisibleTypeConversionsQuals.hasVolatile()) {
4714 // Add this built-in operator as a candidate (VQ is 'volatile').
4715 ParamTypes[0] = ArithmeticTypes[Left];
4716 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4717 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4718 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4719 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004720 }
4721 }
4722 break;
4723
Douglas Gregor74253732008-11-19 15:42:04 +00004724 case OO_Exclaim: {
4725 // C++ [over.operator]p23:
4726 //
4727 // There also exist candidate operator functions of the form
4728 //
Mike Stump1eb44332009-09-09 15:08:12 +00004729 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004730 // bool operator&&(bool, bool); [BELOW]
4731 // bool operator||(bool, bool); [BELOW]
4732 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004733 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4734 /*IsAssignmentOperator=*/false,
4735 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004736 break;
4737 }
4738
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004739 case OO_AmpAmp:
4740 case OO_PipePipe: {
4741 // C++ [over.operator]p23:
4742 //
4743 // There also exist candidate operator functions of the form
4744 //
Douglas Gregor74253732008-11-19 15:42:04 +00004745 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004746 // bool operator&&(bool, bool);
4747 // bool operator||(bool, bool);
4748 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004749 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4750 /*IsAssignmentOperator=*/false,
4751 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004752 break;
4753 }
4754
4755 case OO_Subscript:
4756 // C++ [over.built]p13:
4757 //
4758 // For every cv-qualified or cv-unqualified object type T there
4759 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004760 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004761 // T* operator+(T*, ptrdiff_t); [ABOVE]
4762 // T& operator[](T*, ptrdiff_t);
4763 // T* operator-(T*, ptrdiff_t); [ABOVE]
4764 // T* operator+(ptrdiff_t, T*); [ABOVE]
4765 // T& operator[](ptrdiff_t, T*);
4766 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4767 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4768 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004769 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004770 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004771
4772 // T& operator[](T*, ptrdiff_t)
4773 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4774
4775 // T& operator[](ptrdiff_t, T*);
4776 ParamTypes[0] = ParamTypes[1];
4777 ParamTypes[1] = *Ptr;
4778 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004779 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004780 break;
4781
4782 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004783 // C++ [over.built]p11:
4784 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4785 // C1 is the same type as C2 or is a derived class of C2, T is an object
4786 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4787 // there exist candidate operator functions of the form
4788 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4789 // where CV12 is the union of CV1 and CV2.
4790 {
4791 for (BuiltinCandidateTypeSet::iterator Ptr =
4792 CandidateTypes.pointer_begin();
4793 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4794 QualType C1Ty = (*Ptr);
4795 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004796 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004797 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004798 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004799 if (!isa<RecordType>(C1))
4800 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004801 // heuristic to reduce number of builtin candidates in the set.
4802 // Add volatile/restrict version only if there are conversions to a
4803 // volatile/restrict type.
4804 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4805 continue;
4806 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4807 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004808 }
4809 for (BuiltinCandidateTypeSet::iterator
4810 MemPtr = CandidateTypes.member_pointer_begin(),
4811 MemPtrEnd = CandidateTypes.member_pointer_end();
4812 MemPtr != MemPtrEnd; ++MemPtr) {
4813 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4814 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004815 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004816 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4817 break;
4818 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4819 // build CV12 T&
4820 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004821 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4822 T.isVolatileQualified())
4823 continue;
4824 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4825 T.isRestrictQualified())
4826 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004827 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004828 QualType ResultTy = Context.getLValueReferenceType(T);
4829 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4830 }
4831 }
4832 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004833 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004834
4835 case OO_Conditional:
4836 // Note that we don't consider the first argument, since it has been
4837 // contextually converted to bool long ago. The candidates below are
4838 // therefore added as binary.
4839 //
4840 // C++ [over.built]p24:
4841 // For every type T, where T is a pointer or pointer-to-member type,
4842 // there exist candidate operator functions of the form
4843 //
4844 // T operator?(bool, T, T);
4845 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004846 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4847 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4848 QualType ParamTypes[2] = { *Ptr, *Ptr };
4849 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4850 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004851 for (BuiltinCandidateTypeSet::iterator Ptr =
4852 CandidateTypes.member_pointer_begin(),
4853 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4854 QualType ParamTypes[2] = { *Ptr, *Ptr };
4855 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4856 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004857 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004858 }
4859}
4860
Douglas Gregorfa047642009-02-04 00:32:51 +00004861/// \brief Add function candidates found via argument-dependent lookup
4862/// to the set of overloading candidates.
4863///
4864/// This routine performs argument-dependent name lookup based on the
4865/// given function name (which may also be an operator name) and adds
4866/// all of the overload candidates found by ADL to the overload
4867/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004868void
Douglas Gregorfa047642009-02-04 00:32:51 +00004869Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004870 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004871 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004872 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004873 OverloadCandidateSet& CandidateSet,
4874 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004875 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004876
John McCalla113e722010-01-26 06:04:06 +00004877 // FIXME: This approach for uniquing ADL results (and removing
4878 // redundant candidates from the set) relies on pointer-equality,
4879 // which means we need to key off the canonical decl. However,
4880 // always going back to the canonical decl might not get us the
4881 // right set of default arguments. What default arguments are
4882 // we supposed to consider on ADL candidates, anyway?
4883
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004884 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004885 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004886
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004887 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004888 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4889 CandEnd = CandidateSet.end();
4890 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004891 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004892 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004893 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004894 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004895 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004896
4897 // For each of the ADL candidates we found, add it to the overload
4898 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004899 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00004900 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00004901 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004902 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004903 continue;
4904
John McCall9aa472c2010-03-19 07:35:19 +00004905 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00004906 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004907 } else
John McCall6e266892010-01-26 03:27:55 +00004908 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00004909 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004910 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004911 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004912}
4913
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004914/// isBetterOverloadCandidate - Determines whether the first overload
4915/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004916bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004917Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00004918 const OverloadCandidate& Cand2,
4919 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004920 // Define viable functions to be better candidates than non-viable
4921 // functions.
4922 if (!Cand2.Viable)
4923 return Cand1.Viable;
4924 else if (!Cand1.Viable)
4925 return false;
4926
Douglas Gregor88a35142008-12-22 05:46:06 +00004927 // C++ [over.match.best]p1:
4928 //
4929 // -- if F is a static member function, ICS1(F) is defined such
4930 // that ICS1(F) is neither better nor worse than ICS1(G) for
4931 // any function G, and, symmetrically, ICS1(G) is neither
4932 // better nor worse than ICS1(F).
4933 unsigned StartArg = 0;
4934 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4935 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004936
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004937 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004938 // A viable function F1 is defined to be a better function than another
4939 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004940 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004941 unsigned NumArgs = Cand1.Conversions.size();
4942 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4943 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004944 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004945 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4946 Cand2.Conversions[ArgIdx])) {
4947 case ImplicitConversionSequence::Better:
4948 // Cand1 has a better conversion sequence.
4949 HasBetterConversion = true;
4950 break;
4951
4952 case ImplicitConversionSequence::Worse:
4953 // Cand1 can't be better than Cand2.
4954 return false;
4955
4956 case ImplicitConversionSequence::Indistinguishable:
4957 // Do nothing.
4958 break;
4959 }
4960 }
4961
Mike Stump1eb44332009-09-09 15:08:12 +00004962 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004963 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004964 if (HasBetterConversion)
4965 return true;
4966
Mike Stump1eb44332009-09-09 15:08:12 +00004967 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004968 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00004969 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004970 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4971 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004972
4973 // -- F1 and F2 are function template specializations, and the function
4974 // template for F1 is more specialized than the template for F2
4975 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004976 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004977 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4978 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004979 if (FunctionTemplateDecl *BetterTemplate
4980 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4981 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00004982 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004983 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4984 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004985 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004986
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004987 // -- the context is an initialization by user-defined conversion
4988 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4989 // from the return type of F1 to the destination type (i.e.,
4990 // the type of the entity being initialized) is a better
4991 // conversion sequence than the standard conversion sequence
4992 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004993 if (Cand1.Function && Cand2.Function &&
4994 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004995 isa<CXXConversionDecl>(Cand2.Function)) {
4996 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4997 Cand2.FinalConversion)) {
4998 case ImplicitConversionSequence::Better:
4999 // Cand1 has a better conversion sequence.
5000 return true;
5001
5002 case ImplicitConversionSequence::Worse:
5003 // Cand1 can't be better than Cand2.
5004 return false;
5005
5006 case ImplicitConversionSequence::Indistinguishable:
5007 // Do nothing
5008 break;
5009 }
5010 }
5011
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005012 return false;
5013}
5014
Mike Stump1eb44332009-09-09 15:08:12 +00005015/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005016/// within an overload candidate set.
5017///
5018/// \param CandidateSet the set of candidate functions.
5019///
5020/// \param Loc the location of the function name (or operator symbol) for
5021/// which overload resolution occurs.
5022///
Mike Stump1eb44332009-09-09 15:08:12 +00005023/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005024/// function, Best points to the candidate function found.
5025///
5026/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00005027OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5028 SourceLocation Loc,
5029 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005030 // Find the best viable function.
5031 Best = CandidateSet.end();
5032 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5033 Cand != CandidateSet.end(); ++Cand) {
5034 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00005035 if (Best == CandidateSet.end() ||
5036 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005037 Best = Cand;
5038 }
5039 }
5040
5041 // If we didn't find any viable functions, abort.
5042 if (Best == CandidateSet.end())
5043 return OR_No_Viable_Function;
5044
5045 // Make sure that this function is better than every other viable
5046 // function. If not, we have an ambiguity.
5047 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5048 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005049 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005050 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00005051 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005052 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005053 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005054 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005055 }
Mike Stump1eb44332009-09-09 15:08:12 +00005056
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005057 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005058 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005059 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005060 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005061 return OR_Deleted;
5062
Douglas Gregore0762c92009-06-19 23:52:42 +00005063 // C++ [basic.def.odr]p2:
5064 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005065 // when referred to from a potentially-evaluated expression. [Note: this
5066 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005067 // (clause 13), user-defined conversions (12.3.2), allocation function for
5068 // placement new (5.3.4), as well as non-default initialization (8.5).
5069 if (Best->Function)
5070 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005071 return OR_Success;
5072}
5073
John McCall3c80f572010-01-12 02:15:36 +00005074namespace {
5075
5076enum OverloadCandidateKind {
5077 oc_function,
5078 oc_method,
5079 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005080 oc_function_template,
5081 oc_method_template,
5082 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005083 oc_implicit_default_constructor,
5084 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005085 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005086};
5087
John McCall220ccbf2010-01-13 00:25:19 +00005088OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5089 FunctionDecl *Fn,
5090 std::string &Description) {
5091 bool isTemplate = false;
5092
5093 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5094 isTemplate = true;
5095 Description = S.getTemplateArgumentBindingsText(
5096 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5097 }
John McCallb1622a12010-01-06 09:43:14 +00005098
5099 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005100 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005101 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005102
John McCall3c80f572010-01-12 02:15:36 +00005103 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5104 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005105 }
5106
5107 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5108 // This actually gets spelled 'candidate function' for now, but
5109 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005110 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005111 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005112
5113 assert(Meth->isCopyAssignment()
5114 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005115 return oc_implicit_copy_assignment;
5116 }
5117
John McCall220ccbf2010-01-13 00:25:19 +00005118 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005119}
5120
5121} // end anonymous namespace
5122
5123// Notes the location of an overload candidate.
5124void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005125 std::string FnDesc;
5126 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5127 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5128 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005129}
5130
John McCall1d318332010-01-12 00:44:57 +00005131/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5132/// "lead" diagnostic; it will be given two arguments, the source and
5133/// target types of the conversion.
5134void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5135 SourceLocation CaretLoc,
5136 const PartialDiagnostic &PDiag) {
5137 Diag(CaretLoc, PDiag)
5138 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5139 for (AmbiguousConversionSequence::const_iterator
5140 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5141 NoteOverloadCandidate(*I);
5142 }
John McCall81201622010-01-08 04:41:39 +00005143}
5144
John McCall1d318332010-01-12 00:44:57 +00005145namespace {
5146
John McCalladbb8f82010-01-13 09:16:55 +00005147void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5148 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5149 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005150 assert(Cand->Function && "for now, candidate must be a function");
5151 FunctionDecl *Fn = Cand->Function;
5152
5153 // There's a conversion slot for the object argument if this is a
5154 // non-constructor method. Note that 'I' corresponds the
5155 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005156 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005157 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005158 if (I == 0)
5159 isObjectArgument = true;
5160 else
5161 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005162 }
5163
John McCall220ccbf2010-01-13 00:25:19 +00005164 std::string FnDesc;
5165 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5166
John McCalladbb8f82010-01-13 09:16:55 +00005167 Expr *FromExpr = Conv.Bad.FromExpr;
5168 QualType FromTy = Conv.Bad.getFromType();
5169 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005170
John McCall5920dbb2010-02-02 02:42:52 +00005171 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005172 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005173 Expr *E = FromExpr->IgnoreParens();
5174 if (isa<UnaryOperator>(E))
5175 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005176 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005177
5178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5179 << (unsigned) FnKind << FnDesc
5180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5181 << ToTy << Name << I+1;
5182 return;
5183 }
5184
John McCall258b2032010-01-23 08:10:49 +00005185 // Do some hand-waving analysis to see if the non-viability is due
5186 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005187 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5188 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5189 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5190 CToTy = RT->getPointeeType();
5191 else {
5192 // TODO: detect and diagnose the full richness of const mismatches.
5193 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5194 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5195 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5196 }
5197
5198 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5199 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5200 // It is dumb that we have to do this here.
5201 while (isa<ArrayType>(CFromTy))
5202 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5203 while (isa<ArrayType>(CToTy))
5204 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5205
5206 Qualifiers FromQs = CFromTy.getQualifiers();
5207 Qualifiers ToQs = CToTy.getQualifiers();
5208
5209 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5210 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5211 << (unsigned) FnKind << FnDesc
5212 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5213 << FromTy
5214 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5215 << (unsigned) isObjectArgument << I+1;
5216 return;
5217 }
5218
5219 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5220 assert(CVR && "unexpected qualifiers mismatch");
5221
5222 if (isObjectArgument) {
5223 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5224 << (unsigned) FnKind << FnDesc
5225 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5226 << FromTy << (CVR - 1);
5227 } else {
5228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5229 << (unsigned) FnKind << FnDesc
5230 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5231 << FromTy << (CVR - 1) << I+1;
5232 }
5233 return;
5234 }
5235
John McCall258b2032010-01-23 08:10:49 +00005236 // Diagnose references or pointers to incomplete types differently,
5237 // since it's far from impossible that the incompleteness triggered
5238 // the failure.
5239 QualType TempFromTy = FromTy.getNonReferenceType();
5240 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5241 TempFromTy = PTy->getPointeeType();
5242 if (TempFromTy->isIncompleteType()) {
5243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5244 << (unsigned) FnKind << FnDesc
5245 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5246 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5247 return;
5248 }
5249
John McCall651f3ee2010-01-14 03:28:57 +00005250 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5252 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005253 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005254 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005255}
5256
5257void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5258 unsigned NumFormalArgs) {
5259 // TODO: treat calls to a missing default constructor as a special case
5260
5261 FunctionDecl *Fn = Cand->Function;
5262 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5263
5264 unsigned MinParams = Fn->getMinRequiredArguments();
5265
5266 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005267 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005268 unsigned mode, modeCount;
5269 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005270 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5271 (Cand->FailureKind == ovl_fail_bad_deduction &&
5272 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005273 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5274 mode = 0; // "at least"
5275 else
5276 mode = 2; // "exactly"
5277 modeCount = MinParams;
5278 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005279 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5280 (Cand->FailureKind == ovl_fail_bad_deduction &&
5281 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005282 if (MinParams != FnTy->getNumArgs())
5283 mode = 1; // "at most"
5284 else
5285 mode = 2; // "exactly"
5286 modeCount = FnTy->getNumArgs();
5287 }
5288
5289 std::string Description;
5290 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5291
5292 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005293 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5294 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005295}
5296
John McCall342fec42010-02-01 18:53:26 +00005297/// Diagnose a failed template-argument deduction.
5298void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5299 Expr **Args, unsigned NumArgs) {
5300 FunctionDecl *Fn = Cand->Function; // pattern
5301
Douglas Gregora9333192010-05-08 17:41:32 +00005302 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005303 NamedDecl *ParamD;
5304 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5305 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5306 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005307 switch (Cand->DeductionFailure.Result) {
5308 case Sema::TDK_Success:
5309 llvm_unreachable("TDK_success while diagnosing bad deduction");
5310
5311 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005312 assert(ParamD && "no parameter found for incomplete deduction result");
5313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5314 << ParamD->getDeclName();
5315 return;
5316 }
5317
Douglas Gregora9333192010-05-08 17:41:32 +00005318 case Sema::TDK_Inconsistent:
5319 case Sema::TDK_InconsistentQuals: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005320 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005321 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005322 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005323 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005324 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005325 which = 1;
5326 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005327 which = 2;
5328 }
5329
5330 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5331 << which << ParamD->getDeclName()
5332 << *Cand->DeductionFailure.getFirstArg()
5333 << *Cand->DeductionFailure.getSecondArg();
5334 return;
5335 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005336
Douglas Gregorf1a84452010-05-08 19:15:54 +00005337 case Sema::TDK_InvalidExplicitArguments:
5338 assert(ParamD && "no parameter found for invalid explicit arguments");
5339 if (ParamD->getDeclName())
5340 S.Diag(Fn->getLocation(),
5341 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5342 << ParamD->getDeclName();
5343 else {
5344 int index = 0;
5345 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5346 index = TTP->getIndex();
5347 else if (NonTypeTemplateParmDecl *NTTP
5348 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5349 index = NTTP->getIndex();
5350 else
5351 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5352 S.Diag(Fn->getLocation(),
5353 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5354 << (index + 1);
5355 }
5356 return;
5357
Douglas Gregora18592e2010-05-08 18:13:28 +00005358 case Sema::TDK_TooManyArguments:
5359 case Sema::TDK_TooFewArguments:
5360 DiagnoseArityMismatch(S, Cand, NumArgs);
5361 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005362
5363 case Sema::TDK_InstantiationDepth:
5364 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5365 return;
5366
5367 case Sema::TDK_SubstitutionFailure: {
5368 std::string ArgString;
5369 if (TemplateArgumentList *Args
5370 = Cand->DeductionFailure.getTemplateArgumentList())
5371 ArgString = S.getTemplateArgumentBindingsText(
5372 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5373 *Args);
5374 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5375 << ArgString;
5376 return;
5377 }
Douglas Gregora9333192010-05-08 17:41:32 +00005378
John McCall342fec42010-02-01 18:53:26 +00005379 // TODO: diagnose these individually, then kill off
5380 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005381 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005382 case Sema::TDK_FailedOverloadResolution:
5383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5384 return;
5385 }
5386}
5387
5388/// Generates a 'note' diagnostic for an overload candidate. We've
5389/// already generated a primary error at the call site.
5390///
5391/// It really does need to be a single diagnostic with its caret
5392/// pointed at the candidate declaration. Yes, this creates some
5393/// major challenges of technical writing. Yes, this makes pointing
5394/// out problems with specific arguments quite awkward. It's still
5395/// better than generating twenty screens of text for every failed
5396/// overload.
5397///
5398/// It would be great to be able to express per-candidate problems
5399/// more richly for those diagnostic clients that cared, but we'd
5400/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005401void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5402 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005403 FunctionDecl *Fn = Cand->Function;
5404
John McCall81201622010-01-08 04:41:39 +00005405 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005406 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005407 std::string FnDesc;
5408 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005409
5410 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005411 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005412 return;
John McCall81201622010-01-08 04:41:39 +00005413 }
5414
John McCall220ccbf2010-01-13 00:25:19 +00005415 // We don't really have anything else to say about viable candidates.
5416 if (Cand->Viable) {
5417 S.NoteOverloadCandidate(Fn);
5418 return;
5419 }
John McCall1d318332010-01-12 00:44:57 +00005420
John McCalladbb8f82010-01-13 09:16:55 +00005421 switch (Cand->FailureKind) {
5422 case ovl_fail_too_many_arguments:
5423 case ovl_fail_too_few_arguments:
5424 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005425
John McCalladbb8f82010-01-13 09:16:55 +00005426 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005427 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5428
John McCall717e8912010-01-23 05:17:32 +00005429 case ovl_fail_trivial_conversion:
5430 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005431 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005432 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005433
John McCallb1bdc622010-02-25 01:37:24 +00005434 case ovl_fail_bad_conversion: {
5435 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5436 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005437 if (Cand->Conversions[I].isBad())
5438 return DiagnoseBadConversion(S, Cand, I);
5439
5440 // FIXME: this currently happens when we're called from SemaInit
5441 // when user-conversion overload fails. Figure out how to handle
5442 // those conditions and diagnose them well.
5443 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005444 }
John McCallb1bdc622010-02-25 01:37:24 +00005445 }
John McCalla1d7d622010-01-08 00:58:21 +00005446}
5447
5448void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5449 // Desugar the type of the surrogate down to a function type,
5450 // retaining as many typedefs as possible while still showing
5451 // the function type (and, therefore, its parameter types).
5452 QualType FnType = Cand->Surrogate->getConversionType();
5453 bool isLValueReference = false;
5454 bool isRValueReference = false;
5455 bool isPointer = false;
5456 if (const LValueReferenceType *FnTypeRef =
5457 FnType->getAs<LValueReferenceType>()) {
5458 FnType = FnTypeRef->getPointeeType();
5459 isLValueReference = true;
5460 } else if (const RValueReferenceType *FnTypeRef =
5461 FnType->getAs<RValueReferenceType>()) {
5462 FnType = FnTypeRef->getPointeeType();
5463 isRValueReference = true;
5464 }
5465 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5466 FnType = FnTypePtr->getPointeeType();
5467 isPointer = true;
5468 }
5469 // Desugar down to a function type.
5470 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5471 // Reconstruct the pointer/reference as appropriate.
5472 if (isPointer) FnType = S.Context.getPointerType(FnType);
5473 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5474 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5475
5476 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5477 << FnType;
5478}
5479
5480void NoteBuiltinOperatorCandidate(Sema &S,
5481 const char *Opc,
5482 SourceLocation OpLoc,
5483 OverloadCandidate *Cand) {
5484 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5485 std::string TypeStr("operator");
5486 TypeStr += Opc;
5487 TypeStr += "(";
5488 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5489 if (Cand->Conversions.size() == 1) {
5490 TypeStr += ")";
5491 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5492 } else {
5493 TypeStr += ", ";
5494 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5495 TypeStr += ")";
5496 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5497 }
5498}
5499
5500void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5501 OverloadCandidate *Cand) {
5502 unsigned NoOperands = Cand->Conversions.size();
5503 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5504 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005505 if (ICS.isBad()) break; // all meaningless after first invalid
5506 if (!ICS.isAmbiguous()) continue;
5507
5508 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005509 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005510 }
5511}
5512
John McCall1b77e732010-01-15 23:32:50 +00005513SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5514 if (Cand->Function)
5515 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005516 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005517 return Cand->Surrogate->getLocation();
5518 return SourceLocation();
5519}
5520
John McCallbf65c0b2010-01-12 00:48:53 +00005521struct CompareOverloadCandidatesForDisplay {
5522 Sema &S;
5523 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005524
5525 bool operator()(const OverloadCandidate *L,
5526 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005527 // Fast-path this check.
5528 if (L == R) return false;
5529
John McCall81201622010-01-08 04:41:39 +00005530 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005531 if (L->Viable) {
5532 if (!R->Viable) return true;
5533
5534 // TODO: introduce a tri-valued comparison for overload
5535 // candidates. Would be more worthwhile if we had a sort
5536 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005537 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5538 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005539 } else if (R->Viable)
5540 return false;
John McCall81201622010-01-08 04:41:39 +00005541
John McCall1b77e732010-01-15 23:32:50 +00005542 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005543
John McCall1b77e732010-01-15 23:32:50 +00005544 // Criteria by which we can sort non-viable candidates:
5545 if (!L->Viable) {
5546 // 1. Arity mismatches come after other candidates.
5547 if (L->FailureKind == ovl_fail_too_many_arguments ||
5548 L->FailureKind == ovl_fail_too_few_arguments)
5549 return false;
5550 if (R->FailureKind == ovl_fail_too_many_arguments ||
5551 R->FailureKind == ovl_fail_too_few_arguments)
5552 return true;
John McCall81201622010-01-08 04:41:39 +00005553
John McCall717e8912010-01-23 05:17:32 +00005554 // 2. Bad conversions come first and are ordered by the number
5555 // of bad conversions and quality of good conversions.
5556 if (L->FailureKind == ovl_fail_bad_conversion) {
5557 if (R->FailureKind != ovl_fail_bad_conversion)
5558 return true;
5559
5560 // If there's any ordering between the defined conversions...
5561 // FIXME: this might not be transitive.
5562 assert(L->Conversions.size() == R->Conversions.size());
5563
5564 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005565 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5566 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005567 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5568 R->Conversions[I])) {
5569 case ImplicitConversionSequence::Better:
5570 leftBetter++;
5571 break;
5572
5573 case ImplicitConversionSequence::Worse:
5574 leftBetter--;
5575 break;
5576
5577 case ImplicitConversionSequence::Indistinguishable:
5578 break;
5579 }
5580 }
5581 if (leftBetter > 0) return true;
5582 if (leftBetter < 0) return false;
5583
5584 } else if (R->FailureKind == ovl_fail_bad_conversion)
5585 return false;
5586
John McCall1b77e732010-01-15 23:32:50 +00005587 // TODO: others?
5588 }
5589
5590 // Sort everything else by location.
5591 SourceLocation LLoc = GetLocationForCandidate(L);
5592 SourceLocation RLoc = GetLocationForCandidate(R);
5593
5594 // Put candidates without locations (e.g. builtins) at the end.
5595 if (LLoc.isInvalid()) return false;
5596 if (RLoc.isInvalid()) return true;
5597
5598 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005599 }
5600};
5601
John McCall717e8912010-01-23 05:17:32 +00005602/// CompleteNonViableCandidate - Normally, overload resolution only
5603/// computes up to the first
5604void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5605 Expr **Args, unsigned NumArgs) {
5606 assert(!Cand->Viable);
5607
5608 // Don't do anything on failures other than bad conversion.
5609 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5610
5611 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005612 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005613 unsigned ConvCount = Cand->Conversions.size();
5614 while (true) {
5615 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5616 ConvIdx++;
5617 if (Cand->Conversions[ConvIdx - 1].isBad())
5618 break;
5619 }
5620
5621 if (ConvIdx == ConvCount)
5622 return;
5623
John McCallb1bdc622010-02-25 01:37:24 +00005624 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5625 "remaining conversion is initialized?");
5626
Douglas Gregor23ef6c02010-04-16 17:45:54 +00005627 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00005628 // operation somehow.
5629 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00005630
5631 const FunctionProtoType* Proto;
5632 unsigned ArgIdx = ConvIdx;
5633
5634 if (Cand->IsSurrogate) {
5635 QualType ConvType
5636 = Cand->Surrogate->getConversionType().getNonReferenceType();
5637 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5638 ConvType = ConvPtrType->getPointeeType();
5639 Proto = ConvType->getAs<FunctionProtoType>();
5640 ArgIdx--;
5641 } else if (Cand->Function) {
5642 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5643 if (isa<CXXMethodDecl>(Cand->Function) &&
5644 !isa<CXXConstructorDecl>(Cand->Function))
5645 ArgIdx--;
5646 } else {
5647 // Builtin binary operator with a bad first conversion.
5648 assert(ConvCount <= 3);
5649 for (; ConvIdx != ConvCount; ++ConvIdx)
5650 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005651 = TryCopyInitialization(S, Args[ConvIdx],
5652 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5653 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005654 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00005655 return;
5656 }
5657
5658 // Fill in the rest of the conversions.
5659 unsigned NumArgsInProto = Proto->getNumArgs();
5660 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5661 if (ArgIdx < NumArgsInProto)
5662 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005663 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5664 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005665 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00005666 else
5667 Cand->Conversions[ConvIdx].setEllipsis();
5668 }
5669}
5670
John McCalla1d7d622010-01-08 00:58:21 +00005671} // end anonymous namespace
5672
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005673/// PrintOverloadCandidates - When overload resolution fails, prints
5674/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00005675/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00005676void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005677Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00005678 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00005679 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005680 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00005681 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00005682 // Sort the candidates by viability and position. Sorting directly would
5683 // be prohibitive, so we make a set of pointers and sort those.
5684 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5685 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5686 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5687 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00005688 Cand != LastCand; ++Cand) {
5689 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00005690 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00005691 else if (OCD == OCD_AllCandidates) {
5692 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005693 if (Cand->Function || Cand->IsSurrogate)
5694 Cands.push_back(Cand);
5695 // Otherwise, this a non-viable builtin candidate. We do not, in general,
5696 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00005697 }
5698 }
5699
John McCallbf65c0b2010-01-12 00:48:53 +00005700 std::sort(Cands.begin(), Cands.end(),
5701 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00005702
John McCall1d318332010-01-12 00:44:57 +00005703 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00005704
John McCall81201622010-01-08 04:41:39 +00005705 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005706 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
5707 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00005708 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5709 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00005710
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005711 // Set an arbitrary limit on the number of candidate functions we'll spam
5712 // the user with. FIXME: This limit should depend on details of the
5713 // candidate list.
5714 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
5715 break;
5716 }
5717 ++CandsShown;
5718
John McCalla1d7d622010-01-08 00:58:21 +00005719 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00005720 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00005721 else if (Cand->IsSurrogate)
5722 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005723 else {
5724 assert(Cand->Viable &&
5725 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00005726 // Generally we only see ambiguities including viable builtin
5727 // operators if overload resolution got screwed up by an
5728 // ambiguous user-defined conversion.
5729 //
5730 // FIXME: It's quite possible for different conversions to see
5731 // different ambiguities, though.
5732 if (!ReportedAmbiguousConversions) {
5733 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5734 ReportedAmbiguousConversions = true;
5735 }
John McCalla1d7d622010-01-08 00:58:21 +00005736
John McCall1d318332010-01-12 00:44:57 +00005737 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00005738 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005739 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005740 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005741
5742 if (I != E)
Jeffrey Yasskin258de302010-06-11 06:58:43 +00005743 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005744}
5745
John McCall9aa472c2010-03-19 07:35:19 +00005746static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00005747 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00005748 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005749
John McCall9aa472c2010-03-19 07:35:19 +00005750 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005751}
5752
Douglas Gregor904eed32008-11-10 20:40:00 +00005753/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5754/// an overloaded function (C++ [over.over]), where @p From is an
5755/// expression with overloaded function type and @p ToType is the type
5756/// we're trying to resolve to. For example:
5757///
5758/// @code
5759/// int f(double);
5760/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00005761///
Douglas Gregor904eed32008-11-10 20:40:00 +00005762/// int (*pfd)(double) = f; // selects f(double)
5763/// @endcode
5764///
5765/// This routine returns the resulting FunctionDecl if it could be
5766/// resolved, and NULL otherwise. When @p Complain is true, this
5767/// routine will emit diagnostics if there is an error.
5768FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00005769Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00005770 bool Complain,
5771 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005772 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00005773 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00005774 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00005775 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00005776 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00005777 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00005778 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00005779 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005780 FunctionType = MemTypePtr->getPointeeType();
5781 IsMember = true;
5782 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005783
Douglas Gregor904eed32008-11-10 20:40:00 +00005784 // C++ [over.over]p1:
5785 // [...] [Note: any redundant set of parentheses surrounding the
5786 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00005787 // C++ [over.over]p1:
5788 // [...] The overloaded function name can be preceded by the &
5789 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005790 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5791 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5792 if (OvlExpr->hasExplicitTemplateArgs()) {
5793 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5794 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00005795 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005796
5797 // We expect a pointer or reference to function, or a function pointer.
5798 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5799 if (!FunctionType->isFunctionType()) {
5800 if (Complain)
5801 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5802 << OvlExpr->getName() << ToType;
5803
5804 return 0;
5805 }
5806
5807 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00005808
Douglas Gregor904eed32008-11-10 20:40:00 +00005809 // Look through all of the overloaded functions, searching for one
5810 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00005811 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00005812 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5813
Douglas Gregor00aeb522009-07-08 23:33:52 +00005814 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00005815 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5816 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00005817 // Look through any using declarations to find the underlying function.
5818 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5819
Douglas Gregor904eed32008-11-10 20:40:00 +00005820 // C++ [over.over]p3:
5821 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00005822 // targets of type "pointer-to-function" or "reference-to-function."
5823 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00005824 // type "pointer-to-member-function."
5825 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00005826
Mike Stump1eb44332009-09-09 15:08:12 +00005827 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00005828 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005829 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00005830 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005831 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005832 // static when converting to member pointer.
5833 if (Method->isStatic() == IsMember)
5834 continue;
5835 } else if (IsMember)
5836 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005837
Douglas Gregor00aeb522009-07-08 23:33:52 +00005838 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005839 // If the name is a function template, template argument deduction is
5840 // done (14.8.2.2), and if the argument deduction succeeds, the
5841 // resulting template argument list is used to generate a single
5842 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005843 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005844 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005845 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005846 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005847 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005848 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005849 FunctionType, Specialization, Info)) {
5850 // FIXME: make a note of the failed deduction for diagnostics.
5851 (void)Result;
5852 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005853 // FIXME: If the match isn't exact, shouldn't we just drop this as
5854 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005855 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005856 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00005857 Matches.push_back(std::make_pair(I.getPair(),
5858 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00005859 }
John McCallba135432009-11-21 08:51:07 +00005860
5861 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005862 }
Mike Stump1eb44332009-09-09 15:08:12 +00005863
Chandler Carruthbd647292009-12-29 06:17:27 +00005864 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005865 // Skip non-static functions when converting to pointer, and static
5866 // when converting to member pointer.
5867 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005868 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005869
5870 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005871 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005872 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005873 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005874 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005875
Chandler Carruthbd647292009-12-29 06:17:27 +00005876 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005877 QualType ResultTy;
5878 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5879 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5880 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00005881 Matches.push_back(std::make_pair(I.getPair(),
5882 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00005883 FoundNonTemplateFunction = true;
5884 }
Mike Stump1eb44332009-09-09 15:08:12 +00005885 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005886 }
5887
Douglas Gregor00aeb522009-07-08 23:33:52 +00005888 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005889 if (Matches.empty()) {
5890 if (Complain) {
5891 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5892 << OvlExpr->getName() << FunctionType;
5893 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5894 E = OvlExpr->decls_end();
5895 I != E; ++I)
5896 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5897 NoteOverloadCandidate(F);
5898 }
5899
Douglas Gregor00aeb522009-07-08 23:33:52 +00005900 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005901 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005902 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00005903 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005904 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005905 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00005906 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005907 return Result;
5908 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005909
5910 // C++ [over.over]p4:
5911 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005912 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005913 // [...] and any given function template specialization F1 is
5914 // eliminated if the set contains a second function template
5915 // specialization whose function template is more specialized
5916 // than the function template of F1 according to the partial
5917 // ordering rules of 14.5.5.2.
5918
5919 // The algorithm specified above is quadratic. We instead use a
5920 // two-pass algorithm (similar to the one used to identify the
5921 // best viable function in an overload set) that identifies the
5922 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00005923
5924 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5925 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5926 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00005927
5928 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00005929 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005930 TPOC_Other, From->getLocStart(),
5931 PDiag(),
5932 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005933 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005934 PDiag(diag::note_ovl_candidate)
5935 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00005936 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00005937 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00005938 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00005939 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00005940 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00005941 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5942 }
John McCallc373d482010-01-27 01:50:18 +00005943 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005944 }
Mike Stump1eb44332009-09-09 15:08:12 +00005945
Douglas Gregor312a2022009-09-26 03:56:17 +00005946 // [...] any function template specializations in the set are
5947 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005948 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00005949 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00005950 ++I;
5951 else {
John McCall9aa472c2010-03-19 07:35:19 +00005952 Matches[I] = Matches[--N];
5953 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00005954 }
5955 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005956
Mike Stump1eb44332009-09-09 15:08:12 +00005957 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005958 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005959 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005960 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00005961 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00005962 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00005963 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00005964 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5965 }
John McCall9aa472c2010-03-19 07:35:19 +00005966 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005967 }
Mike Stump1eb44332009-09-09 15:08:12 +00005968
Douglas Gregor00aeb522009-07-08 23:33:52 +00005969 // FIXME: We should probably return the same thing that BestViableFunction
5970 // returns (even if we issue the diagnostics here).
5971 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005972 << Matches[0].second->getDeclName();
5973 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5974 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00005975 return 0;
5976}
5977
Douglas Gregor4b52e252009-12-21 23:17:24 +00005978/// \brief Given an expression that refers to an overloaded function, try to
5979/// resolve that overloaded function expression down to a single function.
5980///
5981/// This routine can only resolve template-ids that refer to a single function
5982/// template, where that template-id refers to a single template whose template
5983/// arguments are either provided by the template-id or have defaults,
5984/// as described in C++0x [temp.arg.explicit]p3.
5985FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5986 // C++ [over.over]p1:
5987 // [...] [Note: any redundant set of parentheses surrounding the
5988 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005989 // C++ [over.over]p1:
5990 // [...] The overloaded function name can be preceded by the &
5991 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005992
5993 if (From->getType() != Context.OverloadTy)
5994 return 0;
5995
5996 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005997
5998 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005999 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006000 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006001
6002 TemplateArgumentListInfo ExplicitTemplateArgs;
6003 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006004
6005 // Look through all of the overloaded functions, searching for one
6006 // whose type matches exactly.
6007 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006008 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6009 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006010 // C++0x [temp.arg.explicit]p3:
6011 // [...] In contexts where deduction is done and fails, or in contexts
6012 // where deduction is not done, if a template argument list is
6013 // specified and it, along with any default template arguments,
6014 // identifies a single function template specialization, then the
6015 // template-id is an lvalue for the function template specialization.
6016 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
6017
6018 // C++ [over.over]p2:
6019 // If the name is a function template, template argument deduction is
6020 // done (14.8.2.2), and if the argument deduction succeeds, the
6021 // resulting template argument list is used to generate a single
6022 // function template specialization, which is added to the set of
6023 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006024 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006025 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006026 if (TemplateDeductionResult Result
6027 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6028 Specialization, Info)) {
6029 // FIXME: make a note of the failed deduction for diagnostics.
6030 (void)Result;
6031 continue;
6032 }
6033
6034 // Multiple matches; we can't resolve to a single declaration.
6035 if (Matched)
6036 return 0;
6037
6038 Matched = Specialization;
6039 }
6040
6041 return Matched;
6042}
6043
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006044/// \brief Add a single candidate to the overload set.
6045static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006046 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006047 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006048 Expr **Args, unsigned NumArgs,
6049 OverloadCandidateSet &CandidateSet,
6050 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006051 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006052 if (isa<UsingShadowDecl>(Callee))
6053 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6054
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006055 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006056 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006057 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006058 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006059 return;
John McCallba135432009-11-21 08:51:07 +00006060 }
6061
6062 if (FunctionTemplateDecl *FuncTemplate
6063 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006064 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6065 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006066 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006067 return;
6068 }
6069
6070 assert(false && "unhandled case in overloaded call candidate");
6071
6072 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006073}
6074
6075/// \brief Add the overload candidates named by callee and/or found by argument
6076/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006077void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006078 Expr **Args, unsigned NumArgs,
6079 OverloadCandidateSet &CandidateSet,
6080 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006081
6082#ifndef NDEBUG
6083 // Verify that ArgumentDependentLookup is consistent with the rules
6084 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006085 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006086 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6087 // and let Y be the lookup set produced by argument dependent
6088 // lookup (defined as follows). If X contains
6089 //
6090 // -- a declaration of a class member, or
6091 //
6092 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006093 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006094 //
6095 // -- a declaration that is neither a function or a function
6096 // template
6097 //
6098 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006099
John McCall3b4294e2009-12-16 12:17:52 +00006100 if (ULE->requiresADL()) {
6101 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6102 E = ULE->decls_end(); I != E; ++I) {
6103 assert(!(*I)->getDeclContext()->isRecord());
6104 assert(isa<UsingShadowDecl>(*I) ||
6105 !(*I)->getDeclContext()->isFunctionOrMethod());
6106 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006107 }
6108 }
6109#endif
6110
John McCall3b4294e2009-12-16 12:17:52 +00006111 // It would be nice to avoid this copy.
6112 TemplateArgumentListInfo TABuffer;
6113 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6114 if (ULE->hasExplicitTemplateArgs()) {
6115 ULE->copyTemplateArgumentsInto(TABuffer);
6116 ExplicitTemplateArgs = &TABuffer;
6117 }
6118
6119 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6120 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006121 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006122 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006123 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006124
John McCall3b4294e2009-12-16 12:17:52 +00006125 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006126 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6127 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006128 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006129 CandidateSet,
6130 PartialOverloading);
6131}
John McCall578b69b2009-12-16 08:11:27 +00006132
John McCall3b4294e2009-12-16 12:17:52 +00006133static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6134 Expr **Args, unsigned NumArgs) {
6135 Fn->Destroy(SemaRef.Context);
6136 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6137 Args[Arg]->Destroy(SemaRef.Context);
6138 return SemaRef.ExprError();
6139}
6140
John McCall578b69b2009-12-16 08:11:27 +00006141/// Attempts to recover from a call where no functions were found.
6142///
6143/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00006144static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006145BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006146 UnresolvedLookupExpr *ULE,
6147 SourceLocation LParenLoc,
6148 Expr **Args, unsigned NumArgs,
6149 SourceLocation *CommaLocs,
6150 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006151
6152 CXXScopeSpec SS;
6153 if (ULE->getQualifier()) {
6154 SS.setScopeRep(ULE->getQualifier());
6155 SS.setRange(ULE->getQualifierRange());
6156 }
6157
John McCall3b4294e2009-12-16 12:17:52 +00006158 TemplateArgumentListInfo TABuffer;
6159 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6160 if (ULE->hasExplicitTemplateArgs()) {
6161 ULE->copyTemplateArgumentsInto(TABuffer);
6162 ExplicitTemplateArgs = &TABuffer;
6163 }
6164
John McCall578b69b2009-12-16 08:11:27 +00006165 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6166 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006167 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall3b4294e2009-12-16 12:17:52 +00006168 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00006169
John McCall3b4294e2009-12-16 12:17:52 +00006170 assert(!R.empty() && "lookup results empty despite recovery");
6171
6172 // Build an implicit member call if appropriate. Just drop the
6173 // casts and such from the call, we don't really care.
6174 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6175 if ((*R.begin())->isCXXClassMember())
6176 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6177 else if (ExplicitTemplateArgs)
6178 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6179 else
6180 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6181
6182 if (NewFn.isInvalid())
6183 return Destroy(SemaRef, Fn, Args, NumArgs);
6184
6185 Fn->Destroy(SemaRef.Context);
6186
6187 // This shouldn't cause an infinite loop because we're giving it
6188 // an expression with non-empty lookup results, which should never
6189 // end up here.
6190 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6191 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6192 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006193}
Douglas Gregord7a95972010-06-08 17:35:15 +00006194
Douglas Gregorf6b89692008-11-26 05:54:23 +00006195/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006196/// (which eventually refers to the declaration Func) and the call
6197/// arguments Args/NumArgs, attempt to resolve the function call down
6198/// to a specific function. If overload resolution succeeds, returns
6199/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006200/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006201/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00006202Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006203Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006204 SourceLocation LParenLoc,
6205 Expr **Args, unsigned NumArgs,
6206 SourceLocation *CommaLocs,
6207 SourceLocation RParenLoc) {
6208#ifndef NDEBUG
6209 if (ULE->requiresADL()) {
6210 // To do ADL, we must have found an unqualified name.
6211 assert(!ULE->getQualifier() && "qualified name with ADL");
6212
6213 // We don't perform ADL for implicit declarations of builtins.
6214 // Verify that this was correctly set up.
6215 FunctionDecl *F;
6216 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6217 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6218 F->getBuiltinID() && F->isImplicit())
6219 assert(0 && "performing ADL for builtin");
6220
6221 // We don't perform ADL in C.
6222 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6223 }
6224#endif
6225
John McCall5769d612010-02-08 23:07:23 +00006226 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006227
John McCall3b4294e2009-12-16 12:17:52 +00006228 // Add the functions denoted by the callee to the set of candidate
6229 // functions, including those from argument-dependent lookup.
6230 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006231
6232 // If we found nothing, try to recover.
6233 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6234 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006235 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006236 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006237 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006238
Douglas Gregorf6b89692008-11-26 05:54:23 +00006239 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006240 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006241 case OR_Success: {
6242 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006243 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006244 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006245 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006246 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6247 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006248
6249 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006250 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006251 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006252 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006253 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006254 break;
6255
6256 case OR_Ambiguous:
6257 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006258 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006259 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006260 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006261
6262 case OR_Deleted:
6263 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6264 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006265 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006266 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006267 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006268 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006269 }
6270
6271 // Overload resolution failed. Destroy all of the subexpressions and
6272 // return NULL.
6273 Fn->Destroy(Context);
6274 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6275 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00006276 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006277}
6278
John McCall6e266892010-01-26 03:27:55 +00006279static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006280 return Functions.size() > 1 ||
6281 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6282}
6283
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006284/// \brief Create a unary operation that may resolve to an overloaded
6285/// operator.
6286///
6287/// \param OpLoc The location of the operator itself (e.g., '*').
6288///
6289/// \param OpcIn The UnaryOperator::Opcode that describes this
6290/// operator.
6291///
6292/// \param Functions The set of non-member functions that will be
6293/// considered by overload resolution. The caller needs to build this
6294/// set based on the context using, e.g.,
6295/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6296/// set should not contain any member functions; those will be added
6297/// by CreateOverloadedUnaryOp().
6298///
6299/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00006300Sema::OwningExprResult
6301Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6302 const UnresolvedSetImpl &Fns,
6303 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006304 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6305 Expr *Input = (Expr *)input.get();
6306
6307 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6308 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6309 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6310
6311 Expr *Args[2] = { Input, 0 };
6312 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006313
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006314 // For post-increment and post-decrement, add the implicit '0' as
6315 // the second argument, so that we know this is a post-increment or
6316 // post-decrement.
6317 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6318 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006319 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006320 SourceLocation());
6321 NumArgs = 2;
6322 }
6323
6324 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00006325 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006326 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006327 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006328 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006329 /*ADL*/ true, IsOverloaded(Fns),
6330 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006331 input.release();
6332 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6333 &Args[0], NumArgs,
6334 Context.DependentTy,
6335 OpLoc));
6336 }
6337
6338 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006339 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006340
6341 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006342 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006343
6344 // Add operator candidates that are member functions.
6345 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6346
John McCall6e266892010-01-26 03:27:55 +00006347 // Add candidates from ADL.
6348 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006349 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006350 /*ExplicitTemplateArgs*/ 0,
6351 CandidateSet);
6352
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006353 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006354 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006355
6356 // Perform overload resolution.
6357 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006358 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006359 case OR_Success: {
6360 // We found a built-in operator or an overloaded operator.
6361 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006362
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006363 if (FnDecl) {
6364 // We matched an overloaded operator. Build a call to that
6365 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006366
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006367 // Convert the arguments.
6368 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006369 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006370
John McCall6bb80172010-03-30 21:47:33 +00006371 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6372 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006373 return ExprError();
6374 } else {
6375 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00006376 OwningExprResult InputInit
6377 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006378 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006379 SourceLocation(),
6380 move(input));
6381 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006382 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006383
Douglas Gregore1a5c172009-12-23 17:40:29 +00006384 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006385 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006386 }
6387
John McCallb697e082010-05-06 18:15:07 +00006388 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6389
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006390 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00006391 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006392
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006393 // Build the actual expression node.
6394 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6395 SourceLocation());
6396 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006397
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006398 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00006399 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00006400 ExprOwningPtr<CallExpr> TheCall(this,
6401 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00006402 Args, NumArgs, ResultTy, OpLoc));
John McCallb697e082010-05-06 18:15:07 +00006403
Anders Carlsson26a2a072009-10-13 21:19:37 +00006404 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6405 FnDecl))
6406 return ExprError();
6407
6408 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006409 } else {
6410 // We matched a built-in operator. Convert the arguments, then
6411 // break out so that we will build the appropriate built-in
6412 // operator node.
6413 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006414 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006415 return ExprError();
6416
6417 break;
6418 }
6419 }
6420
6421 case OR_No_Viable_Function:
6422 // No viable function; fall through to handling this as a
6423 // built-in operator, which will produce an error message for us.
6424 break;
6425
6426 case OR_Ambiguous:
6427 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6428 << UnaryOperator::getOpcodeStr(Opc)
6429 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006430 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006431 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006432 return ExprError();
6433
6434 case OR_Deleted:
6435 Diag(OpLoc, diag::err_ovl_deleted_oper)
6436 << Best->Function->isDeleted()
6437 << UnaryOperator::getOpcodeStr(Opc)
6438 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006439 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006440 return ExprError();
6441 }
6442
6443 // Either we found no viable overloaded operator or we matched a
6444 // built-in operator. In either case, fall through to trying to
6445 // build a built-in operation.
6446 input.release();
6447 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6448}
6449
Douglas Gregor063daf62009-03-13 18:40:31 +00006450/// \brief Create a binary operation that may resolve to an overloaded
6451/// operator.
6452///
6453/// \param OpLoc The location of the operator itself (e.g., '+').
6454///
6455/// \param OpcIn The BinaryOperator::Opcode that describes this
6456/// operator.
6457///
6458/// \param Functions The set of non-member functions that will be
6459/// considered by overload resolution. The caller needs to build this
6460/// set based on the context using, e.g.,
6461/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6462/// set should not contain any member functions; those will be added
6463/// by CreateOverloadedBinOp().
6464///
6465/// \param LHS Left-hand argument.
6466/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006467Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006468Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006469 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006470 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006471 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006472 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006473 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006474
6475 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6476 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6477 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6478
6479 // If either side is type-dependent, create an appropriate dependent
6480 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006481 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006482 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006483 // If there are no functions to store, just build a dependent
6484 // BinaryOperator or CompoundAssignment.
6485 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6486 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6487 Context.DependentTy, OpLoc));
6488
6489 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6490 Context.DependentTy,
6491 Context.DependentTy,
6492 Context.DependentTy,
6493 OpLoc));
6494 }
John McCall6e266892010-01-26 03:27:55 +00006495
6496 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006497 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006498 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006499 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006500 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006501 /*ADL*/ true, IsOverloaded(Fns),
6502 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006503 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006504 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006505 Context.DependentTy,
6506 OpLoc));
6507 }
6508
6509 // If this is the .* operator, which is not overloadable, just
6510 // create a built-in binary operator.
6511 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006512 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006513
Sebastian Redl275c2b42009-11-18 23:10:33 +00006514 // If this is the assignment operator, we only perform overload resolution
6515 // if the left-hand side is a class or enumeration type. This is actually
6516 // a hack. The standard requires that we do overload resolution between the
6517 // various built-in candidates, but as DR507 points out, this can lead to
6518 // problems. So we do it this way, which pretty much follows what GCC does.
6519 // Note that we go the traditional code path for compound assignment forms.
6520 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006521 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006522
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006523 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006524 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006525
6526 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006527 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006528
6529 // Add operator candidates that are member functions.
6530 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6531
John McCall6e266892010-01-26 03:27:55 +00006532 // Add candidates from ADL.
6533 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6534 Args, 2,
6535 /*ExplicitTemplateArgs*/ 0,
6536 CandidateSet);
6537
Douglas Gregor063daf62009-03-13 18:40:31 +00006538 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006539 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006540
6541 // Perform overload resolution.
6542 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006543 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006544 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006545 // We found a built-in operator or an overloaded operator.
6546 FunctionDecl *FnDecl = Best->Function;
6547
6548 if (FnDecl) {
6549 // We matched an overloaded operator. Build a call to that
6550 // operator.
6551
6552 // Convert the arguments.
6553 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006554 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006555 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006556
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006557 OwningExprResult Arg1
6558 = PerformCopyInitialization(
6559 InitializedEntity::InitializeParameter(
6560 FnDecl->getParamDecl(0)),
6561 SourceLocation(),
6562 Owned(Args[1]));
6563 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006564 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006565
Douglas Gregor5fccd362010-03-03 23:55:11 +00006566 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006567 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006568 return ExprError();
6569
6570 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006571 } else {
6572 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006573 OwningExprResult Arg0
6574 = PerformCopyInitialization(
6575 InitializedEntity::InitializeParameter(
6576 FnDecl->getParamDecl(0)),
6577 SourceLocation(),
6578 Owned(Args[0]));
6579 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006580 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006581
6582 OwningExprResult Arg1
6583 = PerformCopyInitialization(
6584 InitializedEntity::InitializeParameter(
6585 FnDecl->getParamDecl(1)),
6586 SourceLocation(),
6587 Owned(Args[1]));
6588 if (Arg1.isInvalid())
6589 return ExprError();
6590 Args[0] = LHS = Arg0.takeAs<Expr>();
6591 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006592 }
6593
John McCallb697e082010-05-06 18:15:07 +00006594 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6595
Douglas Gregor063daf62009-03-13 18:40:31 +00006596 // Determine the result type
6597 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00006598 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00006599 ResultTy = ResultTy.getNonReferenceType();
6600
6601 // Build the actual expression node.
6602 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006603 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006604 UsualUnaryConversions(FnExpr);
6605
Anders Carlsson15ea3782009-10-13 22:43:21 +00006606 ExprOwningPtr<CXXOperatorCallExpr>
6607 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6608 Args, 2, ResultTy,
6609 OpLoc));
6610
6611 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6612 FnDecl))
6613 return ExprError();
6614
6615 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006616 } else {
6617 // We matched a built-in operator. Convert the arguments, then
6618 // break out so that we will build the appropriate built-in
6619 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006620 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006621 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006622 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006623 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00006624 return ExprError();
6625
6626 break;
6627 }
6628 }
6629
Douglas Gregor33074752009-09-30 21:46:01 +00006630 case OR_No_Viable_Function: {
6631 // C++ [over.match.oper]p9:
6632 // If the operator is the operator , [...] and there are no
6633 // viable functions, then the operator is assumed to be the
6634 // built-in operator and interpreted according to clause 5.
6635 if (Opc == BinaryOperator::Comma)
6636 break;
6637
Sebastian Redl8593c782009-05-21 11:50:50 +00006638 // For class as left operand for assignment or compound assigment operator
6639 // do not fall through to handling in built-in, but report that no overloaded
6640 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00006641 OwningExprResult Result = ExprError();
6642 if (Args[0]->getType()->isRecordType() &&
6643 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00006644 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6645 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006646 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00006647 } else {
6648 // No viable function; try to create a built-in operation, which will
6649 // produce an error. Then, show the non-viable candidates.
6650 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00006651 }
Douglas Gregor33074752009-09-30 21:46:01 +00006652 assert(Result.isInvalid() &&
6653 "C++ binary operator overloading is missing candidates!");
6654 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00006655 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006656 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00006657 return move(Result);
6658 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006659
6660 case OR_Ambiguous:
6661 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6662 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006663 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006664 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006665 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006666 return ExprError();
6667
6668 case OR_Deleted:
6669 Diag(OpLoc, diag::err_ovl_deleted_oper)
6670 << Best->Function->isDeleted()
6671 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006672 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006673 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00006674 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00006675 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006676
Douglas Gregor33074752009-09-30 21:46:01 +00006677 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006678 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006679}
6680
Sebastian Redlf322ed62009-10-29 20:17:01 +00006681Action::OwningExprResult
6682Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6683 SourceLocation RLoc,
6684 ExprArg Base, ExprArg Idx) {
6685 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6686 static_cast<Expr*>(Idx.get()) };
6687 DeclarationName OpName =
6688 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6689
6690 // If either side is type-dependent, create an appropriate dependent
6691 // expression.
6692 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6693
John McCallc373d482010-01-27 01:50:18 +00006694 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006695 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006696 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006697 0, SourceRange(), OpName, LLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006698 /*ADL*/ true, /*Overloaded*/ false,
6699 UnresolvedSetIterator(),
6700 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00006701 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00006702
6703 Base.release();
6704 Idx.release();
6705 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6706 Args, 2,
6707 Context.DependentTy,
6708 RLoc));
6709 }
6710
6711 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006712 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006713
6714 // Subscript can only be overloaded as a member function.
6715
6716 // Add operator candidates that are member functions.
6717 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6718
6719 // Add builtin operator candidates.
6720 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6721
6722 // Perform overload resolution.
6723 OverloadCandidateSet::iterator Best;
6724 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6725 case OR_Success: {
6726 // We found a built-in operator or an overloaded operator.
6727 FunctionDecl *FnDecl = Best->Function;
6728
6729 if (FnDecl) {
6730 // We matched an overloaded operator. Build a call to that
6731 // operator.
6732
John McCall9aa472c2010-03-19 07:35:19 +00006733 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006734 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00006735
Sebastian Redlf322ed62009-10-29 20:17:01 +00006736 // Convert the arguments.
6737 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006738 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006739 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006740 return ExprError();
6741
Anders Carlsson38f88ab2010-01-29 18:37:50 +00006742 // Convert the arguments.
6743 OwningExprResult InputInit
6744 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6745 FnDecl->getParamDecl(0)),
6746 SourceLocation(),
6747 Owned(Args[1]));
6748 if (InputInit.isInvalid())
6749 return ExprError();
6750
6751 Args[1] = InputInit.takeAs<Expr>();
6752
Sebastian Redlf322ed62009-10-29 20:17:01 +00006753 // Determine the result type
6754 QualType ResultTy
6755 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6756 ResultTy = ResultTy.getNonReferenceType();
6757
6758 // Build the actual expression node.
6759 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6760 LLoc);
6761 UsualUnaryConversions(FnExpr);
6762
6763 Base.release();
6764 Idx.release();
6765 ExprOwningPtr<CXXOperatorCallExpr>
6766 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6767 FnExpr, Args, 2,
6768 ResultTy, RLoc));
6769
6770 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6771 FnDecl))
6772 return ExprError();
6773
6774 return MaybeBindToTemporary(TheCall.release());
6775 } else {
6776 // We matched a built-in operator. Convert the arguments, then
6777 // break out so that we will build the appropriate built-in
6778 // operator node.
6779 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006780 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00006781 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006782 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006783 return ExprError();
6784
6785 break;
6786 }
6787 }
6788
6789 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00006790 if (CandidateSet.empty())
6791 Diag(LLoc, diag::err_ovl_no_oper)
6792 << Args[0]->getType() << /*subscript*/ 0
6793 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6794 else
6795 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6796 << Args[0]->getType()
6797 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006798 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00006799 "[]", LLoc);
6800 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00006801 }
6802
6803 case OR_Ambiguous:
6804 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6805 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006806 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00006807 "[]", LLoc);
6808 return ExprError();
6809
6810 case OR_Deleted:
6811 Diag(LLoc, diag::err_ovl_deleted_oper)
6812 << Best->Function->isDeleted() << "[]"
6813 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006814 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00006815 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006816 return ExprError();
6817 }
6818
6819 // We matched a built-in operator; build it.
6820 Base.release();
6821 Idx.release();
6822 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6823 Owned(Args[1]), RLoc);
6824}
6825
Douglas Gregor88a35142008-12-22 05:46:06 +00006826/// BuildCallToMemberFunction - Build a call to a member
6827/// function. MemExpr is the expression that refers to the member
6828/// function (and includes the object parameter), Args/NumArgs are the
6829/// arguments to the function call (not including the object
6830/// parameter). The caller needs to validate that the member
6831/// expression refers to a member function or an overloaded member
6832/// function.
John McCallaa81e162009-12-01 22:10:20 +00006833Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00006834Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6835 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00006836 unsigned NumArgs, SourceLocation *CommaLocs,
6837 SourceLocation RParenLoc) {
6838 // Dig out the member expression. This holds both the object
6839 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00006840 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6841
John McCall129e2df2009-11-30 22:42:35 +00006842 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00006843 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00006844 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006845 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00006846 if (isa<MemberExpr>(NakedMemExpr)) {
6847 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00006848 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00006849 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00006850 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00006851 } else {
6852 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006853 Qualifier = UnresExpr->getQualifier();
6854
John McCall701c89e2009-12-03 04:06:58 +00006855 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006856
Douglas Gregor88a35142008-12-22 05:46:06 +00006857 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00006858 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00006859
John McCallaa81e162009-12-01 22:10:20 +00006860 // FIXME: avoid copy.
6861 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6862 if (UnresExpr->hasExplicitTemplateArgs()) {
6863 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6864 TemplateArgs = &TemplateArgsBuffer;
6865 }
6866
John McCall129e2df2009-11-30 22:42:35 +00006867 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6868 E = UnresExpr->decls_end(); I != E; ++I) {
6869
John McCall701c89e2009-12-03 04:06:58 +00006870 NamedDecl *Func = *I;
6871 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6872 if (isa<UsingShadowDecl>(Func))
6873 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6874
John McCall129e2df2009-11-30 22:42:35 +00006875 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006876 // If explicit template arguments were provided, we can't call a
6877 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006878 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006879 continue;
6880
John McCall9aa472c2010-03-19 07:35:19 +00006881 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00006882 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006883 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006884 } else {
John McCall129e2df2009-11-30 22:42:35 +00006885 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00006886 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006887 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006888 CandidateSet,
6889 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006890 }
Douglas Gregordec06662009-08-21 18:42:58 +00006891 }
Mike Stump1eb44332009-09-09 15:08:12 +00006892
John McCall129e2df2009-11-30 22:42:35 +00006893 DeclarationName DeclName = UnresExpr->getMemberName();
6894
Douglas Gregor88a35142008-12-22 05:46:06 +00006895 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006896 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006897 case OR_Success:
6898 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00006899 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00006900 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006901 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00006902 break;
6903
6904 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006905 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006906 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006907 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006908 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006909 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006910 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006911
6912 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006913 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006914 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006915 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006916 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006917 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006918
6919 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006920 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006921 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006922 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006923 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006924 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006925 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006926 }
6927
John McCall6bb80172010-03-30 21:47:33 +00006928 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00006929
John McCallaa81e162009-12-01 22:10:20 +00006930 // If overload resolution picked a static member, build a
6931 // non-member call based on that function.
6932 if (Method->isStatic()) {
6933 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6934 Args, NumArgs, RParenLoc);
6935 }
6936
John McCall129e2df2009-11-30 22:42:35 +00006937 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006938 }
6939
6940 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006941 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006942 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006943 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006944 Method->getResultType().getNonReferenceType(),
6945 RParenLoc));
6946
Anders Carlssoneed3e692009-10-10 00:06:20 +00006947 // Check for a valid return type.
6948 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6949 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006950 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006951
Douglas Gregor88a35142008-12-22 05:46:06 +00006952 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00006953 // We only need to do this if there was actually an overload; otherwise
6954 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00006955 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006956 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00006957 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6958 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00006959 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006960 MemExpr->setBase(ObjectArg);
6961
6962 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00006963 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006964 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006965 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006966 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006967
Anders Carlssond406bf02009-08-16 01:56:34 +00006968 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006969 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006970
John McCallaa81e162009-12-01 22:10:20 +00006971 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006972}
6973
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006974/// BuildCallToObjectOfClassType - Build a call to an object of class
6975/// type (C++ [over.call.object]), which can end up invoking an
6976/// overloaded function call operator (@c operator()) or performing a
6977/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006978Sema::ExprResult
6979Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006980 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006981 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006982 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006983 SourceLocation RParenLoc) {
6984 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006985 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006986
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006987 // C++ [over.call.object]p1:
6988 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006989 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006990 // candidate functions includes at least the function call
6991 // operators of T. The function call operators of T are obtained by
6992 // ordinary lookup of the name operator() in the context of
6993 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00006994 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006995 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006996
6997 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006998 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00006999 << Object->getSourceRange()))
7000 return true;
7001
John McCalla24dc2e2009-11-17 02:14:36 +00007002 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7003 LookupQualifiedName(R, Record->getDecl());
7004 R.suppressDiagnostics();
7005
Douglas Gregor593564b2009-11-15 07:48:03 +00007006 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007007 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007008 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007009 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007010 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007011 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007012
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007013 // C++ [over.call.object]p2:
7014 // In addition, for each conversion function declared in T of the
7015 // form
7016 //
7017 // operator conversion-type-id () cv-qualifier;
7018 //
7019 // where cv-qualifier is the same cv-qualification as, or a
7020 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007021 // denotes the type "pointer to function of (P1,...,Pn) returning
7022 // R", or the type "reference to pointer to function of
7023 // (P1,...,Pn) returning R", or the type "reference to function
7024 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007025 // is also considered as a candidate function. Similarly,
7026 // surrogate call functions are added to the set of candidate
7027 // functions for each conversion function declared in an
7028 // accessible base class provided the function is not hidden
7029 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007030 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007031 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007032 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007033 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007034 NamedDecl *D = *I;
7035 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7036 if (isa<UsingShadowDecl>(D))
7037 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7038
Douglas Gregor4a27d702009-10-21 06:18:39 +00007039 // Skip over templated conversion functions; they aren't
7040 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007041 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007042 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007043
John McCall701c89e2009-12-03 04:06:58 +00007044 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007045
Douglas Gregor4a27d702009-10-21 06:18:39 +00007046 // Strip the reference type (if any) and then the pointer type (if
7047 // any) to get down to what might be a function type.
7048 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7049 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7050 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007051
Douglas Gregor4a27d702009-10-21 06:18:39 +00007052 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007053 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007054 Object->getType(), Args, NumArgs,
7055 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007056 }
Mike Stump1eb44332009-09-09 15:08:12 +00007057
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007058 // Perform overload resolution.
7059 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007060 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007061 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007062 // Overload resolution succeeded; we'll build the appropriate call
7063 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007064 break;
7065
7066 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007067 if (CandidateSet.empty())
7068 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7069 << Object->getType() << /*call*/ 1
7070 << Object->getSourceRange();
7071 else
7072 Diag(Object->getSourceRange().getBegin(),
7073 diag::err_ovl_no_viable_object_call)
7074 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007075 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007076 break;
7077
7078 case OR_Ambiguous:
7079 Diag(Object->getSourceRange().getBegin(),
7080 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007081 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007082 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007083 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007084
7085 case OR_Deleted:
7086 Diag(Object->getSourceRange().getBegin(),
7087 diag::err_ovl_deleted_object_call)
7088 << Best->Function->isDeleted()
7089 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007090 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007091 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007092 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007093
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007094 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007095 // We had an error; delete all of the subexpressions and return
7096 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007097 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007098 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007099 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007100 return true;
7101 }
7102
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007103 if (Best->Function == 0) {
7104 // Since there is no function declaration, this is one of the
7105 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007106 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007107 = cast<CXXConversionDecl>(
7108 Best->Conversions[0].UserDefined.ConversionFunction);
7109
John McCall9aa472c2010-03-19 07:35:19 +00007110 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007111 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007112
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007113 // We selected one of the surrogate functions that converts the
7114 // object parameter to a function pointer. Perform the conversion
7115 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007116
7117 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007118 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007119 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7120 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007121
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007122 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00007123 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00007124 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007125 }
7126
John McCall9aa472c2010-03-19 07:35:19 +00007127 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007128 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007129
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007130 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7131 // that calls this method, using Object for the implicit object
7132 // parameter and passing along the remaining arguments.
7133 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007134 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007135
7136 unsigned NumArgsInProto = Proto->getNumArgs();
7137 unsigned NumArgsToCheck = NumArgs;
7138
7139 // Build the full argument list for the method call (the
7140 // implicit object parameter is placed at the beginning of the
7141 // list).
7142 Expr **MethodArgs;
7143 if (NumArgs < NumArgsInProto) {
7144 NumArgsToCheck = NumArgsInProto;
7145 MethodArgs = new Expr*[NumArgsInProto + 1];
7146 } else {
7147 MethodArgs = new Expr*[NumArgs + 1];
7148 }
7149 MethodArgs[0] = Object;
7150 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7151 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007152
7153 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007154 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007155 UsualUnaryConversions(NewFn);
7156
7157 // Once we've built TheCall, all of the expressions are properly
7158 // owned.
7159 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00007160 ExprOwningPtr<CXXOperatorCallExpr>
7161 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00007162 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00007163 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007164 delete [] MethodArgs;
7165
Anders Carlsson07d68f12009-10-13 21:49:31 +00007166 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7167 Method))
7168 return true;
7169
Douglas Gregor518fda12009-01-13 05:10:00 +00007170 // We may have default arguments. If so, we need to allocate more
7171 // slots in the call for them.
7172 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007173 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007174 else if (NumArgs > NumArgsInProto)
7175 NumArgsToCheck = NumArgsInProto;
7176
Chris Lattner312531a2009-04-12 08:11:20 +00007177 bool IsError = false;
7178
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007179 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007180 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007181 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007182 TheCall->setArg(0, Object);
7183
Chris Lattner312531a2009-04-12 08:11:20 +00007184
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007185 // Check the argument types.
7186 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007187 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007188 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007189 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007190
Douglas Gregor518fda12009-01-13 05:10:00 +00007191 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007192
7193 OwningExprResult InputInit
7194 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7195 Method->getParamDecl(i)),
7196 SourceLocation(), Owned(Arg));
7197
7198 IsError |= InputInit.isInvalid();
7199 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007200 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00007201 OwningExprResult DefArg
7202 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7203 if (DefArg.isInvalid()) {
7204 IsError = true;
7205 break;
7206 }
7207
7208 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007209 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007210
7211 TheCall->setArg(i + 1, Arg);
7212 }
7213
7214 // If this is a variadic call, handle args passed through "...".
7215 if (Proto->isVariadic()) {
7216 // Promote the arguments (C99 6.5.2.2p7).
7217 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7218 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007219 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007220 TheCall->setArg(i + 1, Arg);
7221 }
7222 }
7223
Chris Lattner312531a2009-04-12 08:11:20 +00007224 if (IsError) return true;
7225
Anders Carlssond406bf02009-08-16 01:56:34 +00007226 if (CheckFunctionCall(Method, TheCall.get()))
7227 return true;
7228
Douglas Gregoraa0be172010-04-13 15:50:39 +00007229 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007230}
7231
Douglas Gregor8ba10742008-11-20 16:27:02 +00007232/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007233/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007234/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007235Sema::OwningExprResult
7236Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7237 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007238 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007239
John McCall5769d612010-02-08 23:07:23 +00007240 SourceLocation Loc = Base->getExprLoc();
7241
Douglas Gregor8ba10742008-11-20 16:27:02 +00007242 // C++ [over.ref]p1:
7243 //
7244 // [...] An expression x->m is interpreted as (x.operator->())->m
7245 // for a class object x of type T if T::operator->() exists and if
7246 // the operator is selected as the best match function by the
7247 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007248 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007249 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007250 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007251
John McCall5769d612010-02-08 23:07:23 +00007252 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007253 PDiag(diag::err_typecheck_incomplete_tag)
7254 << Base->getSourceRange()))
7255 return ExprError();
7256
John McCalla24dc2e2009-11-17 02:14:36 +00007257 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7258 LookupQualifiedName(R, BaseRecord->getDecl());
7259 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007260
7261 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007262 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007263 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007264 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007265 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007266
7267 // Perform overload resolution.
7268 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007269 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007270 case OR_Success:
7271 // Overload resolution succeeded; we'll build the call below.
7272 break;
7273
7274 case OR_No_Viable_Function:
7275 if (CandidateSet.empty())
7276 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007277 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007278 else
7279 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007280 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007281 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007282 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007283
7284 case OR_Ambiguous:
7285 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007286 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007287 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007288 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007289
7290 case OR_Deleted:
7291 Diag(OpLoc, diag::err_ovl_deleted_oper)
7292 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007293 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007294 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007295 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007296 }
7297
John McCall9aa472c2010-03-19 07:35:19 +00007298 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007299 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007300
Douglas Gregor8ba10742008-11-20 16:27:02 +00007301 // Convert the object parameter.
7302 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007303 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7304 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007305 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007306
7307 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007308 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007309
7310 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007311 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7312 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007313 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007314
7315 QualType ResultTy = Method->getResultType().getNonReferenceType();
7316 ExprOwningPtr<CXXOperatorCallExpr>
7317 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7318 &Base, 1, ResultTy, OpLoc));
7319
7320 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7321 Method))
7322 return ExprError();
7323 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007324}
7325
Douglas Gregor904eed32008-11-10 20:40:00 +00007326/// FixOverloadedFunctionReference - E is an expression that refers to
7327/// a C++ overloaded function (possibly with some parentheses and
7328/// perhaps a '&' around it). We have resolved the overloaded function
7329/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007330/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007331Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007332 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007333 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007334 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7335 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007336 if (SubExpr == PE->getSubExpr())
7337 return PE->Retain();
7338
7339 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7340 }
7341
7342 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007343 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7344 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007345 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007346 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007347 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00007348 if (SubExpr == ICE->getSubExpr())
7349 return ICE->Retain();
7350
7351 return new (Context) ImplicitCastExpr(ICE->getType(),
7352 ICE->getCastKind(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00007353 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007354 ICE->isLvalueCast());
7355 }
7356
7357 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007358 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007359 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007360 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7361 if (Method->isStatic()) {
7362 // Do nothing: static member functions aren't any different
7363 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007364 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007365 // Fix the sub expression, which really has to be an
7366 // UnresolvedLookupExpr holding an overloaded member function
7367 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007368 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7369 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007370 if (SubExpr == UnOp->getSubExpr())
7371 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007372
John McCallba135432009-11-21 08:51:07 +00007373 assert(isa<DeclRefExpr>(SubExpr)
7374 && "fixed to something other than a decl ref");
7375 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7376 && "fixed to a member ref with no nested name qualifier");
7377
7378 // We have taken the address of a pointer to member
7379 // function. Perform the computation here so that we get the
7380 // appropriate pointer to member type.
7381 QualType ClassType
7382 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7383 QualType MemPtrType
7384 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7385
7386 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7387 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007388 }
7389 }
John McCall6bb80172010-03-30 21:47:33 +00007390 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7391 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007392 if (SubExpr == UnOp->getSubExpr())
7393 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007394
Douglas Gregor699ee522009-11-20 19:42:02 +00007395 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7396 Context.getPointerType(SubExpr->getType()),
7397 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007398 }
John McCallba135432009-11-21 08:51:07 +00007399
7400 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007401 // FIXME: avoid copy.
7402 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007403 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007404 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7405 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007406 }
7407
John McCallba135432009-11-21 08:51:07 +00007408 return DeclRefExpr::Create(Context,
7409 ULE->getQualifier(),
7410 ULE->getQualifierRange(),
7411 Fn,
7412 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007413 Fn->getType(),
7414 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007415 }
7416
John McCall129e2df2009-11-30 22:42:35 +00007417 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007418 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007419 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7420 if (MemExpr->hasExplicitTemplateArgs()) {
7421 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7422 TemplateArgs = &TemplateArgsBuffer;
7423 }
John McCalld5532b62009-11-23 01:53:49 +00007424
John McCallaa81e162009-12-01 22:10:20 +00007425 Expr *Base;
7426
7427 // If we're filling in
7428 if (MemExpr->isImplicitAccess()) {
7429 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7430 return DeclRefExpr::Create(Context,
7431 MemExpr->getQualifier(),
7432 MemExpr->getQualifierRange(),
7433 Fn,
7434 MemExpr->getMemberLoc(),
7435 Fn->getType(),
7436 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007437 } else {
7438 SourceLocation Loc = MemExpr->getMemberLoc();
7439 if (MemExpr->getQualifier())
7440 Loc = MemExpr->getQualifierRange().getBegin();
7441 Base = new (Context) CXXThisExpr(Loc,
7442 MemExpr->getBaseType(),
7443 /*isImplicit=*/true);
7444 }
John McCallaa81e162009-12-01 22:10:20 +00007445 } else
7446 Base = MemExpr->getBase()->Retain();
7447
7448 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007449 MemExpr->isArrow(),
7450 MemExpr->getQualifier(),
7451 MemExpr->getQualifierRange(),
7452 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007453 Found,
John McCalld5532b62009-11-23 01:53:49 +00007454 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007455 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007456 Fn->getType());
7457 }
7458
Douglas Gregor699ee522009-11-20 19:42:02 +00007459 assert(false && "Invalid reference to overloaded function");
7460 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007461}
7462
Douglas Gregor20093b42009-12-09 23:02:17 +00007463Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00007464 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00007465 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007466 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007467}
7468
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007469} // end namespace clang