blob: d82f8854080cd92a85e3bb7caf0e12e08d46e3fc [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035
John McCall5c32be02010-08-24 20:38:10 +000036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
37 bool InOverloadResolution,
38 StandardConversionSequence &SCS);
39static OverloadingResult
40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
41 UserDefinedConversionSequence& User,
42 OverloadCandidateSet& Conversions,
43 bool AllowExplicit);
44
45
46static ImplicitConversionSequence::CompareKind
47CompareStandardConversionSequences(Sema &S,
48 const StandardConversionSequence& SCS1,
49 const StandardConversionSequence& SCS2);
50
51static ImplicitConversionSequence::CompareKind
52CompareQualificationConversions(Sema &S,
53 const StandardConversionSequence& SCS1,
54 const StandardConversionSequence& SCS2);
55
56static ImplicitConversionSequence::CompareKind
57CompareDerivedToBaseConversions(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61
62
Douglas Gregor5251f1b2008-10-21 16:13:35 +000063/// GetConversionCategory - Retrieve the implicit conversion
64/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000065ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000066GetConversionCategory(ImplicitConversionKind Kind) {
67 static const ImplicitConversionCategory
68 Category[(int)ICK_Num_Conversion_Kinds] = {
69 ICC_Identity,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
72 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000073 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICC_Qualification_Adjustment,
75 ICC_Promotion,
76 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000077 ICC_Promotion,
78 ICC_Conversion,
79 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000080 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
84 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000085 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000086 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000087 ICC_Conversion,
88 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089 ICC_Conversion
90 };
91 return Category[(int)Kind];
92}
93
94/// GetConversionRank - Retrieve the implicit conversion rank
95/// corresponding to the given implicit conversion kind.
96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
97 static const ImplicitConversionRank
98 Rank[(int)ICK_Num_Conversion_Kinds] = {
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
103 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000104 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 ICR_Promotion,
106 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000107 ICR_Promotion,
108 ICR_Conversion,
109 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
114 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000115 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000116 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000117 ICR_Conversion,
118 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000119 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000120 };
121 return Rank[(int)Kind];
122}
123
124/// GetImplicitConversionName - Return the name of this kind of
125/// implicit conversion.
126const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128 "No conversion",
129 "Lvalue-to-rvalue",
130 "Array-to-pointer",
131 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000132 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 "Qualification",
134 "Integral promotion",
135 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000136 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 "Integral conversion",
138 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000139 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000140 "Floating-integral conversion",
141 "Pointer conversion",
142 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000143 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000144 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000145 "Derived-to-base conversion",
146 "Vector conversion",
147 "Vector splat",
148 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 };
150 return Name[Kind];
151}
152
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000153/// StandardConversionSequence - Set the standard conversion
154/// sequence to the identity conversion.
155void StandardConversionSequence::setAsIdentityConversion() {
156 First = ICK_Identity;
157 Second = ICK_Identity;
158 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000159 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000160 ReferenceBinding = false;
161 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000162 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000163 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000164}
165
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000166/// getRank - Retrieve the rank of this standard conversion sequence
167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
168/// implicit conversions.
169ImplicitConversionRank StandardConversionSequence::getRank() const {
170 ImplicitConversionRank Rank = ICR_Exact_Match;
171 if (GetConversionRank(First) > Rank)
172 Rank = GetConversionRank(First);
173 if (GetConversionRank(Second) > Rank)
174 Rank = GetConversionRank(Second);
175 if (GetConversionRank(Third) > Rank)
176 Rank = GetConversionRank(Third);
177 return Rank;
178}
179
180/// isPointerConversionToBool - Determines whether this conversion is
181/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000182/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000184bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000185 // Note that FromType has not necessarily been transformed by the
186 // array-to-pointer or function-to-pointer implicit conversions, so
187 // check for their presence as well as checking whether FromType is
188 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000189 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000190 (getFromType()->isPointerType() ||
191 getFromType()->isObjCObjectPointerType() ||
192 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000193 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
195 return true;
196
197 return false;
198}
199
Douglas Gregor5c407d92008-10-23 00:40:37 +0000200/// isPointerConversionToVoidPointer - Determines whether this
201/// conversion is a conversion of a pointer to a void pointer. This is
202/// used as part of the ranking of standard conversion sequences (C++
203/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000204bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000205StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000206isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000207 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000208 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000209
210 // Note that FromType has not necessarily been transformed by the
211 // array-to-pointer implicit conversion, so check for its presence
212 // and redo the conversion to get a pointer.
213 if (First == ICK_Array_To_Pointer)
214 FromType = Context.getArrayDecayedType(FromType);
215
John McCall75851b12010-10-26 06:40:27 +0000216 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000217 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000218 return ToPtrType->getPointeeType()->isVoidType();
219
220 return false;
221}
222
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223/// DebugPrint - Print this standard conversion sequence to standard
224/// error. Useful for debugging overloading issues.
225void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000226 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000227 bool PrintedSomething = false;
228 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000229 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 PrintedSomething = true;
231 }
232
233 if (Second != ICK_Identity) {
234 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000237 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000238
239 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000240 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000241 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000243 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000244 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000245 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000246 PrintedSomething = true;
247 }
248
249 if (Third != ICK_Identity) {
250 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000251 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000252 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000254 PrintedSomething = true;
255 }
256
257 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000258 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000259 }
260}
261
262/// DebugPrint - Print this user-defined conversion sequence to standard
263/// error. Useful for debugging overloading issues.
264void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000265 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000266 if (Before.First || Before.Second || Before.Third) {
267 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000270 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000271 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000272 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273 After.DebugPrint();
274 }
275}
276
277/// DebugPrint - Print this implicit conversion sequence to standard
278/// error. Useful for debugging overloading issues.
279void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 switch (ConversionKind) {
282 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000283 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 Standard.DebugPrint();
285 break;
286 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000287 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288 UserDefined.DebugPrint();
289 break;
290 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000291 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000292 break;
John McCall0d1da222010-01-12 00:44:57 +0000293 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000294 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000295 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000297 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000298 break;
299 }
300
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000301 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000302}
303
John McCall0d1da222010-01-12 00:44:57 +0000304void AmbiguousConversionSequence::construct() {
305 new (&conversions()) ConversionSet();
306}
307
308void AmbiguousConversionSequence::destruct() {
309 conversions().~ConversionSet();
310}
311
312void
313AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
314 FromTypePtr = O.FromTypePtr;
315 ToTypePtr = O.ToTypePtr;
316 new (&conversions()) ConversionSet(O.conversions());
317}
318
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000319namespace {
320 // Structure used by OverloadCandidate::DeductionFailureInfo to store
321 // template parameter and template argument information.
322 struct DFIParamWithArguments {
323 TemplateParameter Param;
324 TemplateArgument FirstArg;
325 TemplateArgument SecondArg;
326 };
327}
328
329/// \brief Convert from Sema's representation of template deduction information
330/// to the form used in overload-candidate information.
331OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000332static MakeDeductionFailureInfo(ASTContext &Context,
333 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000334 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000335 OverloadCandidate::DeductionFailureInfo Result;
336 Result.Result = static_cast<unsigned>(TDK);
337 Result.Data = 0;
338 switch (TDK) {
339 case Sema::TDK_Success:
340 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000341 case Sema::TDK_TooManyArguments:
342 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000343 break;
344
345 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000346 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000347 Result.Data = Info.Param.getOpaqueValue();
348 break;
349
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000352 // FIXME: Should allocate from normal heap so that we can free this later.
353 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354 Saved->Param = Info.Param;
355 Saved->FirstArg = Info.FirstArg;
356 Saved->SecondArg = Info.SecondArg;
357 Result.Data = Saved;
358 break;
359 }
360
361 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000362 Result.Data = Info.take();
363 break;
364
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000366 case Sema::TDK_FailedOverloadResolution:
367 break;
368 }
369
370 return Result;
371}
John McCall0d1da222010-01-12 00:44:57 +0000372
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000373void OverloadCandidate::DeductionFailureInfo::Destroy() {
374 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
375 case Sema::TDK_Success:
376 case Sema::TDK_InstantiationDepth:
377 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000378 case Sema::TDK_TooManyArguments:
379 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000380 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 break;
382
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000383 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000384 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000385 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 Data = 0;
387 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000388
389 case Sema::TDK_SubstitutionFailure:
390 // FIXME: Destroy the template arugment list?
391 Data = 0;
392 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393
Douglas Gregor461761d2010-05-08 18:20:53 +0000394 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 case Sema::TDK_FailedOverloadResolution:
397 break;
398 }
399}
400
401TemplateParameter
402OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
403 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
404 case Sema::TDK_Success:
405 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000406 case Sema::TDK_TooManyArguments:
407 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000408 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000409 return TemplateParameter();
410
411 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000412 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000413 return TemplateParameter::getFromOpaqueValue(Data);
414
415 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000416 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000417 return static_cast<DFIParamWithArguments*>(Data)->Param;
418
419 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000421 case Sema::TDK_FailedOverloadResolution:
422 break;
423 }
424
425 return TemplateParameter();
426}
Douglas Gregord09efd42010-05-08 20:07:26 +0000427
428TemplateArgumentList *
429OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
435 case Sema::TDK_Incomplete:
436 case Sema::TDK_InvalidExplicitArguments:
437 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000438 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000439 return 0;
440
441 case Sema::TDK_SubstitutionFailure:
442 return static_cast<TemplateArgumentList*>(Data);
443
444 // Unhandled
445 case Sema::TDK_NonDeducedMismatch:
446 case Sema::TDK_FailedOverloadResolution:
447 break;
448 }
449
450 return 0;
451}
452
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000453const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
454 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
455 case Sema::TDK_Success:
456 case Sema::TDK_InstantiationDepth:
457 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000458 case Sema::TDK_TooManyArguments:
459 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000460 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000461 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 return 0;
463
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000464 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000466 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
467
Douglas Gregor461761d2010-05-08 18:20:53 +0000468 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000469 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000470 case Sema::TDK_FailedOverloadResolution:
471 break;
472 }
473
474 return 0;
475}
476
477const TemplateArgument *
478OverloadCandidate::DeductionFailureInfo::getSecondArg() {
479 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
480 case Sema::TDK_Success:
481 case Sema::TDK_InstantiationDepth:
482 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000483 case Sema::TDK_TooManyArguments:
484 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000485 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000486 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000487 return 0;
488
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000490 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000491 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
492
Douglas Gregor461761d2010-05-08 18:20:53 +0000493 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000495 case Sema::TDK_FailedOverloadResolution:
496 break;
497 }
498
499 return 0;
500}
501
502void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503 inherited::clear();
504 Functions.clear();
505}
506
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000508// overload of the declarations in Old. This routine returns false if
509// New and Old cannot be overloaded, e.g., if New has the same
510// signature as some function in Old (C++ 1.3.10) or if the Old
511// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000512// it does return false, MatchedDecl will point to the decl that New
513// cannot be overloaded with. This decl may be a UsingShadowDecl on
514// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515//
516// Example: Given the following input:
517//
518// void f(int, float); // #1
519// void f(int, int); // #2
520// int f(int, int); // #3
521//
522// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000523// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524//
John McCall3d988d92009-12-02 08:47:38 +0000525// When we process #2, Old contains only the FunctionDecl for #1. By
526// comparing the parameter types, we see that #1 and #2 are overloaded
527// (since they have different signatures), so this routine returns
528// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529//
John McCall3d988d92009-12-02 08:47:38 +0000530// When we process #3, Old is an overload set containing #1 and #2. We
531// compare the signatures of #3 to #1 (they're overloaded, so we do
532// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
533// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534// signature), IsOverload returns false and MatchedDecl will be set to
535// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000536//
537// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
538// into a class by a using declaration. The rules for whether to hide
539// shadow declarations ignore some properties which otherwise figure
540// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000541Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000542Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
543 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000544 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000545 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000546 NamedDecl *OldD = *I;
547
548 bool OldIsUsingDecl = false;
549 if (isa<UsingShadowDecl>(OldD)) {
550 OldIsUsingDecl = true;
551
552 // We can always introduce two using declarations into the same
553 // context, even if they have identical signatures.
554 if (NewIsUsingDecl) continue;
555
556 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
557 }
558
559 // If either declaration was introduced by a using declaration,
560 // we'll need to use slightly different rules for matching.
561 // Essentially, these rules are the normal rules, except that
562 // function templates hide function templates with different
563 // return types or template parameter lists.
564 bool UseMemberUsingDeclRules =
565 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
566
John McCall3d988d92009-12-02 08:47:38 +0000567 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000568 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
569 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
570 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
571 continue;
572 }
573
John McCalldaa3d6b2009-12-09 03:35:25 +0000574 Match = *I;
575 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000576 }
John McCall3d988d92009-12-02 08:47:38 +0000577 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000578 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
579 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
580 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
581 continue;
582 }
583
John McCalldaa3d6b2009-12-09 03:35:25 +0000584 Match = *I;
585 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000586 }
John McCalla8987a2942010-11-10 03:01:53 +0000587 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000588 // We can overload with these, which can show up when doing
589 // redeclaration checks for UsingDecls.
590 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000591 } else if (isa<TagDecl>(OldD)) {
592 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000593 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
594 // Optimistically assume that an unresolved using decl will
595 // overload; if it doesn't, we'll have to diagnose during
596 // template instantiation.
597 } else {
John McCall1f82f242009-11-18 22:49:29 +0000598 // (C++ 13p1):
599 // Only function declarations can be overloaded; object and type
600 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000603 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000604 }
John McCall1f82f242009-11-18 22:49:29 +0000605
John McCalldaa3d6b2009-12-09 03:35:25 +0000606 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000607}
608
John McCalle9cccd82010-06-16 08:42:20 +0000609bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
610 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000611 // If both of the functions are extern "C", then they are not
612 // overloads.
613 if (Old->isExternC() && New->isExternC())
614 return false;
615
John McCall1f82f242009-11-18 22:49:29 +0000616 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
617 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
618
619 // C++ [temp.fct]p2:
620 // A function template can be overloaded with other function templates
621 // and with normal (non-template) functions.
622 if ((OldTemplate == 0) != (NewTemplate == 0))
623 return true;
624
625 // Is the function New an overload of the function Old?
626 QualType OldQType = Context.getCanonicalType(Old->getType());
627 QualType NewQType = Context.getCanonicalType(New->getType());
628
629 // Compare the signatures (C++ 1.3.10) of the two functions to
630 // determine whether they are overloads. If we find any mismatch
631 // in the signature, they are overloads.
632
633 // If either of these functions is a K&R-style function (no
634 // prototype), then we consider them to have matching signatures.
635 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
636 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
637 return false;
638
639 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
640 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
641
642 // The signature of a function includes the types of its
643 // parameters (C++ 1.3.10), which includes the presence or absence
644 // of the ellipsis; see C++ DR 357).
645 if (OldQType != NewQType &&
646 (OldType->getNumArgs() != NewType->getNumArgs() ||
647 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000648 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000649 return true;
650
651 // C++ [temp.over.link]p4:
652 // The signature of a function template consists of its function
653 // signature, its return type and its template parameter list. The names
654 // of the template parameters are significant only for establishing the
655 // relationship between the template parameters and the rest of the
656 // signature.
657 //
658 // We check the return type and template parameter lists for function
659 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000660 //
661 // However, we don't consider either of these when deciding whether
662 // a member introduced by a shadow declaration is hidden.
663 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000664 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
665 OldTemplate->getTemplateParameters(),
666 false, TPL_TemplateMatch) ||
667 OldType->getResultType() != NewType->getResultType()))
668 return true;
669
670 // If the function is a class member, its signature includes the
671 // cv-qualifiers (if any) on the function itself.
672 //
673 // As part of this, also check whether one of the member functions
674 // is static, in which case they are not overloads (C++
675 // 13.1p2). While not part of the definition of the signature,
676 // this check is important to determine whether these functions
677 // can be overloaded.
678 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
679 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
680 if (OldMethod && NewMethod &&
681 !OldMethod->isStatic() && !NewMethod->isStatic() &&
682 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
683 return true;
684
685 // The signatures match; this is not an overload.
686 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000687}
688
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000689/// TryImplicitConversion - Attempt to perform an implicit conversion
690/// from the given expression (Expr) to the given type (ToType). This
691/// function returns an implicit conversion sequence that can be used
692/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000693///
694/// void f(float f);
695/// void g(int i) { f(i); }
696///
697/// this routine would produce an implicit conversion sequence to
698/// describe the initialization of f from i, which will be a standard
699/// conversion sequence containing an lvalue-to-rvalue conversion (C++
700/// 4.1) followed by a floating-integral conversion (C++ 4.9).
701//
702/// Note that this routine only determines how the conversion can be
703/// performed; it does not actually perform the conversion. As such,
704/// it will not produce any diagnostics if no conversion is available,
705/// but will instead return an implicit conversion sequence of kind
706/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000707///
708/// If @p SuppressUserConversions, then user-defined conversions are
709/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000710/// If @p AllowExplicit, then explicit user-defined conversions are
711/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000712static ImplicitConversionSequence
713TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
714 bool SuppressUserConversions,
715 bool AllowExplicit,
716 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000717 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000718 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
719 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000720 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000721 return ICS;
722 }
723
John McCall5c32be02010-08-24 20:38:10 +0000724 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000725 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000726 return ICS;
727 }
728
Douglas Gregor836a7e82010-08-11 02:15:33 +0000729 // C++ [over.ics.user]p4:
730 // A conversion of an expression of class type to the same class
731 // type is given Exact Match rank, and a conversion of an
732 // expression of class type to a base class of that type is
733 // given Conversion rank, in spite of the fact that a copy/move
734 // constructor (i.e., a user-defined conversion function) is
735 // called for those cases.
736 QualType FromType = From->getType();
737 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000738 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
739 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000740 ICS.setStandard();
741 ICS.Standard.setAsIdentityConversion();
742 ICS.Standard.setFromType(FromType);
743 ICS.Standard.setAllToTypes(ToType);
744
745 // We don't actually check at this point whether there is a valid
746 // copy/move constructor, since overloading just assumes that it
747 // exists. When we actually perform initialization, we'll find the
748 // appropriate constructor to copy the returned object, if needed.
749 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000750
Douglas Gregor5ab11652010-04-17 22:01:05 +0000751 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000752 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000753 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000754
755 return ICS;
756 }
757
758 if (SuppressUserConversions) {
759 // We're not in the case above, so there is no conversion that
760 // we can perform.
761 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000762 return ICS;
763 }
764
765 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000766 OverloadCandidateSet Conversions(From->getExprLoc());
767 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000768 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000769 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000770
771 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000772 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000773 // C++ [over.ics.user]p4:
774 // A conversion of an expression of class type to the same class
775 // type is given Exact Match rank, and a conversion of an
776 // expression of class type to a base class of that type is
777 // given Conversion rank, in spite of the fact that a copy
778 // constructor (i.e., a user-defined conversion function) is
779 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000780 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000781 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000782 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000783 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
784 QualType ToCanon
785 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000786 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000787 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000788 // Turn this into a "standard" conversion sequence, so that it
789 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000790 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000791 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000792 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000793 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000794 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000795 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000796 ICS.Standard.Second = ICK_Derived_To_Base;
797 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000798 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000799
800 // C++ [over.best.ics]p4:
801 // However, when considering the argument of a user-defined
802 // conversion function that is a candidate by 13.3.1.3 when
803 // invoked for the copying of the temporary in the second step
804 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
805 // 13.3.1.6 in all cases, only standard conversion sequences and
806 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000807 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000808 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000809 }
John McCalle8c8cd22010-01-13 22:30:33 +0000810 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000811 ICS.setAmbiguous();
812 ICS.Ambiguous.setFromType(From->getType());
813 ICS.Ambiguous.setToType(ToType);
814 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
815 Cand != Conversions.end(); ++Cand)
816 if (Cand->Viable)
817 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000818 } else {
John McCall65eb8792010-02-25 01:37:24 +0000819 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000820 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000821
822 return ICS;
823}
824
John McCall5c32be02010-08-24 20:38:10 +0000825bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
826 const InitializedEntity &Entity,
827 Expr *Initializer,
828 bool SuppressUserConversions,
829 bool AllowExplicitConversions,
830 bool InOverloadResolution) {
831 ImplicitConversionSequence ICS
832 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
833 SuppressUserConversions,
834 AllowExplicitConversions,
835 InOverloadResolution);
836 if (ICS.isBad()) return true;
837
838 // Perform the actual conversion.
839 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
840 return false;
841}
842
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000843/// PerformImplicitConversion - Perform an implicit conversion of the
844/// expression From to the type ToType. Returns true if there was an
845/// error, false otherwise. The expression From is replaced with the
846/// converted expression. Flavor is the kind of conversion we're
847/// performing, used in the error message. If @p AllowExplicit,
848/// explicit user-defined conversions are permitted.
849bool
850Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
851 AssignmentAction Action, bool AllowExplicit) {
852 ImplicitConversionSequence ICS;
853 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
854}
855
856bool
857Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
858 AssignmentAction Action, bool AllowExplicit,
859 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000860 ICS = clang::TryImplicitConversion(*this, From, ToType,
861 /*SuppressUserConversions=*/false,
862 AllowExplicit,
863 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000864 return PerformImplicitConversion(From, ToType, ICS, Action);
865}
866
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000867/// \brief Determine whether the conversion from FromType to ToType is a valid
868/// conversion that strips "noreturn" off the nested function type.
869static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
870 QualType ToType, QualType &ResultTy) {
871 if (Context.hasSameUnqualifiedType(FromType, ToType))
872 return false;
873
874 // Strip the noreturn off the type we're converting from; noreturn can
875 // safely be removed.
876 FromType = Context.getNoReturnType(FromType, false);
877 if (!Context.hasSameUnqualifiedType(FromType, ToType))
878 return false;
879
880 ResultTy = FromType;
881 return true;
882}
Douglas Gregor46188682010-05-18 22:42:18 +0000883
884/// \brief Determine whether the conversion from FromType to ToType is a valid
885/// vector conversion.
886///
887/// \param ICK Will be set to the vector conversion kind, if this is a vector
888/// conversion.
889static bool IsVectorConversion(ASTContext &Context, QualType FromType,
890 QualType ToType, ImplicitConversionKind &ICK) {
891 // We need at least one of these types to be a vector type to have a vector
892 // conversion.
893 if (!ToType->isVectorType() && !FromType->isVectorType())
894 return false;
895
896 // Identical types require no conversions.
897 if (Context.hasSameUnqualifiedType(FromType, ToType))
898 return false;
899
900 // There are no conversions between extended vector types, only identity.
901 if (ToType->isExtVectorType()) {
902 // There are no conversions between extended vector types other than the
903 // identity conversion.
904 if (FromType->isExtVectorType())
905 return false;
906
907 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000908 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000909 ICK = ICK_Vector_Splat;
910 return true;
911 }
912 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000913
914 // We can perform the conversion between vector types in the following cases:
915 // 1)vector types are equivalent AltiVec and GCC vector types
916 // 2)lax vector conversions are permitted and the vector types are of the
917 // same size
918 if (ToType->isVectorType() && FromType->isVectorType()) {
919 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000920 (Context.getLangOptions().LaxVectorConversions &&
921 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000922 ICK = ICK_Vector_Conversion;
923 return true;
924 }
Douglas Gregor46188682010-05-18 22:42:18 +0000925 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000926
Douglas Gregor46188682010-05-18 22:42:18 +0000927 return false;
928}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000929
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000930/// IsStandardConversion - Determines whether there is a standard
931/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
932/// expression From to the type ToType. Standard conversion sequences
933/// only consider non-class types; for conversions that involve class
934/// types, use TryImplicitConversion. If a conversion exists, SCS will
935/// contain the standard conversion sequence required to perform this
936/// conversion and this routine will return true. Otherwise, this
937/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000938static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
939 bool InOverloadResolution,
940 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000941 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000942
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000943 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000944 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000945 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000946 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000947 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000948 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000949
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000950 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000951 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000952 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000953 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000954 return false;
955
Mike Stump11289f42009-09-09 15:08:12 +0000956 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000957 }
958
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000959 // The first conversion can be an lvalue-to-rvalue conversion,
960 // array-to-pointer conversion, or function-to-pointer conversion
961 // (C++ 4p1).
962
John McCall5c32be02010-08-24 20:38:10 +0000963 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000964 DeclAccessPair AccessPair;
965 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +0000966 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
967 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000968 // We were able to resolve the address of the overloaded function,
969 // so we can convert to the type of that function.
970 FromType = Fn->getType();
971 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
972 if (!Method->isStatic()) {
973 Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +0000974 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
975 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000976 }
977 }
978
979 // If the "from" expression takes the address of the overloaded
980 // function, update the type of the resulting expression accordingly.
981 if (FromType->getAs<FunctionType>())
982 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +0000983 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +0000984 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000985
986 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +0000987 assert(S.Context.hasSameType(FromType,
988 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +0000989 } else {
990 return false;
991 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +0000992 }
Mike Stump11289f42009-09-09 15:08:12 +0000993 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000994 // An lvalue (3.10) of a non-function, non-array type T can be
995 // converted to an rvalue.
John McCall5c32be02010-08-24 20:38:10 +0000996 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +0000997 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000998 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +0000999 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001000 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001001
1002 // If T is a non-class type, the type of the rvalue is the
1003 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001004 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1005 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001006 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001007 } else if (FromType->isArrayType()) {
1008 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001009 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001010
1011 // An lvalue or rvalue of type "array of N T" or "array of unknown
1012 // bound of T" can be converted to an rvalue of type "pointer to
1013 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001014 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001015
John McCall5c32be02010-08-24 20:38:10 +00001016 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001017 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001018 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001019
1020 // For the purpose of ranking in overload resolution
1021 // (13.3.3.1.1), this conversion is considered an
1022 // array-to-pointer conversion followed by a qualification
1023 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001024 SCS.Second = ICK_Identity;
1025 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001026 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001027 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028 }
Mike Stump12b8ce12009-08-04 21:02:39 +00001029 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1030 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001031 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001032
1033 // An lvalue of function type T can be converted to an rvalue of
1034 // type "pointer to T." The result is a pointer to the
1035 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001036 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001037 } else {
1038 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001039 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001040 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001041 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001042
1043 // The second conversion can be an integral promotion, floating
1044 // point promotion, integral conversion, floating point conversion,
1045 // floating-integral conversion, pointer conversion,
1046 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001047 // For overloading in C, this can also be a "compatible-type"
1048 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001049 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001050 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001051 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001052 // The unqualified versions of the types are the same: there's no
1053 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001054 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001055 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001056 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001057 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001058 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001059 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001060 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001061 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001063 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001064 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001065 SCS.Second = ICK_Complex_Promotion;
1066 FromType = ToType.getUnqualifiedType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00001067 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001068 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001069 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001070 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001072 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1073 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001074 SCS.Second = ICK_Complex_Conversion;
1075 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001076 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1077 (ToType->isComplexType() && FromType->isArithmeticType())) {
1078 // Complex-real conversions (C99 6.3.1.7)
1079 SCS.Second = ICK_Complex_Real;
1080 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001081 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001082 // Floating point conversions (C++ 4.8).
1083 SCS.Second = ICK_Floating_Conversion;
1084 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001085 } else if ((FromType->isRealFloatingType() &&
John McCall5c32be02010-08-24 20:38:10 +00001086 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001087 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001088 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001089 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001090 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001091 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001092 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1093 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001094 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001095 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001096 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001097 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1098 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001099 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001100 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001101 } else if (ToType->isBooleanType() &&
1102 (FromType->isArithmeticType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001103 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001104 FromType->isBlockPointerType() ||
1105 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001106 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001107 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001108 SCS.Second = ICK_Boolean_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001109 FromType = S.Context.BoolTy;
1110 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001111 SCS.Second = SecondICK;
1112 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001113 } else if (!S.getLangOptions().CPlusPlus &&
1114 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001115 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001116 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001117 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001118 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001119 // Treat a conversion that strips "noreturn" as an identity conversion.
1120 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001121 } else {
1122 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001123 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001125 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001127 QualType CanonFrom;
1128 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001130 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001131 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001133 CanonFrom = S.Context.getCanonicalType(FromType);
1134 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135 } else {
1136 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001137 SCS.Third = ICK_Identity;
1138
Mike Stump11289f42009-09-09 15:08:12 +00001139 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001140 // [...] Any difference in top-level cv-qualification is
1141 // subsumed by the initialization itself and does not constitute
1142 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001143 CanonFrom = S.Context.getCanonicalType(FromType);
1144 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001145 if (CanonFrom.getLocalUnqualifiedType()
1146 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001147 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1148 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001149 FromType = ToType;
1150 CanonFrom = CanonTo;
1151 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001153 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001154
1155 // If we have not converted the argument type to the parameter type,
1156 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001157 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001158 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001160 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001161}
1162
1163/// IsIntegralPromotion - Determines whether the conversion from the
1164/// expression From (whose potentially-adjusted type is FromType) to
1165/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1166/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001167bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001168 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001169 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001170 if (!To) {
1171 return false;
1172 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001173
1174 // An rvalue of type char, signed char, unsigned char, short int, or
1175 // unsigned short int can be converted to an rvalue of type int if
1176 // int can represent all the values of the source type; otherwise,
1177 // the source rvalue can be converted to an rvalue of type unsigned
1178 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001179 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1180 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001181 if (// We can promote any signed, promotable integer type to an int
1182 (FromType->isSignedIntegerType() ||
1183 // We can promote any unsigned integer type whose size is
1184 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001185 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001186 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001187 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001188 }
1189
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001190 return To->getKind() == BuiltinType::UInt;
1191 }
1192
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001193 // C++0x [conv.prom]p3:
1194 // A prvalue of an unscoped enumeration type whose underlying type is not
1195 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1196 // following types that can represent all the values of the enumeration
1197 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1198 // unsigned int, long int, unsigned long int, long long int, or unsigned
1199 // long long int. If none of the types in that list can represent all the
1200 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1201 // type can be converted to an rvalue a prvalue of the extended integer type
1202 // with lowest integer conversion rank (4.13) greater than the rank of long
1203 // long in which all the values of the enumeration can be represented. If
1204 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001205 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1206 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1207 // provided for a scoped enumeration.
1208 if (FromEnumType->getDecl()->isScoped())
1209 return false;
1210
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001211 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001212 if (ToType->isIntegerType() &&
1213 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001214 return Context.hasSameUnqualifiedType(ToType,
1215 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001216 }
John McCall56774992009-12-09 09:09:27 +00001217
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001218 // C++0x [conv.prom]p2:
1219 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1220 // to an rvalue a prvalue of the first of the following types that can
1221 // represent all the values of its underlying type: int, unsigned int,
1222 // long int, unsigned long int, long long int, or unsigned long long int.
1223 // If none of the types in that list can represent all the values of its
1224 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1225 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1226 // type.
1227 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1228 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229 // Determine whether the type we're converting from is signed or
1230 // unsigned.
1231 bool FromIsSigned;
1232 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001233
1234 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1235 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236
1237 // The types we'll try to promote to, in the appropriate
1238 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001239 QualType PromoteTypes[6] = {
1240 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001241 Context.LongTy, Context.UnsignedLongTy ,
1242 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001243 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001244 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001245 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1246 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001247 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001248 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1249 // We found the type that we can promote to. If this is the
1250 // type we wanted, we have a promotion. Otherwise, no
1251 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001252 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001253 }
1254 }
1255 }
1256
1257 // An rvalue for an integral bit-field (9.6) can be converted to an
1258 // rvalue of type int if int can represent all the values of the
1259 // bit-field; otherwise, it can be converted to unsigned int if
1260 // unsigned int can represent all the values of the bit-field. If
1261 // the bit-field is larger yet, no integral promotion applies to
1262 // it. If the bit-field has an enumerated type, it is treated as any
1263 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001264 // FIXME: We should delay checking of bit-fields until we actually perform the
1265 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001266 using llvm::APSInt;
1267 if (From)
1268 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001269 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001270 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001271 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1272 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1273 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001274
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001275 // Are we promoting to an int from a bitfield that fits in an int?
1276 if (BitWidth < ToSize ||
1277 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1278 return To->getKind() == BuiltinType::Int;
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001281 // Are we promoting to an unsigned int from an unsigned bitfield
1282 // that fits into an unsigned int?
1283 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1284 return To->getKind() == BuiltinType::UInt;
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001287 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001288 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001291 // An rvalue of type bool can be converted to an rvalue of type int,
1292 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001293 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001294 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001295 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001296
1297 return false;
1298}
1299
1300/// IsFloatingPointPromotion - Determines whether the conversion from
1301/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1302/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001303bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304 /// An rvalue of type float can be converted to an rvalue of type
1305 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001306 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1307 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001308 if (FromBuiltin->getKind() == BuiltinType::Float &&
1309 ToBuiltin->getKind() == BuiltinType::Double)
1310 return true;
1311
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001312 // C99 6.3.1.5p1:
1313 // When a float is promoted to double or long double, or a
1314 // double is promoted to long double [...].
1315 if (!getLangOptions().CPlusPlus &&
1316 (FromBuiltin->getKind() == BuiltinType::Float ||
1317 FromBuiltin->getKind() == BuiltinType::Double) &&
1318 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1319 return true;
1320 }
1321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001322 return false;
1323}
1324
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001325/// \brief Determine if a conversion is a complex promotion.
1326///
1327/// A complex promotion is defined as a complex -> complex conversion
1328/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001329/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001330bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001331 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001332 if (!FromComplex)
1333 return false;
1334
John McCall9dd450b2009-09-21 23:43:11 +00001335 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001336 if (!ToComplex)
1337 return false;
1338
1339 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001340 ToComplex->getElementType()) ||
1341 IsIntegralPromotion(0, FromComplex->getElementType(),
1342 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001343}
1344
Douglas Gregor237f96c2008-11-26 23:31:11 +00001345/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1346/// the pointer type FromPtr to a pointer to type ToPointee, with the
1347/// same type qualifiers as FromPtr has on its pointee type. ToType,
1348/// if non-empty, will be a pointer to ToType that may or may not have
1349/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001350static QualType
1351BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001352 QualType ToPointee, QualType ToType,
1353 ASTContext &Context) {
1354 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1355 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001356 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001357
1358 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001359 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001360 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001361 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001362 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001363
1364 // Build a pointer to ToPointee. It has the right qualifiers
1365 // already.
1366 return Context.getPointerType(ToPointee);
1367 }
1368
1369 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001370 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001371 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1372 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001373}
1374
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001375/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1376/// the FromType, which is an objective-c pointer, to ToType, which may or may
1377/// not have the right set of qualifiers.
1378static QualType
1379BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1380 QualType ToType,
1381 ASTContext &Context) {
1382 QualType CanonFromType = Context.getCanonicalType(FromType);
1383 QualType CanonToType = Context.getCanonicalType(ToType);
1384 Qualifiers Quals = CanonFromType.getQualifiers();
1385
1386 // Exact qualifier match -> return the pointer type we're converting to.
1387 if (CanonToType.getLocalQualifiers() == Quals)
1388 return ToType;
1389
1390 // Just build a canonical type that has the right qualifiers.
1391 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1392}
1393
Mike Stump11289f42009-09-09 15:08:12 +00001394static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001395 bool InOverloadResolution,
1396 ASTContext &Context) {
1397 // Handle value-dependent integral null pointer constants correctly.
1398 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1399 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001400 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001401 return !InOverloadResolution;
1402
Douglas Gregor56751b52009-09-25 04:25:58 +00001403 return Expr->isNullPointerConstant(Context,
1404 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1405 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001406}
Mike Stump11289f42009-09-09 15:08:12 +00001407
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001408/// IsPointerConversion - Determines whether the conversion of the
1409/// expression From, which has the (possibly adjusted) type FromType,
1410/// can be converted to the type ToType via a pointer conversion (C++
1411/// 4.10). If so, returns true and places the converted type (that
1412/// might differ from ToType in its cv-qualifiers at some level) into
1413/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001414///
Douglas Gregora29dc052008-11-27 01:19:21 +00001415/// This routine also supports conversions to and from block pointers
1416/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1417/// pointers to interfaces. FIXME: Once we've determined the
1418/// appropriate overloading rules for Objective-C, we may want to
1419/// split the Objective-C checks into a different routine; however,
1420/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001421/// conversions, so for now they live here. IncompatibleObjC will be
1422/// set if the conversion is an allowed Objective-C conversion that
1423/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001425 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001426 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001427 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001428 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001429 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1430 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001431
Mike Stump11289f42009-09-09 15:08:12 +00001432 // Conversion from a null pointer constant to any Objective-C pointer type.
1433 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001434 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001435 ConvertedType = ToType;
1436 return true;
1437 }
1438
Douglas Gregor231d1c62008-11-27 00:15:41 +00001439 // Blocks: Block pointers can be converted to void*.
1440 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001441 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001442 ConvertedType = ToType;
1443 return true;
1444 }
1445 // Blocks: A null pointer constant can be converted to a block
1446 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001447 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001448 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001449 ConvertedType = ToType;
1450 return true;
1451 }
1452
Sebastian Redl576fd422009-05-10 18:38:11 +00001453 // If the left-hand-side is nullptr_t, the right side can be a null
1454 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001455 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001456 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001457 ConvertedType = ToType;
1458 return true;
1459 }
1460
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001461 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001462 if (!ToTypePtr)
1463 return false;
1464
1465 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001466 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001467 ConvertedType = ToType;
1468 return true;
1469 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001470
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001471 // Beyond this point, both types need to be pointers
1472 // , including objective-c pointers.
1473 QualType ToPointeeType = ToTypePtr->getPointeeType();
1474 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1475 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1476 ToType, Context);
1477 return true;
1478
1479 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001480 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001481 if (!FromTypePtr)
1482 return false;
1483
1484 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001485
Douglas Gregorfb640862010-08-18 21:25:30 +00001486 // If the unqualified pointee types are the same, this can't be a
1487 // pointer conversion, so don't do all of the work below.
1488 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1489 return false;
1490
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001491 // An rvalue of type "pointer to cv T," where T is an object type,
1492 // can be converted to an rvalue of type "pointer to cv void" (C++
1493 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001494 if (FromPointeeType->isIncompleteOrObjectType() &&
1495 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001496 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001497 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001498 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001499 return true;
1500 }
1501
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001502 // When we're overloading in C, we allow a special kind of pointer
1503 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001504 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001505 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001506 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001507 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001508 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001509 return true;
1510 }
1511
Douglas Gregor5c407d92008-10-23 00:40:37 +00001512 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001513 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001514 // An rvalue of type "pointer to cv D," where D is a class type,
1515 // can be converted to an rvalue of type "pointer to cv B," where
1516 // B is a base class (clause 10) of D. If B is an inaccessible
1517 // (clause 11) or ambiguous (10.2) base class of D, a program that
1518 // necessitates this conversion is ill-formed. The result of the
1519 // conversion is a pointer to the base class sub-object of the
1520 // derived class object. The null pointer value is converted to
1521 // the null pointer value of the destination type.
1522 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001523 // Note that we do not check for ambiguity or inaccessibility
1524 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001525 if (getLangOptions().CPlusPlus &&
1526 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001527 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001528 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001529 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001530 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001531 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001532 ToType, Context);
1533 return true;
1534 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001535
Douglas Gregora119f102008-12-19 19:13:09 +00001536 return false;
1537}
1538
1539/// isObjCPointerConversion - Determines whether this is an
1540/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1541/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001542bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001543 QualType& ConvertedType,
1544 bool &IncompatibleObjC) {
1545 if (!getLangOptions().ObjC1)
1546 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001547
Steve Naroff7cae42b2009-07-10 23:34:53 +00001548 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001549 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001550 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001551 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001552
Steve Naroff7cae42b2009-07-10 23:34:53 +00001553 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001554 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001555 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001556 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001557 ConvertedType = ToType;
1558 return true;
1559 }
1560 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001561 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001562 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001563 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001564 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001565 ConvertedType = ToType;
1566 return true;
1567 }
1568 // Objective C++: We're able to convert from a pointer to an
1569 // interface to a pointer to a different interface.
1570 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001571 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1572 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1573 if (getLangOptions().CPlusPlus && LHS && RHS &&
1574 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1575 FromObjCPtr->getPointeeType()))
1576 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001577 ConvertedType = ToType;
1578 return true;
1579 }
1580
1581 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1582 // Okay: this is some kind of implicit downcast of Objective-C
1583 // interfaces, which is permitted. However, we're going to
1584 // complain about it.
1585 IncompatibleObjC = true;
1586 ConvertedType = FromType;
1587 return true;
1588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001590 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001591 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001592 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001593 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001594 else if (const BlockPointerType *ToBlockPtr =
1595 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001596 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001597 // to a block pointer type.
1598 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1599 ConvertedType = ToType;
1600 return true;
1601 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001602 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001603 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001604 else if (FromType->getAs<BlockPointerType>() &&
1605 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1606 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001607 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001608 ConvertedType = ToType;
1609 return true;
1610 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001611 else
Douglas Gregora119f102008-12-19 19:13:09 +00001612 return false;
1613
Douglas Gregor033f56d2008-12-23 00:53:59 +00001614 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001615 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001616 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001617 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001618 FromPointeeType = FromBlockPtr->getPointeeType();
1619 else
Douglas Gregora119f102008-12-19 19:13:09 +00001620 return false;
1621
Douglas Gregora119f102008-12-19 19:13:09 +00001622 // If we have pointers to pointers, recursively check whether this
1623 // is an Objective-C conversion.
1624 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1625 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1626 IncompatibleObjC)) {
1627 // We always complain about this conversion.
1628 IncompatibleObjC = true;
1629 ConvertedType = ToType;
1630 return true;
1631 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001632 // Allow conversion of pointee being objective-c pointer to another one;
1633 // as in I* to id.
1634 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1635 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1636 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1637 IncompatibleObjC)) {
1638 ConvertedType = ToType;
1639 return true;
1640 }
1641
Douglas Gregor033f56d2008-12-23 00:53:59 +00001642 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001643 // differences in the argument and result types are in Objective-C
1644 // pointer conversions. If so, we permit the conversion (but
1645 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001646 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001647 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001648 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001649 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001650 if (FromFunctionType && ToFunctionType) {
1651 // If the function types are exactly the same, this isn't an
1652 // Objective-C pointer conversion.
1653 if (Context.getCanonicalType(FromPointeeType)
1654 == Context.getCanonicalType(ToPointeeType))
1655 return false;
1656
1657 // Perform the quick checks that will tell us whether these
1658 // function types are obviously different.
1659 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1660 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1661 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1662 return false;
1663
1664 bool HasObjCConversion = false;
1665 if (Context.getCanonicalType(FromFunctionType->getResultType())
1666 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1667 // Okay, the types match exactly. Nothing to do.
1668 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1669 ToFunctionType->getResultType(),
1670 ConvertedType, IncompatibleObjC)) {
1671 // Okay, we have an Objective-C pointer conversion.
1672 HasObjCConversion = true;
1673 } else {
1674 // Function types are too different. Abort.
1675 return false;
1676 }
Mike Stump11289f42009-09-09 15:08:12 +00001677
Douglas Gregora119f102008-12-19 19:13:09 +00001678 // Check argument types.
1679 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1680 ArgIdx != NumArgs; ++ArgIdx) {
1681 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1682 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1683 if (Context.getCanonicalType(FromArgType)
1684 == Context.getCanonicalType(ToArgType)) {
1685 // Okay, the types match exactly. Nothing to do.
1686 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1687 ConvertedType, IncompatibleObjC)) {
1688 // Okay, we have an Objective-C pointer conversion.
1689 HasObjCConversion = true;
1690 } else {
1691 // Argument types are too different. Abort.
1692 return false;
1693 }
1694 }
1695
1696 if (HasObjCConversion) {
1697 // We had an Objective-C conversion. Allow this pointer
1698 // conversion, but complain about it.
1699 ConvertedType = ToType;
1700 IncompatibleObjC = true;
1701 return true;
1702 }
1703 }
1704
Sebastian Redl72b597d2009-01-25 19:43:20 +00001705 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001707
1708/// FunctionArgTypesAreEqual - This routine checks two function proto types
1709/// for equlity of their argument types. Caller has already checked that
1710/// they have same number of arguments. This routine assumes that Objective-C
1711/// pointer types which only differ in their protocol qualifiers are equal.
1712bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1713 FunctionProtoType* NewType){
1714 if (!getLangOptions().ObjC1)
1715 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1716 NewType->arg_type_begin());
1717
1718 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1719 N = NewType->arg_type_begin(),
1720 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1721 QualType ToType = (*O);
1722 QualType FromType = (*N);
1723 if (ToType != FromType) {
1724 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1725 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001726 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1727 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1728 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1729 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001730 continue;
1731 }
John McCall8b07ec22010-05-15 11:32:37 +00001732 else if (const ObjCObjectPointerType *PTTo =
1733 ToType->getAs<ObjCObjectPointerType>()) {
1734 if (const ObjCObjectPointerType *PTFr =
1735 FromType->getAs<ObjCObjectPointerType>())
1736 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1737 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001738 }
1739 return false;
1740 }
1741 }
1742 return true;
1743}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001744
Douglas Gregor39c16d42008-10-24 04:54:22 +00001745/// CheckPointerConversion - Check the pointer conversion from the
1746/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001747/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001748/// conversions for which IsPointerConversion has already returned
1749/// true. It returns true and produces a diagnostic if there was an
1750/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001751bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001752 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001753 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001754 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001755 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001756 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001757
Douglas Gregor4038cf42010-06-08 17:35:15 +00001758 if (CXXBoolLiteralExpr* LitBool
1759 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001760 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001761 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1762 << ToType;
1763
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001764 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1765 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001766 QualType FromPointeeType = FromPtrType->getPointeeType(),
1767 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001768
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001769 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1770 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001771 // We must have a derived-to-base conversion. Check an
1772 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001773 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1774 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001775 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001776 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001777 return true;
1778
1779 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001780 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001781 }
1782 }
Mike Stump11289f42009-09-09 15:08:12 +00001783 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001784 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001785 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001786 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001787 // Objective-C++ conversions are always okay.
1788 // FIXME: We should have a different class of conversions for the
1789 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001790 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001791 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001792
Steve Naroff7cae42b2009-07-10 23:34:53 +00001793 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001794 return false;
1795}
1796
Sebastian Redl72b597d2009-01-25 19:43:20 +00001797/// IsMemberPointerConversion - Determines whether the conversion of the
1798/// expression From, which has the (possibly adjusted) type FromType, can be
1799/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1800/// If so, returns true and places the converted type (that might differ from
1801/// ToType in its cv-qualifiers at some level) into ConvertedType.
1802bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001803 QualType ToType,
1804 bool InOverloadResolution,
1805 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001806 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001807 if (!ToTypePtr)
1808 return false;
1809
1810 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001811 if (From->isNullPointerConstant(Context,
1812 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1813 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001814 ConvertedType = ToType;
1815 return true;
1816 }
1817
1818 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001819 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001820 if (!FromTypePtr)
1821 return false;
1822
1823 // A pointer to member of B can be converted to a pointer to member of D,
1824 // where D is derived from B (C++ 4.11p2).
1825 QualType FromClass(FromTypePtr->getClass(), 0);
1826 QualType ToClass(ToTypePtr->getClass(), 0);
1827 // FIXME: What happens when these are dependent? Is this function even called?
1828
1829 if (IsDerivedFrom(ToClass, FromClass)) {
1830 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1831 ToClass.getTypePtr());
1832 return true;
1833 }
1834
1835 return false;
1836}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001837
Sebastian Redl72b597d2009-01-25 19:43:20 +00001838/// CheckMemberPointerConversion - Check the member pointer conversion from the
1839/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001840/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001841/// for which IsMemberPointerConversion has already returned true. It returns
1842/// true and produces a diagnostic if there was an error, or returns false
1843/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001844bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001845 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001846 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001847 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001848 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001849 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001850 if (!FromPtrType) {
1851 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001852 assert(From->isNullPointerConstant(Context,
1853 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001854 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001855 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001856 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001857 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001858
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001859 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001860 assert(ToPtrType && "No member pointer cast has a target type "
1861 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001862
Sebastian Redled8f2002009-01-28 18:33:18 +00001863 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1864 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001865
Sebastian Redled8f2002009-01-28 18:33:18 +00001866 // FIXME: What about dependent types?
1867 assert(FromClass->isRecordType() && "Pointer into non-class.");
1868 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001869
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001870 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001871 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001872 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1873 assert(DerivationOkay &&
1874 "Should not have been called if derivation isn't OK.");
1875 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001876
Sebastian Redled8f2002009-01-28 18:33:18 +00001877 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1878 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001879 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1880 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1881 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1882 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001883 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001884
Douglas Gregor89ee6822009-02-28 01:32:25 +00001885 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001886 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1887 << FromClass << ToClass << QualType(VBase, 0)
1888 << From->getSourceRange();
1889 return true;
1890 }
1891
John McCall5b0829a2010-02-10 09:31:12 +00001892 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001893 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1894 Paths.front(),
1895 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001896
Anders Carlssond7923c62009-08-22 23:33:40 +00001897 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001898 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001899 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001900 return false;
1901}
1902
Douglas Gregor9a657932008-10-21 23:43:52 +00001903/// IsQualificationConversion - Determines whether the conversion from
1904/// an rvalue of type FromType to ToType is a qualification conversion
1905/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001906bool
1907Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001908 FromType = Context.getCanonicalType(FromType);
1909 ToType = Context.getCanonicalType(ToType);
1910
1911 // If FromType and ToType are the same type, this is not a
1912 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001913 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001914 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001915
Douglas Gregor9a657932008-10-21 23:43:52 +00001916 // (C++ 4.4p4):
1917 // A conversion can add cv-qualifiers at levels other than the first
1918 // in multi-level pointers, subject to the following rules: [...]
1919 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001920 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001921 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001922 // Within each iteration of the loop, we check the qualifiers to
1923 // determine if this still looks like a qualification
1924 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001925 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001926 // until there are no more pointers or pointers-to-members left to
1927 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001928 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001929
1930 // -- for every j > 0, if const is in cv 1,j then const is in cv
1931 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001932 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001933 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001934
Douglas Gregor9a657932008-10-21 23:43:52 +00001935 // -- if the cv 1,j and cv 2,j are different, then const is in
1936 // every cv for 0 < k < j.
1937 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001938 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001939 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001940
Douglas Gregor9a657932008-10-21 23:43:52 +00001941 // Keep track of whether all prior cv-qualifiers in the "to" type
1942 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001943 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001944 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001945 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001946
1947 // We are left with FromType and ToType being the pointee types
1948 // after unwrapping the original FromType and ToType the same number
1949 // of types. If we unwrapped any pointers, and if FromType and
1950 // ToType have the same unqualified type (since we checked
1951 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001952 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001953}
1954
Douglas Gregor576e98c2009-01-30 23:27:23 +00001955/// Determines whether there is a user-defined conversion sequence
1956/// (C++ [over.ics.user]) that converts expression From to the type
1957/// ToType. If such a conversion exists, User will contain the
1958/// user-defined conversion sequence that performs such a conversion
1959/// and this routine will return true. Otherwise, this routine returns
1960/// false and User is unspecified.
1961///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001962/// \param AllowExplicit true if the conversion should consider C++0x
1963/// "explicit" conversion functions as well as non-explicit conversion
1964/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001965static OverloadingResult
1966IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1967 UserDefinedConversionSequence& User,
1968 OverloadCandidateSet& CandidateSet,
1969 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001970 // Whether we will only visit constructors.
1971 bool ConstructorsOnly = false;
1972
1973 // If the type we are conversion to is a class type, enumerate its
1974 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001975 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001976 // C++ [over.match.ctor]p1:
1977 // When objects of class type are direct-initialized (8.5), or
1978 // copy-initialized from an expression of the same or a
1979 // derived class type (8.5), overload resolution selects the
1980 // constructor. [...] For copy-initialization, the candidate
1981 // functions are all the converting constructors (12.3.1) of
1982 // that class. The argument list is the expression-list within
1983 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00001984 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00001985 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001986 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001987 ConstructorsOnly = true;
1988
John McCall5c32be02010-08-24 20:38:10 +00001989 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001990 // We're not going to find any constructors.
1991 } else if (CXXRecordDecl *ToRecordDecl
1992 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001993 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00001994 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001995 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001996 NamedDecl *D = *Con;
1997 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1998
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001999 // Find the constructor (which may be a template).
2000 CXXConstructorDecl *Constructor = 0;
2001 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002002 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002003 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002004 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002005 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2006 else
John McCalla0296f72010-03-19 07:35:19 +00002007 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002008
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002009 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002010 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002011 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002012 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2013 /*ExplicitArgs*/ 0,
2014 &From, 1, CandidateSet,
2015 /*SuppressUserConversions=*/
2016 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002017 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002018 // Allow one user-defined conversion when user specifies a
2019 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002020 S.AddOverloadCandidate(Constructor, FoundDecl,
2021 &From, 1, CandidateSet,
2022 /*SuppressUserConversions=*/
2023 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002024 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002025 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002026 }
2027 }
2028
Douglas Gregor5ab11652010-04-17 22:01:05 +00002029 // Enumerate conversion functions, if we're allowed to.
2030 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002031 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2032 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002033 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002034 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002035 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002036 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002037 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2038 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002039 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002040 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002041 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002042 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002043 DeclAccessPair FoundDecl = I.getPair();
2044 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002045 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2046 if (isa<UsingShadowDecl>(D))
2047 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2048
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002049 CXXConversionDecl *Conv;
2050 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002051 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2052 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002053 else
John McCallda4458e2010-03-31 01:36:47 +00002054 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002055
2056 if (AllowExplicit || !Conv->isExplicit()) {
2057 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002058 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2059 ActingContext, From, ToType,
2060 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002061 else
John McCall5c32be02010-08-24 20:38:10 +00002062 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2063 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002064 }
2065 }
2066 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002067 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002068
2069 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002070 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002071 case OR_Success:
2072 // Record the standard conversion we used and the conversion function.
2073 if (CXXConstructorDecl *Constructor
2074 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2075 // C++ [over.ics.user]p1:
2076 // If the user-defined conversion is specified by a
2077 // constructor (12.3.1), the initial standard conversion
2078 // sequence converts the source type to the type required by
2079 // the argument of the constructor.
2080 //
2081 QualType ThisType = Constructor->getThisType(S.Context);
2082 if (Best->Conversions[0].isEllipsis())
2083 User.EllipsisConversion = true;
2084 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002085 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002086 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002087 }
John McCall5c32be02010-08-24 20:38:10 +00002088 User.ConversionFunction = Constructor;
2089 User.After.setAsIdentityConversion();
2090 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2091 User.After.setAllToTypes(ToType);
2092 return OR_Success;
2093 } else if (CXXConversionDecl *Conversion
2094 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2095 // C++ [over.ics.user]p1:
2096 //
2097 // [...] If the user-defined conversion is specified by a
2098 // conversion function (12.3.2), the initial standard
2099 // conversion sequence converts the source type to the
2100 // implicit object parameter of the conversion function.
2101 User.Before = Best->Conversions[0].Standard;
2102 User.ConversionFunction = Conversion;
2103 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002104
John McCall5c32be02010-08-24 20:38:10 +00002105 // C++ [over.ics.user]p2:
2106 // The second standard conversion sequence converts the
2107 // result of the user-defined conversion to the target type
2108 // for the sequence. Since an implicit conversion sequence
2109 // is an initialization, the special rules for
2110 // initialization by user-defined conversion apply when
2111 // selecting the best user-defined conversion for a
2112 // user-defined conversion sequence (see 13.3.3 and
2113 // 13.3.3.1).
2114 User.After = Best->FinalConversion;
2115 return OR_Success;
2116 } else {
2117 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002118 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002119 }
2120
John McCall5c32be02010-08-24 20:38:10 +00002121 case OR_No_Viable_Function:
2122 return OR_No_Viable_Function;
2123 case OR_Deleted:
2124 // No conversion here! We're done.
2125 return OR_Deleted;
2126
2127 case OR_Ambiguous:
2128 return OR_Ambiguous;
2129 }
2130
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002131 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002132}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002133
2134bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002135Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002136 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002137 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002138 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002139 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002140 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002141 if (OvResult == OR_Ambiguous)
2142 Diag(From->getSourceRange().getBegin(),
2143 diag::err_typecheck_ambiguous_condition)
2144 << From->getType() << ToType << From->getSourceRange();
2145 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2146 Diag(From->getSourceRange().getBegin(),
2147 diag::err_typecheck_nonviable_condition)
2148 << From->getType() << ToType << From->getSourceRange();
2149 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002150 return false;
John McCall5c32be02010-08-24 20:38:10 +00002151 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002152 return true;
2153}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002154
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002155/// CompareImplicitConversionSequences - Compare two implicit
2156/// conversion sequences to determine whether one is better than the
2157/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002158static ImplicitConversionSequence::CompareKind
2159CompareImplicitConversionSequences(Sema &S,
2160 const ImplicitConversionSequence& ICS1,
2161 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002162{
2163 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2164 // conversion sequences (as defined in 13.3.3.1)
2165 // -- a standard conversion sequence (13.3.3.1.1) is a better
2166 // conversion sequence than a user-defined conversion sequence or
2167 // an ellipsis conversion sequence, and
2168 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2169 // conversion sequence than an ellipsis conversion sequence
2170 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002171 //
John McCall0d1da222010-01-12 00:44:57 +00002172 // C++0x [over.best.ics]p10:
2173 // For the purpose of ranking implicit conversion sequences as
2174 // described in 13.3.3.2, the ambiguous conversion sequence is
2175 // treated as a user-defined sequence that is indistinguishable
2176 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002177 if (ICS1.getKindRank() < ICS2.getKindRank())
2178 return ImplicitConversionSequence::Better;
2179 else if (ICS2.getKindRank() < ICS1.getKindRank())
2180 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002181
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002182 // The following checks require both conversion sequences to be of
2183 // the same kind.
2184 if (ICS1.getKind() != ICS2.getKind())
2185 return ImplicitConversionSequence::Indistinguishable;
2186
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187 // Two implicit conversion sequences of the same form are
2188 // indistinguishable conversion sequences unless one of the
2189 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002190 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002191 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002192 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002193 // User-defined conversion sequence U1 is a better conversion
2194 // sequence than another user-defined conversion sequence U2 if
2195 // they contain the same user-defined conversion function or
2196 // constructor and if the second standard conversion sequence of
2197 // U1 is better than the second standard conversion sequence of
2198 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002199 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002200 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002201 return CompareStandardConversionSequences(S,
2202 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002203 ICS2.UserDefined.After);
2204 }
2205
2206 return ImplicitConversionSequence::Indistinguishable;
2207}
2208
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002209static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2210 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2211 Qualifiers Quals;
2212 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2213 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2214 }
2215
2216 return Context.hasSameUnqualifiedType(T1, T2);
2217}
2218
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002219// Per 13.3.3.2p3, compare the given standard conversion sequences to
2220// determine if one is a proper subset of the other.
2221static ImplicitConversionSequence::CompareKind
2222compareStandardConversionSubsets(ASTContext &Context,
2223 const StandardConversionSequence& SCS1,
2224 const StandardConversionSequence& SCS2) {
2225 ImplicitConversionSequence::CompareKind Result
2226 = ImplicitConversionSequence::Indistinguishable;
2227
Douglas Gregore87561a2010-05-23 22:10:15 +00002228 // the identity conversion sequence is considered to be a subsequence of
2229 // any non-identity conversion sequence
2230 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2231 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2232 return ImplicitConversionSequence::Better;
2233 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2234 return ImplicitConversionSequence::Worse;
2235 }
2236
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002237 if (SCS1.Second != SCS2.Second) {
2238 if (SCS1.Second == ICK_Identity)
2239 Result = ImplicitConversionSequence::Better;
2240 else if (SCS2.Second == ICK_Identity)
2241 Result = ImplicitConversionSequence::Worse;
2242 else
2243 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002244 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002245 return ImplicitConversionSequence::Indistinguishable;
2246
2247 if (SCS1.Third == SCS2.Third) {
2248 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2249 : ImplicitConversionSequence::Indistinguishable;
2250 }
2251
2252 if (SCS1.Third == ICK_Identity)
2253 return Result == ImplicitConversionSequence::Worse
2254 ? ImplicitConversionSequence::Indistinguishable
2255 : ImplicitConversionSequence::Better;
2256
2257 if (SCS2.Third == ICK_Identity)
2258 return Result == ImplicitConversionSequence::Better
2259 ? ImplicitConversionSequence::Indistinguishable
2260 : ImplicitConversionSequence::Worse;
2261
2262 return ImplicitConversionSequence::Indistinguishable;
2263}
2264
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265/// CompareStandardConversionSequences - Compare two standard
2266/// conversion sequences to determine whether one is better than the
2267/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002268static ImplicitConversionSequence::CompareKind
2269CompareStandardConversionSequences(Sema &S,
2270 const StandardConversionSequence& SCS1,
2271 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002272{
2273 // Standard conversion sequence S1 is a better conversion sequence
2274 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2275
2276 // -- S1 is a proper subsequence of S2 (comparing the conversion
2277 // sequences in the canonical form defined by 13.3.3.1.1,
2278 // excluding any Lvalue Transformation; the identity conversion
2279 // sequence is considered to be a subsequence of any
2280 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002281 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002282 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002283 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002284
2285 // -- the rank of S1 is better than the rank of S2 (by the rules
2286 // defined below), or, if not that,
2287 ImplicitConversionRank Rank1 = SCS1.getRank();
2288 ImplicitConversionRank Rank2 = SCS2.getRank();
2289 if (Rank1 < Rank2)
2290 return ImplicitConversionSequence::Better;
2291 else if (Rank2 < Rank1)
2292 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002293
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002294 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2295 // are indistinguishable unless one of the following rules
2296 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002297
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002298 // A conversion that is not a conversion of a pointer, or
2299 // pointer to member, to bool is better than another conversion
2300 // that is such a conversion.
2301 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2302 return SCS2.isPointerConversionToBool()
2303 ? ImplicitConversionSequence::Better
2304 : ImplicitConversionSequence::Worse;
2305
Douglas Gregor5c407d92008-10-23 00:40:37 +00002306 // C++ [over.ics.rank]p4b2:
2307 //
2308 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002309 // conversion of B* to A* is better than conversion of B* to
2310 // void*, and conversion of A* to void* is better than conversion
2311 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002312 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002313 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002314 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002315 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002316 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2317 // Exactly one of the conversion sequences is a conversion to
2318 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002319 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2320 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002321 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2322 // Neither conversion sequence converts to a void pointer; compare
2323 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002324 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002325 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002326 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002327 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2328 // Both conversion sequences are conversions to void
2329 // pointers. Compare the source types to determine if there's an
2330 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002331 QualType FromType1 = SCS1.getFromType();
2332 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002333
2334 // Adjust the types we're converting from via the array-to-pointer
2335 // conversion, if we need to.
2336 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002337 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002338 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002339 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002340
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002341 QualType FromPointee1
2342 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2343 QualType FromPointee2
2344 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002345
John McCall5c32be02010-08-24 20:38:10 +00002346 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002347 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002348 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002349 return ImplicitConversionSequence::Worse;
2350
2351 // Objective-C++: If one interface is more specific than the
2352 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002353 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2354 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002355 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002356 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002357 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002358 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002359 return ImplicitConversionSequence::Worse;
2360 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002361 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002362
2363 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2364 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002365 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002366 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002367 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002368
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002369 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002370 // C++0x [over.ics.rank]p3b4:
2371 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2372 // implicit object parameter of a non-static member function declared
2373 // without a ref-qualifier, and S1 binds an rvalue reference to an
2374 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002375 // FIXME: We don't know if we're dealing with the implicit object parameter,
2376 // or if the member function in this case has a ref qualifier.
2377 // (Of course, we don't have ref qualifiers yet.)
2378 if (SCS1.RRefBinding != SCS2.RRefBinding)
2379 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2380 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002381
2382 // C++ [over.ics.rank]p3b4:
2383 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2384 // which the references refer are the same type except for
2385 // top-level cv-qualifiers, and the type to which the reference
2386 // initialized by S2 refers is more cv-qualified than the type
2387 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002388 QualType T1 = SCS1.getToType(2);
2389 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002390 T1 = S.Context.getCanonicalType(T1);
2391 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002392 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002393 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2394 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002395 if (UnqualT1 == UnqualT2) {
2396 // If the type is an array type, promote the element qualifiers to the type
2397 // for comparison.
2398 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002399 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002400 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002401 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002402 if (T2.isMoreQualifiedThan(T1))
2403 return ImplicitConversionSequence::Better;
2404 else if (T1.isMoreQualifiedThan(T2))
2405 return ImplicitConversionSequence::Worse;
2406 }
2407 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002408
2409 return ImplicitConversionSequence::Indistinguishable;
2410}
2411
2412/// CompareQualificationConversions - Compares two standard conversion
2413/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002414/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2415ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002416CompareQualificationConversions(Sema &S,
2417 const StandardConversionSequence& SCS1,
2418 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002419 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002420 // -- S1 and S2 differ only in their qualification conversion and
2421 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2422 // cv-qualification signature of type T1 is a proper subset of
2423 // the cv-qualification signature of type T2, and S1 is not the
2424 // deprecated string literal array-to-pointer conversion (4.2).
2425 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2426 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2427 return ImplicitConversionSequence::Indistinguishable;
2428
2429 // FIXME: the example in the standard doesn't use a qualification
2430 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002431 QualType T1 = SCS1.getToType(2);
2432 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002433 T1 = S.Context.getCanonicalType(T1);
2434 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002435 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002436 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2437 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002438
2439 // If the types are the same, we won't learn anything by unwrapped
2440 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002441 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002442 return ImplicitConversionSequence::Indistinguishable;
2443
Chandler Carruth607f38e2009-12-29 07:16:59 +00002444 // If the type is an array type, promote the element qualifiers to the type
2445 // for comparison.
2446 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002447 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002448 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002449 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002450
Mike Stump11289f42009-09-09 15:08:12 +00002451 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002452 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002453 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002454 // Within each iteration of the loop, we check the qualifiers to
2455 // determine if this still looks like a qualification
2456 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002457 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002458 // until there are no more pointers or pointers-to-members left
2459 // to unwrap. This essentially mimics what
2460 // IsQualificationConversion does, but here we're checking for a
2461 // strict subset of qualifiers.
2462 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2463 // The qualifiers are the same, so this doesn't tell us anything
2464 // about how the sequences rank.
2465 ;
2466 else if (T2.isMoreQualifiedThan(T1)) {
2467 // T1 has fewer qualifiers, so it could be the better sequence.
2468 if (Result == ImplicitConversionSequence::Worse)
2469 // Neither has qualifiers that are a subset of the other's
2470 // qualifiers.
2471 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002472
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002473 Result = ImplicitConversionSequence::Better;
2474 } else if (T1.isMoreQualifiedThan(T2)) {
2475 // T2 has fewer qualifiers, so it could be the better sequence.
2476 if (Result == ImplicitConversionSequence::Better)
2477 // Neither has qualifiers that are a subset of the other's
2478 // qualifiers.
2479 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002480
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002481 Result = ImplicitConversionSequence::Worse;
2482 } else {
2483 // Qualifiers are disjoint.
2484 return ImplicitConversionSequence::Indistinguishable;
2485 }
2486
2487 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002488 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002489 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002490 }
2491
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002492 // Check that the winning standard conversion sequence isn't using
2493 // the deprecated string literal array to pointer conversion.
2494 switch (Result) {
2495 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002496 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002497 Result = ImplicitConversionSequence::Indistinguishable;
2498 break;
2499
2500 case ImplicitConversionSequence::Indistinguishable:
2501 break;
2502
2503 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002504 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002505 Result = ImplicitConversionSequence::Indistinguishable;
2506 break;
2507 }
2508
2509 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002510}
2511
Douglas Gregor5c407d92008-10-23 00:40:37 +00002512/// CompareDerivedToBaseConversions - Compares two standard conversion
2513/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002514/// various kinds of derived-to-base conversions (C++
2515/// [over.ics.rank]p4b3). As part of these checks, we also look at
2516/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002517ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002518CompareDerivedToBaseConversions(Sema &S,
2519 const StandardConversionSequence& SCS1,
2520 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002521 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002522 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002523 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002524 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002525
2526 // Adjust the types we're converting from via the array-to-pointer
2527 // conversion, if we need to.
2528 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002529 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002530 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002531 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002532
2533 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002534 FromType1 = S.Context.getCanonicalType(FromType1);
2535 ToType1 = S.Context.getCanonicalType(ToType1);
2536 FromType2 = S.Context.getCanonicalType(FromType2);
2537 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002538
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002539 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002540 //
2541 // If class B is derived directly or indirectly from class A and
2542 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002543 //
2544 // For Objective-C, we let A, B, and C also be Objective-C
2545 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002546
2547 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002548 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002549 SCS2.Second == ICK_Pointer_Conversion &&
2550 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2551 FromType1->isPointerType() && FromType2->isPointerType() &&
2552 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002553 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002554 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002555 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002556 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002557 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002558 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002559 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002560 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002561
John McCall8b07ec22010-05-15 11:32:37 +00002562 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2563 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2564 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2565 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002566
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002567 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002568 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002569 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002570 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002571 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002572 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002573
2574 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002575 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002576 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002577 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002578 return ImplicitConversionSequence::Worse;
2579 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002580 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002581
2582 // -- conversion of B* to A* is better than conversion of C* to A*,
2583 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002584 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002585 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002586 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002587 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregor237f96c2008-11-26 23:31:11 +00002589 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002590 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002591 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002592 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002593 return ImplicitConversionSequence::Worse;
2594 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002595 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002596 }
2597
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002598 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002599 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2600 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2601 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2602 const MemberPointerType * FromMemPointer1 =
2603 FromType1->getAs<MemberPointerType>();
2604 const MemberPointerType * ToMemPointer1 =
2605 ToType1->getAs<MemberPointerType>();
2606 const MemberPointerType * FromMemPointer2 =
2607 FromType2->getAs<MemberPointerType>();
2608 const MemberPointerType * ToMemPointer2 =
2609 ToType2->getAs<MemberPointerType>();
2610 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2611 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2612 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2613 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2614 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2615 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2616 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2617 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002618 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002619 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002620 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002621 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002622 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002623 return ImplicitConversionSequence::Better;
2624 }
2625 // conversion of B::* to C::* is better than conversion of A::* to C::*
2626 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002627 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002628 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002629 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002630 return ImplicitConversionSequence::Worse;
2631 }
2632 }
2633
Douglas Gregor5ab11652010-04-17 22:01:05 +00002634 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002635 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002636 // -- binding of an expression of type C to a reference of type
2637 // B& is better than binding an expression of type C to a
2638 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002639 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2640 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2641 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002642 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002643 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002644 return ImplicitConversionSequence::Worse;
2645 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002646
Douglas Gregor2fe98832008-11-03 19:09:14 +00002647 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002648 // -- binding of an expression of type B to a reference of type
2649 // A& is better than binding an expression of type C to a
2650 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002651 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2652 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2653 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002654 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002655 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002656 return ImplicitConversionSequence::Worse;
2657 }
2658 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002659
Douglas Gregor5c407d92008-10-23 00:40:37 +00002660 return ImplicitConversionSequence::Indistinguishable;
2661}
2662
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002663/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2664/// determine whether they are reference-related,
2665/// reference-compatible, reference-compatible with added
2666/// qualification, or incompatible, for use in C++ initialization by
2667/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2668/// type, and the first type (T1) is the pointee type of the reference
2669/// type being initialized.
2670Sema::ReferenceCompareResult
2671Sema::CompareReferenceRelationship(SourceLocation Loc,
2672 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002673 bool &DerivedToBase,
2674 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002675 assert(!OrigT1->isReferenceType() &&
2676 "T1 must be the pointee type of the reference type");
2677 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2678
2679 QualType T1 = Context.getCanonicalType(OrigT1);
2680 QualType T2 = Context.getCanonicalType(OrigT2);
2681 Qualifiers T1Quals, T2Quals;
2682 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2683 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2684
2685 // C++ [dcl.init.ref]p4:
2686 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2687 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2688 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002689 DerivedToBase = false;
2690 ObjCConversion = false;
2691 if (UnqualT1 == UnqualT2) {
2692 // Nothing to do.
2693 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002694 IsDerivedFrom(UnqualT2, UnqualT1))
2695 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002696 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2697 UnqualT2->isObjCObjectOrInterfaceType() &&
2698 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2699 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002700 else
2701 return Ref_Incompatible;
2702
2703 // At this point, we know that T1 and T2 are reference-related (at
2704 // least).
2705
2706 // If the type is an array type, promote the element qualifiers to the type
2707 // for comparison.
2708 if (isa<ArrayType>(T1) && T1Quals)
2709 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2710 if (isa<ArrayType>(T2) && T2Quals)
2711 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2712
2713 // C++ [dcl.init.ref]p4:
2714 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2715 // reference-related to T2 and cv1 is the same cv-qualification
2716 // as, or greater cv-qualification than, cv2. For purposes of
2717 // overload resolution, cases for which cv1 is greater
2718 // cv-qualification than cv2 are identified as
2719 // reference-compatible with added qualification (see 13.3.3.2).
2720 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2721 return Ref_Compatible;
2722 else if (T1.isMoreQualifiedThan(T2))
2723 return Ref_Compatible_With_Added_Qualification;
2724 else
2725 return Ref_Related;
2726}
2727
Douglas Gregor836a7e82010-08-11 02:15:33 +00002728/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002729/// with DeclType. Return true if something definite is found.
2730static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002731FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2732 QualType DeclType, SourceLocation DeclLoc,
2733 Expr *Init, QualType T2, bool AllowRvalues,
2734 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002735 assert(T2->isRecordType() && "Can only find conversions of record types.");
2736 CXXRecordDecl *T2RecordDecl
2737 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2738
Douglas Gregor836a7e82010-08-11 02:15:33 +00002739 QualType ToType
2740 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2741 : DeclType;
2742
Sebastian Redld92badf2010-06-30 18:13:39 +00002743 OverloadCandidateSet CandidateSet(DeclLoc);
2744 const UnresolvedSetImpl *Conversions
2745 = T2RecordDecl->getVisibleConversionFunctions();
2746 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2747 E = Conversions->end(); I != E; ++I) {
2748 NamedDecl *D = *I;
2749 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2750 if (isa<UsingShadowDecl>(D))
2751 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2752
2753 FunctionTemplateDecl *ConvTemplate
2754 = dyn_cast<FunctionTemplateDecl>(D);
2755 CXXConversionDecl *Conv;
2756 if (ConvTemplate)
2757 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2758 else
2759 Conv = cast<CXXConversionDecl>(D);
2760
Douglas Gregor836a7e82010-08-11 02:15:33 +00002761 // If this is an explicit conversion, and we're not allowed to consider
2762 // explicit conversions, skip it.
2763 if (!AllowExplicit && Conv->isExplicit())
2764 continue;
2765
2766 if (AllowRvalues) {
2767 bool DerivedToBase = false;
2768 bool ObjCConversion = false;
2769 if (!ConvTemplate &&
2770 S.CompareReferenceRelationship(DeclLoc,
2771 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2772 DeclType.getNonReferenceType().getUnqualifiedType(),
2773 DerivedToBase, ObjCConversion)
2774 == Sema::Ref_Incompatible)
2775 continue;
2776 } else {
2777 // If the conversion function doesn't return a reference type,
2778 // it can't be considered for this conversion. An rvalue reference
2779 // is only acceptable if its referencee is a function type.
2780
2781 const ReferenceType *RefType =
2782 Conv->getConversionType()->getAs<ReferenceType>();
2783 if (!RefType ||
2784 (!RefType->isLValueReferenceType() &&
2785 !RefType->getPointeeType()->isFunctionType()))
2786 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002787 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002788
2789 if (ConvTemplate)
2790 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2791 Init, ToType, CandidateSet);
2792 else
2793 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2794 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002795 }
2796
2797 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002798 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002799 case OR_Success:
2800 // C++ [over.ics.ref]p1:
2801 //
2802 // [...] If the parameter binds directly to the result of
2803 // applying a conversion function to the argument
2804 // expression, the implicit conversion sequence is a
2805 // user-defined conversion sequence (13.3.3.1.2), with the
2806 // second standard conversion sequence either an identity
2807 // conversion or, if the conversion function returns an
2808 // entity of a type that is a derived class of the parameter
2809 // type, a derived-to-base Conversion.
2810 if (!Best->FinalConversion.DirectBinding)
2811 return false;
2812
2813 ICS.setUserDefined();
2814 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2815 ICS.UserDefined.After = Best->FinalConversion;
2816 ICS.UserDefined.ConversionFunction = Best->Function;
2817 ICS.UserDefined.EllipsisConversion = false;
2818 assert(ICS.UserDefined.After.ReferenceBinding &&
2819 ICS.UserDefined.After.DirectBinding &&
2820 "Expected a direct reference binding!");
2821 return true;
2822
2823 case OR_Ambiguous:
2824 ICS.setAmbiguous();
2825 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2826 Cand != CandidateSet.end(); ++Cand)
2827 if (Cand->Viable)
2828 ICS.Ambiguous.addConversion(Cand->Function);
2829 return true;
2830
2831 case OR_No_Viable_Function:
2832 case OR_Deleted:
2833 // There was no suitable conversion, or we found a deleted
2834 // conversion; continue with other checks.
2835 return false;
2836 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002837
2838 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002839}
2840
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002841/// \brief Compute an implicit conversion sequence for reference
2842/// initialization.
2843static ImplicitConversionSequence
2844TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2845 SourceLocation DeclLoc,
2846 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002847 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002848 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2849
2850 // Most paths end in a failed conversion.
2851 ImplicitConversionSequence ICS;
2852 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2853
2854 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2855 QualType T2 = Init->getType();
2856
2857 // If the initializer is the address of an overloaded function, try
2858 // to resolve the overloaded function. If all goes well, T2 is the
2859 // type of the resulting function.
2860 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2861 DeclAccessPair Found;
2862 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2863 false, Found))
2864 T2 = Fn->getType();
2865 }
2866
2867 // Compute some basic properties of the types and the initializer.
2868 bool isRValRef = DeclType->isRValueReferenceType();
2869 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002870 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002871 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002872 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002873 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2874 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002875
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002876
Sebastian Redld92badf2010-06-30 18:13:39 +00002877 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002878 // A reference to type "cv1 T1" is initialized by an expression
2879 // of type "cv2 T2" as follows:
2880
Sebastian Redld92badf2010-06-30 18:13:39 +00002881 // -- If reference is an lvalue reference and the initializer expression
2882 // The next bullet point (T1 is a function) is pretty much equivalent to this
2883 // one, so it's handled here.
2884 if (!isRValRef || T1->isFunctionType()) {
2885 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2886 // reference-compatible with "cv2 T2," or
2887 //
2888 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2889 if (InitCategory.isLValue() &&
2890 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002891 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002892 // When a parameter of reference type binds directly (8.5.3)
2893 // to an argument expression, the implicit conversion sequence
2894 // is the identity conversion, unless the argument expression
2895 // has a type that is a derived class of the parameter type,
2896 // in which case the implicit conversion sequence is a
2897 // derived-to-base Conversion (13.3.3.1).
2898 ICS.setStandard();
2899 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002900 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2901 : ObjCConversion? ICK_Compatible_Conversion
2902 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002903 ICS.Standard.Third = ICK_Identity;
2904 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2905 ICS.Standard.setToType(0, T2);
2906 ICS.Standard.setToType(1, T1);
2907 ICS.Standard.setToType(2, T1);
2908 ICS.Standard.ReferenceBinding = true;
2909 ICS.Standard.DirectBinding = true;
2910 ICS.Standard.RRefBinding = isRValRef;
2911 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002912
Sebastian Redld92badf2010-06-30 18:13:39 +00002913 // Nothing more to do: the inaccessibility/ambiguity check for
2914 // derived-to-base conversions is suppressed when we're
2915 // computing the implicit conversion sequence (C++
2916 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002917 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002918 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002919
Sebastian Redld92badf2010-06-30 18:13:39 +00002920 // -- has a class type (i.e., T2 is a class type), where T1 is
2921 // not reference-related to T2, and can be implicitly
2922 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2923 // is reference-compatible with "cv3 T3" 92) (this
2924 // conversion is selected by enumerating the applicable
2925 // conversion functions (13.3.1.6) and choosing the best
2926 // one through overload resolution (13.3)),
2927 if (!SuppressUserConversions && T2->isRecordType() &&
2928 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2929 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002930 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2931 Init, T2, /*AllowRvalues=*/false,
2932 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002933 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002934 }
2935 }
2936
Sebastian Redld92badf2010-06-30 18:13:39 +00002937 // -- Otherwise, the reference shall be an lvalue reference to a
2938 // non-volatile const type (i.e., cv1 shall be const), or the reference
2939 // shall be an rvalue reference and the initializer expression shall be
2940 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002941 //
2942 // We actually handle one oddity of C++ [over.ics.ref] at this
2943 // point, which is that, due to p2 (which short-circuits reference
2944 // binding by only attempting a simple conversion for non-direct
2945 // bindings) and p3's strange wording, we allow a const volatile
2946 // reference to bind to an rvalue. Hence the check for the presence
2947 // of "const" rather than checking for "const" being the only
2948 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002949 // This is also the point where rvalue references and lvalue inits no longer
2950 // go together.
2951 if ((!isRValRef && !T1.isConstQualified()) ||
2952 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002953 return ICS;
2954
Sebastian Redld92badf2010-06-30 18:13:39 +00002955 // -- If T1 is a function type, then
2956 // -- if T2 is the same type as T1, the reference is bound to the
2957 // initializer expression lvalue;
2958 // -- if T2 is a class type and the initializer expression can be
2959 // implicitly converted to an lvalue of type T1 [...], the
2960 // reference is bound to the function lvalue that is the result
2961 // of the conversion;
2962 // This is the same as for the lvalue case above, so it was handled there.
2963 // -- otherwise, the program is ill-formed.
2964 // This is the one difference to the lvalue case.
2965 if (T1->isFunctionType())
2966 return ICS;
2967
2968 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002969 // -- the initializer expression is an rvalue and "cv1 T1"
2970 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002971 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002972 // -- T1 is not reference-related to T2 and the initializer
2973 // expression can be implicitly converted to an rvalue
2974 // of type "cv3 T3" (this conversion is selected by
2975 // enumerating the applicable conversion functions
2976 // (13.3.1.6) and choosing the best one through overload
2977 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002978 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002979 // then the reference is bound to the initializer
2980 // expression rvalue in the first case and to the object
2981 // that is the result of the conversion in the second case
2982 // (or, in either case, to the appropriate base class
2983 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002984 if (T2->isRecordType()) {
2985 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2986 // direct binding in C++0x but not in C++03.
2987 if (InitCategory.isRValue() &&
2988 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2989 ICS.setStandard();
2990 ICS.Standard.First = ICK_Identity;
2991 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2992 : ObjCConversion? ICK_Compatible_Conversion
2993 : ICK_Identity;
2994 ICS.Standard.Third = ICK_Identity;
2995 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2996 ICS.Standard.setToType(0, T2);
2997 ICS.Standard.setToType(1, T1);
2998 ICS.Standard.setToType(2, T1);
2999 ICS.Standard.ReferenceBinding = true;
3000 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3001 ICS.Standard.RRefBinding = isRValRef;
3002 ICS.Standard.CopyConstructor = 0;
3003 return ICS;
3004 }
3005
3006 // Second case: not reference-related.
3007 if (RefRelationship == Sema::Ref_Incompatible &&
3008 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3009 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3010 Init, T2, /*AllowRvalues=*/true,
3011 AllowExplicit))
3012 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003013 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00003014
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003015 // -- Otherwise, a temporary of type "cv1 T1" is created and
3016 // initialized from the initializer expression using the
3017 // rules for a non-reference copy initialization (8.5). The
3018 // reference is then bound to the temporary. If T1 is
3019 // reference-related to T2, cv1 must be the same
3020 // cv-qualification as, or greater cv-qualification than,
3021 // cv2; otherwise, the program is ill-formed.
3022 if (RefRelationship == Sema::Ref_Related) {
3023 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3024 // we would be reference-compatible or reference-compatible with
3025 // added qualification. But that wasn't the case, so the reference
3026 // initialization fails.
3027 return ICS;
3028 }
3029
3030 // If at least one of the types is a class type, the types are not
3031 // related, and we aren't allowed any user conversions, the
3032 // reference binding fails. This case is important for breaking
3033 // recursion, since TryImplicitConversion below will attempt to
3034 // create a temporary through the use of a copy constructor.
3035 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3036 (T1->isRecordType() || T2->isRecordType()))
3037 return ICS;
3038
3039 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003040 // When a parameter of reference type is not bound directly to
3041 // an argument expression, the conversion sequence is the one
3042 // required to convert the argument expression to the
3043 // underlying type of the reference according to
3044 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3045 // to copy-initializing a temporary of the underlying type with
3046 // the argument expression. Any difference in top-level
3047 // cv-qualification is subsumed by the initialization itself
3048 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003049 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3050 /*AllowExplicit=*/false,
3051 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003052
3053 // Of course, that's still a reference binding.
3054 if (ICS.isStandard()) {
3055 ICS.Standard.ReferenceBinding = true;
3056 ICS.Standard.RRefBinding = isRValRef;
3057 } else if (ICS.isUserDefined()) {
3058 ICS.UserDefined.After.ReferenceBinding = true;
3059 ICS.UserDefined.After.RRefBinding = isRValRef;
3060 }
3061 return ICS;
3062}
3063
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003064/// TryCopyInitialization - Try to copy-initialize a value of type
3065/// ToType from the expression From. Return the implicit conversion
3066/// sequence required to pass this argument, which may be a bad
3067/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003068/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003069/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003070static ImplicitConversionSequence
3071TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003072 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003073 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003074 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003075 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003076 /*FIXME:*/From->getLocStart(),
3077 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003078 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003079
John McCall5c32be02010-08-24 20:38:10 +00003080 return TryImplicitConversion(S, From, ToType,
3081 SuppressUserConversions,
3082 /*AllowExplicit=*/false,
3083 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003084}
3085
Douglas Gregor436424c2008-11-18 23:14:02 +00003086/// TryObjectArgumentInitialization - Try to initialize the object
3087/// parameter of the given member function (@c Method) from the
3088/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003089static ImplicitConversionSequence
3090TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3091 CXXMethodDecl *Method,
3092 CXXRecordDecl *ActingContext) {
3093 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003094 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3095 // const volatile object.
3096 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3097 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003098 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003099
3100 // Set up the conversion sequence as a "bad" conversion, to allow us
3101 // to exit early.
3102 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003103
3104 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003105 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003106 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003107 FromType = PT->getPointeeType();
3108
3109 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003110
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003111 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003112 // where X is the class of which the function is a member
3113 // (C++ [over.match.funcs]p4). However, when finding an implicit
3114 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003115 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003116 // (C++ [over.match.funcs]p5). We perform a simplified version of
3117 // reference binding here, that allows class rvalues to bind to
3118 // non-constant references.
3119
3120 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3121 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003122 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003123 if (ImplicitParamType.getCVRQualifiers()
3124 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003125 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003126 ICS.setBad(BadConversionSequence::bad_qualifiers,
3127 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003128 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003129 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003130
3131 // Check that we have either the same type or a derived type. It
3132 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003133 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003134 ImplicitConversionKind SecondKind;
3135 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3136 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003137 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003138 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003139 else {
John McCall65eb8792010-02-25 01:37:24 +00003140 ICS.setBad(BadConversionSequence::unrelated_class,
3141 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003142 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003143 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003144
3145 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003146 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003147 ICS.Standard.setAsIdentityConversion();
3148 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003149 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003150 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003151 ICS.Standard.ReferenceBinding = true;
3152 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003153 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003154 return ICS;
3155}
3156
3157/// PerformObjectArgumentInitialization - Perform initialization of
3158/// the implicit object parameter for the given Method with the given
3159/// expression.
3160bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003161Sema::PerformObjectArgumentInitialization(Expr *&From,
3162 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003163 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003164 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003165 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003166 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003167 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003168
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003169 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003170 FromRecordType = PT->getPointeeType();
3171 DestType = Method->getThisType(Context);
3172 } else {
3173 FromRecordType = From->getType();
3174 DestType = ImplicitParamRecordType;
3175 }
3176
John McCall6e9f8f62009-12-03 04:06:58 +00003177 // Note that we always use the true parent context when performing
3178 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003179 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003180 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003181 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003182 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003183 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003184 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003185 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003186
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003187 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003188 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003189
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003190 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003191 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003192 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003193 return false;
3194}
3195
Douglas Gregor5fb53972009-01-14 15:45:31 +00003196/// TryContextuallyConvertToBool - Attempt to contextually convert the
3197/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003198static ImplicitConversionSequence
3199TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003200 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003201 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003202 // FIXME: Are these flags correct?
3203 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003204 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003205 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003206}
3207
3208/// PerformContextuallyConvertToBool - Perform a contextual conversion
3209/// of the expression From to bool (C++0x [conv]p3).
3210bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003211 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003212 if (!ICS.isBad())
3213 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003214
Fariborz Jahanian76197412009-11-18 18:26:29 +00003215 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003216 return Diag(From->getSourceRange().getBegin(),
3217 diag::err_typecheck_bool_condition)
3218 << From->getType() << From->getSourceRange();
3219 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003220}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003221
3222/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3223/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003224static ImplicitConversionSequence
3225TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3226 QualType Ty = S.Context.getObjCIdType();
3227 return TryImplicitConversion(S, From, Ty,
3228 // FIXME: Are these flags correct?
3229 /*SuppressUserConversions=*/false,
3230 /*AllowExplicit=*/true,
3231 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003232}
John McCall5c32be02010-08-24 20:38:10 +00003233
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003234/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3235/// of the expression From to 'id'.
3236bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003237 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003238 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003239 if (!ICS.isBad())
3240 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3241 return true;
3242}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003243
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003244/// \brief Attempt to convert the given expression to an integral or
3245/// enumeration type.
3246///
3247/// This routine will attempt to convert an expression of class type to an
3248/// integral or enumeration type, if that class type only has a single
3249/// conversion to an integral or enumeration type.
3250///
Douglas Gregor4799d032010-06-30 00:20:43 +00003251/// \param Loc The source location of the construct that requires the
3252/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003253///
Douglas Gregor4799d032010-06-30 00:20:43 +00003254/// \param FromE The expression we're converting from.
3255///
3256/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3257/// have integral or enumeration type.
3258///
3259/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3260/// incomplete class type.
3261///
3262/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3263/// explicit conversion function (because no implicit conversion functions
3264/// were available). This is a recovery mode.
3265///
3266/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3267/// showing which conversion was picked.
3268///
3269/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3270/// conversion function that could convert to integral or enumeration type.
3271///
3272/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3273/// usable conversion function.
3274///
3275/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3276/// function, which may be an extension in this case.
3277///
3278/// \returns The expression, converted to an integral or enumeration type if
3279/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003280ExprResult
John McCallb268a282010-08-23 23:25:46 +00003281Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003282 const PartialDiagnostic &NotIntDiag,
3283 const PartialDiagnostic &IncompleteDiag,
3284 const PartialDiagnostic &ExplicitConvDiag,
3285 const PartialDiagnostic &ExplicitConvNote,
3286 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003287 const PartialDiagnostic &AmbigNote,
3288 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003289 // We can't perform any more checking for type-dependent expressions.
3290 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003291 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003292
3293 // If the expression already has integral or enumeration type, we're golden.
3294 QualType T = From->getType();
3295 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003296 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003297
3298 // FIXME: Check for missing '()' if T is a function type?
3299
3300 // If we don't have a class type in C++, there's no way we can get an
3301 // expression of integral or enumeration type.
3302 const RecordType *RecordTy = T->getAs<RecordType>();
3303 if (!RecordTy || !getLangOptions().CPlusPlus) {
3304 Diag(Loc, NotIntDiag)
3305 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003306 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003307 }
3308
3309 // We must have a complete class type.
3310 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003311 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003312
3313 // Look for a conversion to an integral or enumeration type.
3314 UnresolvedSet<4> ViableConversions;
3315 UnresolvedSet<4> ExplicitConversions;
3316 const UnresolvedSetImpl *Conversions
3317 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3318
3319 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3320 E = Conversions->end();
3321 I != E;
3322 ++I) {
3323 if (CXXConversionDecl *Conversion
3324 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3325 if (Conversion->getConversionType().getNonReferenceType()
3326 ->isIntegralOrEnumerationType()) {
3327 if (Conversion->isExplicit())
3328 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3329 else
3330 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3331 }
3332 }
3333
3334 switch (ViableConversions.size()) {
3335 case 0:
3336 if (ExplicitConversions.size() == 1) {
3337 DeclAccessPair Found = ExplicitConversions[0];
3338 CXXConversionDecl *Conversion
3339 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3340
3341 // The user probably meant to invoke the given explicit
3342 // conversion; use it.
3343 QualType ConvTy
3344 = Conversion->getConversionType().getNonReferenceType();
3345 std::string TypeStr;
3346 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3347
3348 Diag(Loc, ExplicitConvDiag)
3349 << T << ConvTy
3350 << FixItHint::CreateInsertion(From->getLocStart(),
3351 "static_cast<" + TypeStr + ">(")
3352 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3353 ")");
3354 Diag(Conversion->getLocation(), ExplicitConvNote)
3355 << ConvTy->isEnumeralType() << ConvTy;
3356
3357 // If we aren't in a SFINAE context, build a call to the
3358 // explicit conversion function.
3359 if (isSFINAEContext())
3360 return ExprError();
3361
3362 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003363 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003364 }
3365
3366 // We'll complain below about a non-integral condition type.
3367 break;
3368
3369 case 1: {
3370 // Apply this conversion.
3371 DeclAccessPair Found = ViableConversions[0];
3372 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003373
3374 CXXConversionDecl *Conversion
3375 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3376 QualType ConvTy
3377 = Conversion->getConversionType().getNonReferenceType();
3378 if (ConvDiag.getDiagID()) {
3379 if (isSFINAEContext())
3380 return ExprError();
3381
3382 Diag(Loc, ConvDiag)
3383 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3384 }
3385
John McCallb268a282010-08-23 23:25:46 +00003386 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003387 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003388 break;
3389 }
3390
3391 default:
3392 Diag(Loc, AmbigDiag)
3393 << T << From->getSourceRange();
3394 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3395 CXXConversionDecl *Conv
3396 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3397 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3398 Diag(Conv->getLocation(), AmbigNote)
3399 << ConvTy->isEnumeralType() << ConvTy;
3400 }
John McCallb268a282010-08-23 23:25:46 +00003401 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003402 }
3403
Douglas Gregor5823da32010-06-29 23:25:20 +00003404 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003405 Diag(Loc, NotIntDiag)
3406 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003407
John McCallb268a282010-08-23 23:25:46 +00003408 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003409}
3410
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003411/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003412/// candidate functions, using the given function call arguments. If
3413/// @p SuppressUserConversions, then don't allow user-defined
3414/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003415///
3416/// \para PartialOverloading true if we are performing "partial" overloading
3417/// based on an incomplete set of function arguments. This feature is used by
3418/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003419void
3420Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003421 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003422 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003423 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003424 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003425 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003426 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003427 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003428 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003429 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003430 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003431
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003433 if (!isa<CXXConstructorDecl>(Method)) {
3434 // If we get here, it's because we're calling a member function
3435 // that is named without a member access expression (e.g.,
3436 // "this->f") that was either written explicitly or created
3437 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003438 // function, e.g., X::f(). We use an empty type for the implied
3439 // object argument (C++ [over.call.func]p3), and the acting context
3440 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003441 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003442 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003443 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003444 return;
3445 }
3446 // We treat a constructor like a non-member function, since its object
3447 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003448 }
3449
Douglas Gregorff7028a2009-11-13 23:59:09 +00003450 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003451 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003452
Douglas Gregor27381f32009-11-23 12:27:39 +00003453 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003454 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003455
Douglas Gregorffe14e32009-11-14 01:20:54 +00003456 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3457 // C++ [class.copy]p3:
3458 // A member function template is never instantiated to perform the copy
3459 // of a class object to an object of its class type.
3460 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3461 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003462 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003463 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3464 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003465 return;
3466 }
3467
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003468 // Add this candidate
3469 CandidateSet.push_back(OverloadCandidate());
3470 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003471 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003472 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003473 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003474 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003475 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003476
3477 unsigned NumArgsInProto = Proto->getNumArgs();
3478
3479 // (C++ 13.3.2p2): A candidate function having fewer than m
3480 // parameters is viable only if it has an ellipsis in its parameter
3481 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003482 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3483 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003484 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003485 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003486 return;
3487 }
3488
3489 // (C++ 13.3.2p2): A candidate function having more than m parameters
3490 // is viable only if the (m+1)st parameter has a default argument
3491 // (8.3.6). For the purposes of overload resolution, the
3492 // parameter list is truncated on the right, so that there are
3493 // exactly m parameters.
3494 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003495 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003496 // Not enough arguments.
3497 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003498 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003499 return;
3500 }
3501
3502 // Determine the implicit conversion sequences for each of the
3503 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003504 Candidate.Conversions.resize(NumArgs);
3505 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3506 if (ArgIdx < NumArgsInProto) {
3507 // (C++ 13.3.2p3): for F to be a viable function, there shall
3508 // exist for each argument an implicit conversion sequence
3509 // (13.3.3.1) that converts that argument to the corresponding
3510 // parameter of F.
3511 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003512 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003513 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003514 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003515 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003516 if (Candidate.Conversions[ArgIdx].isBad()) {
3517 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003518 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003519 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003520 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003521 } else {
3522 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3523 // argument for which there is no corresponding parameter is
3524 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003525 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003526 }
3527 }
3528}
3529
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003530/// \brief Add all of the function declarations in the given function set to
3531/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003532void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003533 Expr **Args, unsigned NumArgs,
3534 OverloadCandidateSet& CandidateSet,
3535 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003536 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003537 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003539 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003540 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003541 cast<CXXMethodDecl>(FD)->getParent(),
3542 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003543 CandidateSet, SuppressUserConversions);
3544 else
John McCalla0296f72010-03-19 07:35:19 +00003545 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003546 SuppressUserConversions);
3547 } else {
John McCalla0296f72010-03-19 07:35:19 +00003548 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003549 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3550 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003551 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003552 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003553 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003554 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003555 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003556 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003557 else
John McCalla0296f72010-03-19 07:35:19 +00003558 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003559 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003560 Args, NumArgs, CandidateSet,
3561 SuppressUserConversions);
3562 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003563 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003564}
3565
John McCallf0f1cf02009-11-17 07:50:12 +00003566/// AddMethodCandidate - Adds a named decl (which is some kind of
3567/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003568void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003569 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003570 Expr **Args, unsigned NumArgs,
3571 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003572 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003573 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003574 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003575
3576 if (isa<UsingShadowDecl>(Decl))
3577 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3578
3579 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3580 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3581 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003582 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3583 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003584 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003585 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003586 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003587 } else {
John McCalla0296f72010-03-19 07:35:19 +00003588 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003589 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003590 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003591 }
3592}
3593
Douglas Gregor436424c2008-11-18 23:14:02 +00003594/// AddMethodCandidate - Adds the given C++ member function to the set
3595/// of candidate functions, using the given function call arguments
3596/// and the object argument (@c Object). For example, in a call
3597/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3598/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3599/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003600/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003601void
John McCalla0296f72010-03-19 07:35:19 +00003602Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003603 CXXRecordDecl *ActingContext, QualType ObjectType,
3604 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003605 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003606 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003607 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003608 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003609 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003610 assert(!isa<CXXConstructorDecl>(Method) &&
3611 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003612
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003613 if (!CandidateSet.isNewCandidate(Method))
3614 return;
3615
Douglas Gregor27381f32009-11-23 12:27:39 +00003616 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003617 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003618
Douglas Gregor436424c2008-11-18 23:14:02 +00003619 // Add this candidate
3620 CandidateSet.push_back(OverloadCandidate());
3621 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003622 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003623 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003624 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003625 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003626
3627 unsigned NumArgsInProto = Proto->getNumArgs();
3628
3629 // (C++ 13.3.2p2): A candidate function having fewer than m
3630 // parameters is viable only if it has an ellipsis in its parameter
3631 // list (8.3.5).
3632 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3633 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003634 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003635 return;
3636 }
3637
3638 // (C++ 13.3.2p2): A candidate function having more than m parameters
3639 // is viable only if the (m+1)st parameter has a default argument
3640 // (8.3.6). For the purposes of overload resolution, the
3641 // parameter list is truncated on the right, so that there are
3642 // exactly m parameters.
3643 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3644 if (NumArgs < MinRequiredArgs) {
3645 // Not enough arguments.
3646 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003647 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003648 return;
3649 }
3650
3651 Candidate.Viable = true;
3652 Candidate.Conversions.resize(NumArgs + 1);
3653
John McCall6e9f8f62009-12-03 04:06:58 +00003654 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003655 // The implicit object argument is ignored.
3656 Candidate.IgnoreObjectArgument = true;
3657 else {
3658 // Determine the implicit conversion sequence for the object
3659 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003660 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003661 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3662 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003663 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003664 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003665 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003666 return;
3667 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003668 }
3669
3670 // Determine the implicit conversion sequences for each of the
3671 // arguments.
3672 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3673 if (ArgIdx < NumArgsInProto) {
3674 // (C++ 13.3.2p3): for F to be a viable function, there shall
3675 // exist for each argument an implicit conversion sequence
3676 // (13.3.3.1) that converts that argument to the corresponding
3677 // parameter of F.
3678 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003679 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003680 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003681 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003682 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003683 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003684 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003685 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003686 break;
3687 }
3688 } else {
3689 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3690 // argument for which there is no corresponding parameter is
3691 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003692 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003693 }
3694 }
3695}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003696
Douglas Gregor97628d62009-08-21 00:16:32 +00003697/// \brief Add a C++ member function template as a candidate to the candidate
3698/// set, using template argument deduction to produce an appropriate member
3699/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003700void
Douglas Gregor97628d62009-08-21 00:16:32 +00003701Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003702 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003703 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003704 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003705 QualType ObjectType,
3706 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003707 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003708 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003709 if (!CandidateSet.isNewCandidate(MethodTmpl))
3710 return;
3711
Douglas Gregor97628d62009-08-21 00:16:32 +00003712 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003713 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003714 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003715 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003716 // candidate functions in the usual way.113) A given name can refer to one
3717 // or more function templates and also to a set of overloaded non-template
3718 // functions. In such a case, the candidate functions generated from each
3719 // function template are combined with the set of non-template candidate
3720 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003721 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003722 FunctionDecl *Specialization = 0;
3723 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003724 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003725 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003726 CandidateSet.push_back(OverloadCandidate());
3727 OverloadCandidate &Candidate = CandidateSet.back();
3728 Candidate.FoundDecl = FoundDecl;
3729 Candidate.Function = MethodTmpl->getTemplatedDecl();
3730 Candidate.Viable = false;
3731 Candidate.FailureKind = ovl_fail_bad_deduction;
3732 Candidate.IsSurrogate = false;
3733 Candidate.IgnoreObjectArgument = false;
3734 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3735 Info);
3736 return;
3737 }
Mike Stump11289f42009-09-09 15:08:12 +00003738
Douglas Gregor97628d62009-08-21 00:16:32 +00003739 // Add the function template specialization produced by template argument
3740 // deduction as a candidate.
3741 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003742 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003743 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003744 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003745 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003746 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003747}
3748
Douglas Gregor05155d82009-08-21 23:19:43 +00003749/// \brief Add a C++ function template specialization as a candidate
3750/// in the candidate set, using template argument deduction to produce
3751/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003752void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003753Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003754 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003755 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003756 Expr **Args, unsigned NumArgs,
3757 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003758 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003759 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3760 return;
3761
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003762 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003763 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003764 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003765 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003766 // candidate functions in the usual way.113) A given name can refer to one
3767 // or more function templates and also to a set of overloaded non-template
3768 // functions. In such a case, the candidate functions generated from each
3769 // function template are combined with the set of non-template candidate
3770 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003771 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003772 FunctionDecl *Specialization = 0;
3773 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003774 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003775 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003776 CandidateSet.push_back(OverloadCandidate());
3777 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003778 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003779 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3780 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003781 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003782 Candidate.IsSurrogate = false;
3783 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003784 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3785 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003786 return;
3787 }
Mike Stump11289f42009-09-09 15:08:12 +00003788
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003789 // Add the function template specialization produced by template argument
3790 // deduction as a candidate.
3791 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003792 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003793 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003794}
Mike Stump11289f42009-09-09 15:08:12 +00003795
Douglas Gregora1f013e2008-11-07 22:36:19 +00003796/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003797/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003798/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003799/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003800/// (which may or may not be the same type as the type that the
3801/// conversion function produces).
3802void
3803Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003804 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003805 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003806 Expr *From, QualType ToType,
3807 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003808 assert(!Conversion->getDescribedFunctionTemplate() &&
3809 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003810 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003811 if (!CandidateSet.isNewCandidate(Conversion))
3812 return;
3813
Douglas Gregor27381f32009-11-23 12:27:39 +00003814 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003815 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003816
Douglas Gregora1f013e2008-11-07 22:36:19 +00003817 // Add this candidate
3818 CandidateSet.push_back(OverloadCandidate());
3819 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003820 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003821 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003822 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003823 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003824 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003825 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003826 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003827 Candidate.Viable = true;
3828 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003829
Douglas Gregor6affc782010-08-19 15:37:02 +00003830 // C++ [over.match.funcs]p4:
3831 // For conversion functions, the function is considered to be a member of
3832 // the class of the implicit implied object argument for the purpose of
3833 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003834 //
3835 // Determine the implicit conversion sequence for the implicit
3836 // object parameter.
3837 QualType ImplicitParamType = From->getType();
3838 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3839 ImplicitParamType = FromPtrType->getPointeeType();
3840 CXXRecordDecl *ConversionContext
3841 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3842
3843 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003844 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003845 ConversionContext);
3846
John McCall0d1da222010-01-12 00:44:57 +00003847 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003848 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003849 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003850 return;
3851 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003852
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003853 // We won't go through a user-define type conversion function to convert a
3854 // derived to base as such conversions are given Conversion Rank. They only
3855 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3856 QualType FromCanon
3857 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3858 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3859 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3860 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003861 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003862 return;
3863 }
3864
Douglas Gregora1f013e2008-11-07 22:36:19 +00003865 // To determine what the conversion from the result of calling the
3866 // conversion function to the type we're eventually trying to
3867 // convert to (ToType), we need to synthesize a call to the
3868 // conversion function and attempt copy initialization from it. This
3869 // makes sure that we get the right semantics with respect to
3870 // lvalues/rvalues and the type. Fortunately, we can allocate this
3871 // call on the stack and we don't need its arguments to be
3872 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003873 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003874 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003875 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3876 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003877 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003878 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003879
3880 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003881 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3882 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003883 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003884 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003885 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003886 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003887 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003888 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003889 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003890
John McCall0d1da222010-01-12 00:44:57 +00003891 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003892 case ImplicitConversionSequence::StandardConversion:
3893 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003894
3895 // C++ [over.ics.user]p3:
3896 // If the user-defined conversion is specified by a specialization of a
3897 // conversion function template, the second standard conversion sequence
3898 // shall have exact match rank.
3899 if (Conversion->getPrimaryTemplate() &&
3900 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3901 Candidate.Viable = false;
3902 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3903 }
3904
Douglas Gregora1f013e2008-11-07 22:36:19 +00003905 break;
3906
3907 case ImplicitConversionSequence::BadConversion:
3908 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003909 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003910 break;
3911
3912 default:
Mike Stump11289f42009-09-09 15:08:12 +00003913 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003914 "Can only end up with a standard conversion sequence or failure");
3915 }
3916}
3917
Douglas Gregor05155d82009-08-21 23:19:43 +00003918/// \brief Adds a conversion function template specialization
3919/// candidate to the overload set, using template argument deduction
3920/// to deduce the template arguments of the conversion function
3921/// template from the type that we are converting to (C++
3922/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003923void
Douglas Gregor05155d82009-08-21 23:19:43 +00003924Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003925 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003926 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003927 Expr *From, QualType ToType,
3928 OverloadCandidateSet &CandidateSet) {
3929 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3930 "Only conversion function templates permitted here");
3931
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003932 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3933 return;
3934
John McCallbc077cf2010-02-08 23:07:23 +00003935 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003936 CXXConversionDecl *Specialization = 0;
3937 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003938 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003939 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003940 CandidateSet.push_back(OverloadCandidate());
3941 OverloadCandidate &Candidate = CandidateSet.back();
3942 Candidate.FoundDecl = FoundDecl;
3943 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3944 Candidate.Viable = false;
3945 Candidate.FailureKind = ovl_fail_bad_deduction;
3946 Candidate.IsSurrogate = false;
3947 Candidate.IgnoreObjectArgument = false;
3948 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3949 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003950 return;
3951 }
Mike Stump11289f42009-09-09 15:08:12 +00003952
Douglas Gregor05155d82009-08-21 23:19:43 +00003953 // Add the conversion function template specialization produced by
3954 // template argument deduction as a candidate.
3955 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003956 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003957 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003958}
3959
Douglas Gregorab7897a2008-11-19 22:57:39 +00003960/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3961/// converts the given @c Object to a function pointer via the
3962/// conversion function @c Conversion, and then attempts to call it
3963/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3964/// the type of function that we'll eventually be calling.
3965void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003966 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003967 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003968 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003969 QualType ObjectType,
3970 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003971 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003972 if (!CandidateSet.isNewCandidate(Conversion))
3973 return;
3974
Douglas Gregor27381f32009-11-23 12:27:39 +00003975 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003976 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003977
Douglas Gregorab7897a2008-11-19 22:57:39 +00003978 CandidateSet.push_back(OverloadCandidate());
3979 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003980 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003981 Candidate.Function = 0;
3982 Candidate.Surrogate = Conversion;
3983 Candidate.Viable = true;
3984 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003985 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003986 Candidate.Conversions.resize(NumArgs + 1);
3987
3988 // Determine the implicit conversion sequence for the implicit
3989 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003990 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00003991 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3992 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003993 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003994 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003995 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003996 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003997 return;
3998 }
3999
4000 // The first conversion is actually a user-defined conversion whose
4001 // first conversion is ObjectInit's standard conversion (which is
4002 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004003 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004004 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004005 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004006 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00004007 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004008 = Candidate.Conversions[0].UserDefined.Before;
4009 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4010
Mike Stump11289f42009-09-09 15:08:12 +00004011 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004012 unsigned NumArgsInProto = Proto->getNumArgs();
4013
4014 // (C++ 13.3.2p2): A candidate function having fewer than m
4015 // parameters is viable only if it has an ellipsis in its parameter
4016 // list (8.3.5).
4017 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4018 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004019 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004020 return;
4021 }
4022
4023 // Function types don't have any default arguments, so just check if
4024 // we have enough arguments.
4025 if (NumArgs < NumArgsInProto) {
4026 // Not enough arguments.
4027 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004028 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004029 return;
4030 }
4031
4032 // Determine the implicit conversion sequences for each of the
4033 // arguments.
4034 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4035 if (ArgIdx < NumArgsInProto) {
4036 // (C++ 13.3.2p3): for F to be a viable function, there shall
4037 // exist for each argument an implicit conversion sequence
4038 // (13.3.3.1) that converts that argument to the corresponding
4039 // parameter of F.
4040 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004041 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004042 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004043 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004044 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004045 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004046 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004047 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004048 break;
4049 }
4050 } else {
4051 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4052 // argument for which there is no corresponding parameter is
4053 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004054 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004055 }
4056 }
4057}
4058
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004059/// \brief Add overload candidates for overloaded operators that are
4060/// member functions.
4061///
4062/// Add the overloaded operator candidates that are member functions
4063/// for the operator Op that was used in an operator expression such
4064/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4065/// CandidateSet will store the added overload candidates. (C++
4066/// [over.match.oper]).
4067void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4068 SourceLocation OpLoc,
4069 Expr **Args, unsigned NumArgs,
4070 OverloadCandidateSet& CandidateSet,
4071 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004072 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4073
4074 // C++ [over.match.oper]p3:
4075 // For a unary operator @ with an operand of a type whose
4076 // cv-unqualified version is T1, and for a binary operator @ with
4077 // a left operand of a type whose cv-unqualified version is T1 and
4078 // a right operand of a type whose cv-unqualified version is T2,
4079 // three sets of candidate functions, designated member
4080 // candidates, non-member candidates and built-in candidates, are
4081 // constructed as follows:
4082 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004083
4084 // -- If T1 is a class type, the set of member candidates is the
4085 // result of the qualified lookup of T1::operator@
4086 // (13.3.1.1.1); otherwise, the set of member candidates is
4087 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004088 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004089 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004090 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004091 return;
Mike Stump11289f42009-09-09 15:08:12 +00004092
John McCall27b18f82009-11-17 02:14:36 +00004093 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4094 LookupQualifiedName(Operators, T1Rec->getDecl());
4095 Operators.suppressDiagnostics();
4096
Mike Stump11289f42009-09-09 15:08:12 +00004097 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004098 OperEnd = Operators.end();
4099 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004100 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004101 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004102 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004103 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004104 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004105}
4106
Douglas Gregora11693b2008-11-12 17:17:38 +00004107/// AddBuiltinCandidate - Add a candidate for a built-in
4108/// operator. ResultTy and ParamTys are the result and parameter types
4109/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004110/// arguments being passed to the candidate. IsAssignmentOperator
4111/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004112/// operator. NumContextualBoolArguments is the number of arguments
4113/// (at the beginning of the argument list) that will be contextually
4114/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004115void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004116 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004117 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004118 bool IsAssignmentOperator,
4119 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004120 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004121 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004122
Douglas Gregora11693b2008-11-12 17:17:38 +00004123 // Add this candidate
4124 CandidateSet.push_back(OverloadCandidate());
4125 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004126 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004127 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004128 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004129 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004130 Candidate.BuiltinTypes.ResultTy = ResultTy;
4131 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4132 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4133
4134 // Determine the implicit conversion sequences for each of the
4135 // arguments.
4136 Candidate.Viable = true;
4137 Candidate.Conversions.resize(NumArgs);
4138 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004139 // C++ [over.match.oper]p4:
4140 // For the built-in assignment operators, conversions of the
4141 // left operand are restricted as follows:
4142 // -- no temporaries are introduced to hold the left operand, and
4143 // -- no user-defined conversions are applied to the left
4144 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004145 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004146 //
4147 // We block these conversions by turning off user-defined
4148 // conversions, since that is the only way that initialization of
4149 // a reference to a non-class type can occur from something that
4150 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004151 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004152 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004153 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004154 Candidate.Conversions[ArgIdx]
4155 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004156 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004157 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004158 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004159 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004160 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004161 }
John McCall0d1da222010-01-12 00:44:57 +00004162 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004163 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004164 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004165 break;
4166 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004167 }
4168}
4169
4170/// BuiltinCandidateTypeSet - A set of types that will be used for the
4171/// candidate operator functions for built-in operators (C++
4172/// [over.built]). The types are separated into pointer types and
4173/// enumeration types.
4174class BuiltinCandidateTypeSet {
4175 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004176 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004177
4178 /// PointerTypes - The set of pointer types that will be used in the
4179 /// built-in candidates.
4180 TypeSet PointerTypes;
4181
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004182 /// MemberPointerTypes - The set of member pointer types that will be
4183 /// used in the built-in candidates.
4184 TypeSet MemberPointerTypes;
4185
Douglas Gregora11693b2008-11-12 17:17:38 +00004186 /// EnumerationTypes - The set of enumeration types that will be
4187 /// used in the built-in candidates.
4188 TypeSet EnumerationTypes;
4189
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004190 /// \brief The set of vector types that will be used in the built-in
4191 /// candidates.
4192 TypeSet VectorTypes;
4193
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004194 /// Sema - The semantic analysis instance where we are building the
4195 /// candidate type set.
4196 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004197
Douglas Gregora11693b2008-11-12 17:17:38 +00004198 /// Context - The AST context in which we will build the type sets.
4199 ASTContext &Context;
4200
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004201 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4202 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004203 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004204
4205public:
4206 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004207 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004208
Mike Stump11289f42009-09-09 15:08:12 +00004209 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004210 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004211
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004212 void AddTypesConvertedFrom(QualType Ty,
4213 SourceLocation Loc,
4214 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004215 bool AllowExplicitConversions,
4216 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004217
4218 /// pointer_begin - First pointer type found;
4219 iterator pointer_begin() { return PointerTypes.begin(); }
4220
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004221 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004222 iterator pointer_end() { return PointerTypes.end(); }
4223
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004224 /// member_pointer_begin - First member pointer type found;
4225 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4226
4227 /// member_pointer_end - Past the last member pointer type found;
4228 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4229
Douglas Gregora11693b2008-11-12 17:17:38 +00004230 /// enumeration_begin - First enumeration type found;
4231 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4232
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004233 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004234 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004235
4236 iterator vector_begin() { return VectorTypes.begin(); }
4237 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004238};
4239
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004240/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004241/// the set of pointer types along with any more-qualified variants of
4242/// that type. For example, if @p Ty is "int const *", this routine
4243/// will add "int const *", "int const volatile *", "int const
4244/// restrict *", and "int const volatile restrict *" to the set of
4245/// pointer types. Returns true if the add of @p Ty itself succeeded,
4246/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004247///
4248/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004249bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004250BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4251 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004252
Douglas Gregora11693b2008-11-12 17:17:38 +00004253 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004254 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004255 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004256
4257 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004258 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004259 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004260 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004261 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004262 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004263 buildObjCPtr = true;
4264 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004265 else
4266 assert(false && "type was not a pointer type!");
4267 }
4268 else
4269 PointeeTy = PointerTy->getPointeeType();
4270
Sebastian Redl4990a632009-11-18 20:39:26 +00004271 // Don't add qualified variants of arrays. For one, they're not allowed
4272 // (the qualifier would sink to the element type), and for another, the
4273 // only overload situation where it matters is subscript or pointer +- int,
4274 // and those shouldn't have qualifier variants anyway.
4275 if (PointeeTy->isArrayType())
4276 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004277 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004278 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004279 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004280 bool hasVolatile = VisibleQuals.hasVolatile();
4281 bool hasRestrict = VisibleQuals.hasRestrict();
4282
John McCall8ccfcb52009-09-24 19:53:00 +00004283 // Iterate through all strict supersets of BaseCVR.
4284 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4285 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004286 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4287 // in the types.
4288 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4289 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004290 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004291 if (!buildObjCPtr)
4292 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4293 else
4294 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004295 }
4296
4297 return true;
4298}
4299
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004300/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4301/// to the set of pointer types along with any more-qualified variants of
4302/// that type. For example, if @p Ty is "int const *", this routine
4303/// will add "int const *", "int const volatile *", "int const
4304/// restrict *", and "int const volatile restrict *" to the set of
4305/// pointer types. Returns true if the add of @p Ty itself succeeded,
4306/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004307///
4308/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004309bool
4310BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4311 QualType Ty) {
4312 // Insert this type.
4313 if (!MemberPointerTypes.insert(Ty))
4314 return false;
4315
John McCall8ccfcb52009-09-24 19:53:00 +00004316 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4317 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004318
John McCall8ccfcb52009-09-24 19:53:00 +00004319 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004320 // Don't add qualified variants of arrays. For one, they're not allowed
4321 // (the qualifier would sink to the element type), and for another, the
4322 // only overload situation where it matters is subscript or pointer +- int,
4323 // and those shouldn't have qualifier variants anyway.
4324 if (PointeeTy->isArrayType())
4325 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004326 const Type *ClassTy = PointerTy->getClass();
4327
4328 // Iterate through all strict supersets of the pointee type's CVR
4329 // qualifiers.
4330 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4331 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4332 if ((CVR | BaseCVR) != CVR) continue;
4333
4334 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4335 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004336 }
4337
4338 return true;
4339}
4340
Douglas Gregora11693b2008-11-12 17:17:38 +00004341/// AddTypesConvertedFrom - Add each of the types to which the type @p
4342/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004343/// primarily interested in pointer types and enumeration types. We also
4344/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004345/// AllowUserConversions is true if we should look at the conversion
4346/// functions of a class type, and AllowExplicitConversions if we
4347/// should also include the explicit conversion functions of a class
4348/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004349void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004350BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004351 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004352 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004353 bool AllowExplicitConversions,
4354 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004355 // Only deal with canonical types.
4356 Ty = Context.getCanonicalType(Ty);
4357
4358 // Look through reference types; they aren't part of the type of an
4359 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004360 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004361 Ty = RefTy->getPointeeType();
4362
4363 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004364 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004365
Sebastian Redl65ae2002009-11-05 16:36:20 +00004366 // If we're dealing with an array type, decay to the pointer.
4367 if (Ty->isArrayType())
4368 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004369 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4370 PointerTypes.insert(Ty);
4371 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004372 // Insert our type, and its more-qualified variants, into the set
4373 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004374 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004375 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004376 } else if (Ty->isMemberPointerType()) {
4377 // Member pointers are far easier, since the pointee can't be converted.
4378 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4379 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004380 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004381 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004382 } else if (Ty->isVectorType()) {
4383 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004384 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004385 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004386 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004387 // No conversion functions in incomplete types.
4388 return;
4389 }
Mike Stump11289f42009-09-09 15:08:12 +00004390
Douglas Gregora11693b2008-11-12 17:17:38 +00004391 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004392 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004393 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004394 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004395 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004396 NamedDecl *D = I.getDecl();
4397 if (isa<UsingShadowDecl>(D))
4398 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004399
Mike Stump11289f42009-09-09 15:08:12 +00004400 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004401 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004402 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004403 continue;
4404
John McCallda4458e2010-03-31 01:36:47 +00004405 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004406 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004407 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004408 VisibleQuals);
4409 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004410 }
4411 }
4412 }
4413}
4414
Douglas Gregor84605ae2009-08-24 13:43:27 +00004415/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4416/// the volatile- and non-volatile-qualified assignment operators for the
4417/// given type to the candidate set.
4418static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4419 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004420 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004421 unsigned NumArgs,
4422 OverloadCandidateSet &CandidateSet) {
4423 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004424
Douglas Gregor84605ae2009-08-24 13:43:27 +00004425 // T& operator=(T&, T)
4426 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4427 ParamTypes[1] = T;
4428 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4429 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004430
Douglas Gregor84605ae2009-08-24 13:43:27 +00004431 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4432 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004433 ParamTypes[0]
4434 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004435 ParamTypes[1] = T;
4436 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004437 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004438 }
4439}
Mike Stump11289f42009-09-09 15:08:12 +00004440
Sebastian Redl1054fae2009-10-25 17:03:50 +00004441/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4442/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004443static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4444 Qualifiers VRQuals;
4445 const RecordType *TyRec;
4446 if (const MemberPointerType *RHSMPType =
4447 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004448 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004449 else
4450 TyRec = ArgExpr->getType()->getAs<RecordType>();
4451 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004452 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004453 VRQuals.addVolatile();
4454 VRQuals.addRestrict();
4455 return VRQuals;
4456 }
4457
4458 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004459 if (!ClassDecl->hasDefinition())
4460 return VRQuals;
4461
John McCallad371252010-01-20 00:46:10 +00004462 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004463 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004464
John McCallad371252010-01-20 00:46:10 +00004465 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004466 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004467 NamedDecl *D = I.getDecl();
4468 if (isa<UsingShadowDecl>(D))
4469 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4470 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004471 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4472 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4473 CanTy = ResTypeRef->getPointeeType();
4474 // Need to go down the pointer/mempointer chain and add qualifiers
4475 // as see them.
4476 bool done = false;
4477 while (!done) {
4478 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4479 CanTy = ResTypePtr->getPointeeType();
4480 else if (const MemberPointerType *ResTypeMPtr =
4481 CanTy->getAs<MemberPointerType>())
4482 CanTy = ResTypeMPtr->getPointeeType();
4483 else
4484 done = true;
4485 if (CanTy.isVolatileQualified())
4486 VRQuals.addVolatile();
4487 if (CanTy.isRestrictQualified())
4488 VRQuals.addRestrict();
4489 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4490 return VRQuals;
4491 }
4492 }
4493 }
4494 return VRQuals;
4495}
John McCall52872982010-11-13 05:51:15 +00004496
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004497
Douglas Gregord08452f2008-11-19 15:42:04 +00004498/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4499/// operator overloads to the candidate set (C++ [over.built]), based
4500/// on the operator @p Op and the arguments given. For example, if the
4501/// operator is a binary '+', this routine might add "int
4502/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004503void
Mike Stump11289f42009-09-09 15:08:12 +00004504Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004505 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004506 Expr **Args, unsigned NumArgs,
4507 OverloadCandidateSet& CandidateSet) {
John McCall52872982010-11-13 05:51:15 +00004508 // Information about arithmetic types useful to builtin-type
4509 // calculations.
4510
4511 // The "promoted arithmetic types" are the arithmetic
4512 // types are that preserved by promotion (C++ [over.built]p2).
4513
4514 static const unsigned FirstIntegralType = 3;
4515 static const unsigned LastIntegralType = 18;
4516 static const unsigned FirstPromotedIntegralType = 3,
4517 LastPromotedIntegralType = 9;
4518 static const unsigned FirstPromotedArithmeticType = 0,
4519 LastPromotedArithmeticType = 9;
4520 static const unsigned NumArithmeticTypes = 18;
4521
John McCall988ffb72010-11-13 02:01:09 +00004522 static CanQualType ASTContext::* const ArithmeticTypes[NumArithmeticTypes] = {
John McCall52872982010-11-13 05:51:15 +00004523 // Start of promoted types.
4524 &ASTContext::FloatTy,
4525 &ASTContext::DoubleTy,
4526 &ASTContext::LongDoubleTy,
4527
4528 // Start of integral types.
4529 &ASTContext::IntTy,
4530 &ASTContext::LongTy,
4531 &ASTContext::LongLongTy,
4532 &ASTContext::UnsignedIntTy,
4533 &ASTContext::UnsignedLongTy,
4534 &ASTContext::UnsignedLongLongTy,
4535 // End of promoted types.
4536
John McCall988ffb72010-11-13 02:01:09 +00004537 &ASTContext::BoolTy,
4538 &ASTContext::CharTy,
4539 &ASTContext::WCharTy,
4540 &ASTContext::Char16Ty,
4541 &ASTContext::Char32Ty,
4542 &ASTContext::SignedCharTy,
4543 &ASTContext::ShortTy,
4544 &ASTContext::UnsignedCharTy,
John McCall52872982010-11-13 05:51:15 +00004545 &ASTContext::UnsignedShortTy
4546 // End of integral types.
Douglas Gregora11693b2008-11-12 17:17:38 +00004547 };
John McCall52872982010-11-13 05:51:15 +00004548 // FIXME: What about complex?
John McCall988ffb72010-11-13 02:01:09 +00004549 assert(ArithmeticTypes[FirstPromotedIntegralType] == &ASTContext::IntTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004550 "Invalid first promoted integral type");
4551 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
John McCall988ffb72010-11-13 02:01:09 +00004552 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004553 "Invalid last promoted integral type");
John McCall52872982010-11-13 05:51:15 +00004554 assert(ArithmeticTypes[FirstPromotedArithmeticType] == &ASTContext::FloatTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004555 "Invalid first promoted arithmetic type");
4556 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
John McCall52872982010-11-13 05:51:15 +00004557 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004558 "Invalid last promoted arithmetic type");
John McCall52872982010-11-13 05:51:15 +00004559
4560 // Accelerator table for performing the usual arithmetic conversions.
4561 // The rules are basically:
4562 // - if either is floating-point, use the wider floating-point
4563 // - if same signedness, use the higher rank
4564 // - if same size, use unsigned of the higher rank
4565 // - use the larger type
4566 // These rules, together with the axiom that higher ranks are
4567 // never smaller, are sufficient to precompute all of these results
4568 // *except* when dealing with signed types of higher rank.
4569 // (we could precompute SLL x UI for all known platforms, but it's
4570 // better not to make any assumptions).
4571 enum PromT { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 };
4572 static PromT UsualArithmeticConversionsTypes
4573 [LastPromotedArithmeticType][LastPromotedArithmeticType] = {
4574 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4575 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4576 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4577 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4578 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4579 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4580 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4581 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4582 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }
4583 };
4584 struct UsualArithmeticConversionsType {
4585 static CanQualType find(ASTContext &C, unsigned L, unsigned R) {
4586 assert(L < LastPromotedArithmeticType);
4587 assert(R < LastPromotedArithmeticType);
4588 signed char Idx = UsualArithmeticConversionsTypes[L][R];
4589
4590 // Fast path: the table gives us a concrete answer.
4591 if (Idx != Dep) return C.*ArithmeticTypes[Idx];
4592
4593 // Slow path: we need to compare widths.
4594 // An invariant is that the signed type has higher rank.
4595 CanQualType LT = C.*ArithmeticTypes[L], RT = C.*ArithmeticTypes[R];
4596 unsigned LW = C.getIntWidth(LT), RW = C.getIntWidth(RT);
4597
4598 // If they're different widths, use the signed type.
4599 if (LW > RW) return LT;
4600 else if (LW > RW) return RT;
4601
4602 // Otherwise, use the unsigned type of the signed type's rank.
4603 if (L == SL || R == SL) return C.UnsignedLongTy;
4604 assert(L == SLL || R == SLL);
4605 return C.UnsignedLongLongTy;
4606 }
4607 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004608
Douglas Gregora11693b2008-11-12 17:17:38 +00004609 // Find all of the types that the arguments can convert to, but only
4610 // if the operator we're looking at has built-in operator candidates
4611 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004612 Qualifiers VisibleTypeConversionsQuals;
4613 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004614 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4615 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4616
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004617 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4618 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4619 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4620 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4621 OpLoc,
4622 true,
4623 (Op == OO_Exclaim ||
4624 Op == OO_AmpAmp ||
4625 Op == OO_PipePipe),
4626 VisibleTypeConversionsQuals);
4627 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004628
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004629 // C++ [over.built]p1:
4630 // If there is a user-written candidate with the same name and parameter
4631 // types as a built-in candidate operator function, the built-in operator
4632 // function is hidden and is not included in the set of candidate functions.
4633 //
4634 // The text is actually in a note, but if we don't implement it then we end
4635 // up with ambiguities when the user provides an overloaded operator for
4636 // an enumeration type. Note that only enumeration types have this problem,
4637 // so we track which enumeration types we've seen operators for.
4638 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4639 UserDefinedBinaryOperators;
4640
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004641 /// Set of (canonical) types that we've already handled.
4642 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4643
4644 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4645 if (CandidateTypes[ArgIdx].enumeration_begin()
4646 != CandidateTypes[ArgIdx].enumeration_end()) {
4647 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4648 CEnd = CandidateSet.end();
4649 C != CEnd; ++C) {
4650 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4651 continue;
4652
4653 // Check if the first parameter is of enumeration type.
4654 QualType FirstParamType
4655 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4656 if (!FirstParamType->isEnumeralType())
4657 continue;
4658
4659 // Check if the second parameter is of enumeration type.
4660 QualType SecondParamType
4661 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4662 if (!SecondParamType->isEnumeralType())
4663 continue;
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004664
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004665 // Add this operator to the set of known user-defined operators.
4666 UserDefinedBinaryOperators.insert(
4667 std::make_pair(Context.getCanonicalType(FirstParamType),
4668 Context.getCanonicalType(SecondParamType)));
4669 }
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004670 }
4671 }
4672
Douglas Gregora11693b2008-11-12 17:17:38 +00004673 bool isComparison = false;
4674 switch (Op) {
4675 case OO_None:
4676 case NUM_OVERLOADED_OPERATORS:
4677 assert(false && "Expected an overloaded operator");
4678 break;
4679
Douglas Gregord08452f2008-11-19 15:42:04 +00004680 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004681 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004682 goto UnaryStar;
4683 else
4684 goto BinaryStar;
4685 break;
4686
4687 case OO_Plus: // '+' is either unary or binary
4688 if (NumArgs == 1)
4689 goto UnaryPlus;
4690 else
4691 goto BinaryPlus;
4692 break;
4693
4694 case OO_Minus: // '-' is either unary or binary
4695 if (NumArgs == 1)
4696 goto UnaryMinus;
4697 else
4698 goto BinaryMinus;
4699 break;
4700
4701 case OO_Amp: // '&' is either unary or binary
4702 if (NumArgs == 1)
4703 goto UnaryAmp;
4704 else
4705 goto BinaryAmp;
4706
4707 case OO_PlusPlus:
4708 case OO_MinusMinus:
4709 // C++ [over.built]p3:
4710 //
4711 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4712 // is either volatile or empty, there exist candidate operator
4713 // functions of the form
4714 //
4715 // VQ T& operator++(VQ T&);
4716 // T operator++(VQ T&, int);
4717 //
4718 // C++ [over.built]p4:
4719 //
4720 // For every pair (T, VQ), where T is an arithmetic type other
4721 // than bool, and VQ is either volatile or empty, there exist
4722 // candidate operator functions of the form
4723 //
4724 // VQ T& operator--(VQ T&);
4725 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004726 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004727 Arith < NumArithmeticTypes; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004728 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004729 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004730 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004731
4732 // Non-volatile version.
4733 if (NumArgs == 1)
4734 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4735 else
4736 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004737 // heuristic to reduce number of builtin candidates in the set.
4738 // Add volatile version only if there are conversions to a volatile type.
4739 if (VisibleTypeConversionsQuals.hasVolatile()) {
4740 // Volatile version
4741 ParamTypes[0]
4742 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4743 if (NumArgs == 1)
4744 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4745 else
4746 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4747 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004748 }
4749
4750 // C++ [over.built]p5:
4751 //
4752 // For every pair (T, VQ), where T is a cv-qualified or
4753 // cv-unqualified object type, and VQ is either volatile or
4754 // empty, there exist candidate operator functions of the form
4755 //
4756 // T*VQ& operator++(T*VQ&);
4757 // T*VQ& operator--(T*VQ&);
4758 // T* operator++(T*VQ&, int);
4759 // T* operator--(T*VQ&, int);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004760 for (BuiltinCandidateTypeSet::iterator
4761 Ptr = CandidateTypes[0].pointer_begin(),
4762 PtrEnd = CandidateTypes[0].pointer_end();
4763 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004764 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004765 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004766 continue;
4767
Mike Stump11289f42009-09-09 15:08:12 +00004768 QualType ParamTypes[2] = {
4769 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004770 };
Mike Stump11289f42009-09-09 15:08:12 +00004771
Douglas Gregord08452f2008-11-19 15:42:04 +00004772 // Without volatile
4773 if (NumArgs == 1)
4774 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4775 else
4776 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4777
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004778 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4779 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004780 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004781 ParamTypes[0]
4782 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004783 if (NumArgs == 1)
4784 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4785 else
4786 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4787 }
4788 }
4789 break;
4790
4791 UnaryStar:
4792 // C++ [over.built]p6:
4793 // For every cv-qualified or cv-unqualified object type T, there
4794 // exist candidate operator functions of the form
4795 //
4796 // T& operator*(T*);
4797 //
4798 // C++ [over.built]p7:
4799 // For every function type T, there exist candidate operator
4800 // functions of the form
4801 // T& operator*(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004802 for (BuiltinCandidateTypeSet::iterator
4803 Ptr = CandidateTypes[0].pointer_begin(),
4804 PtrEnd = CandidateTypes[0].pointer_end();
4805 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004806 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004807 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004808 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004809 &ParamTy, Args, 1, CandidateSet);
4810 }
4811 break;
4812
4813 UnaryPlus:
4814 // C++ [over.built]p8:
4815 // For every type T, there exist candidate operator functions of
4816 // the form
4817 //
4818 // T* operator+(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004819 for (BuiltinCandidateTypeSet::iterator
4820 Ptr = CandidateTypes[0].pointer_begin(),
4821 PtrEnd = CandidateTypes[0].pointer_end();
4822 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004823 QualType ParamTy = *Ptr;
4824 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4825 }
Mike Stump11289f42009-09-09 15:08:12 +00004826
Douglas Gregord08452f2008-11-19 15:42:04 +00004827 // Fall through
4828
4829 UnaryMinus:
4830 // C++ [over.built]p9:
4831 // For every promoted arithmetic type T, there exist candidate
4832 // operator functions of the form
4833 //
4834 // T operator+(T);
4835 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004836 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004837 Arith < LastPromotedArithmeticType; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004838 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Douglas Gregord08452f2008-11-19 15:42:04 +00004839 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4840 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004841
4842 // Extension: We also add these operators for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004843 for (BuiltinCandidateTypeSet::iterator
4844 Vec = CandidateTypes[0].vector_begin(),
4845 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004846 Vec != VecEnd; ++Vec) {
4847 QualType VecTy = *Vec;
4848 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4849 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004850 break;
4851
4852 case OO_Tilde:
4853 // C++ [over.built]p10:
4854 // For every promoted integral type T, there exist candidate
4855 // operator functions of the form
4856 //
4857 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004858 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004859 Int < LastPromotedIntegralType; ++Int) {
John McCall988ffb72010-11-13 02:01:09 +00004860 QualType IntTy = Context.*ArithmeticTypes[Int];
Douglas Gregord08452f2008-11-19 15:42:04 +00004861 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4862 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004863
4864 // Extension: We also add this operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004865 for (BuiltinCandidateTypeSet::iterator
4866 Vec = CandidateTypes[0].vector_begin(),
4867 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004868 Vec != VecEnd; ++Vec) {
4869 QualType VecTy = *Vec;
4870 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4871 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004872 break;
4873
Douglas Gregora11693b2008-11-12 17:17:38 +00004874 case OO_New:
4875 case OO_Delete:
4876 case OO_Array_New:
4877 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004878 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004879 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004880 break;
4881
4882 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004883 UnaryAmp:
4884 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004885 // C++ [over.match.oper]p3:
4886 // -- For the operator ',', the unary operator '&', or the
4887 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004888 break;
4889
Douglas Gregor84605ae2009-08-24 13:43:27 +00004890 case OO_EqualEqual:
4891 case OO_ExclaimEqual:
4892 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004893 // For every pointer to member type T, there exist candidate operator
4894 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004895 //
4896 // bool operator==(T,T);
4897 // bool operator!=(T,T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004898 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4899 for (BuiltinCandidateTypeSet::iterator
4900 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4901 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4902 MemPtr != MemPtrEnd;
4903 ++MemPtr) {
4904 // Don't add the same builtin candidate twice.
4905 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4906 continue;
4907
4908 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4909 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4910 }
Douglas Gregor84605ae2009-08-24 13:43:27 +00004911 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004912 AddedTypes.clear();
4913
Douglas Gregor84605ae2009-08-24 13:43:27 +00004914 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004915
Douglas Gregora11693b2008-11-12 17:17:38 +00004916 case OO_Less:
4917 case OO_Greater:
4918 case OO_LessEqual:
4919 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004920 // C++ [over.built]p15:
4921 //
4922 // For every pointer or enumeration type T, there exist
4923 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004924 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004925 // bool operator<(T, T);
4926 // bool operator>(T, T);
4927 // bool operator<=(T, T);
4928 // bool operator>=(T, T);
4929 // bool operator==(T, T);
4930 // bool operator!=(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004931 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4932 for (BuiltinCandidateTypeSet::iterator
4933 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4934 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4935 Ptr != PtrEnd; ++Ptr) {
4936 // Don't add the same builtin candidate twice.
4937 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4938 continue;
4939
4940 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004941 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004942 }
4943 for (BuiltinCandidateTypeSet::iterator
4944 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4945 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4946 Enum != EnumEnd; ++Enum) {
4947 // Don't add the same builtin candidate twice.
4948 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4949 continue;
4950
4951 QualType ParamTypes[2] = { *Enum, *Enum };
4952 CanQualType CanonType = Context.getCanonicalType(*Enum);
4953 if (!UserDefinedBinaryOperators.count(
4954 std::make_pair(CanonType, CanonType)))
4955 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4956 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004957 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004958 AddedTypes.clear();
4959
Douglas Gregora11693b2008-11-12 17:17:38 +00004960 // Fall through.
4961 isComparison = true;
4962
Douglas Gregord08452f2008-11-19 15:42:04 +00004963 BinaryPlus:
4964 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004965 if (!isComparison) {
4966 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4967
4968 // C++ [over.built]p13:
4969 //
4970 // For every cv-qualified or cv-unqualified object type T
4971 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004972 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004973 // T* operator+(T*, ptrdiff_t);
4974 // T& operator[](T*, ptrdiff_t); [BELOW]
4975 // T* operator-(T*, ptrdiff_t);
4976 // T* operator+(ptrdiff_t, T*);
4977 // T& operator[](ptrdiff_t, T*); [BELOW]
4978 //
4979 // C++ [over.built]p14:
4980 //
4981 // For every T, where T is a pointer to object type, there
4982 // exist candidate operator functions of the form
4983 //
4984 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004985 for (BuiltinCandidateTypeSet::iterator
4986 Ptr = CandidateTypes[0].pointer_begin(),
4987 PtrEnd = CandidateTypes[0].pointer_end();
4988 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004989 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4990
4991 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4992 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4993
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004994 if (Op == OO_Minus) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004995 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004996 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4997 continue;
4998
Douglas Gregora11693b2008-11-12 17:17:38 +00004999 ParamTypes[1] = *Ptr;
5000 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5001 Args, 2, CandidateSet);
5002 }
5003 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005004
5005 for (BuiltinCandidateTypeSet::iterator
5006 Ptr = CandidateTypes[1].pointer_begin(),
5007 PtrEnd = CandidateTypes[1].pointer_end();
5008 Ptr != PtrEnd; ++Ptr) {
5009 if (Op == OO_Plus) {
5010 // T* operator+(ptrdiff_t, T*);
5011 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5012 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5013 } else {
5014 // ptrdiff_t operator-(T, T);
5015 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5016 continue;
5017
5018 QualType ParamTypes[2] = { *Ptr, *Ptr };
5019 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5020 Args, 2, CandidateSet);
5021 }
5022 }
5023
5024 AddedTypes.clear();
Douglas Gregora11693b2008-11-12 17:17:38 +00005025 }
5026 // Fall through
5027
Douglas Gregora11693b2008-11-12 17:17:38 +00005028 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00005029 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00005030 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00005031 // C++ [over.built]p12:
5032 //
5033 // For every pair of promoted arithmetic types L and R, there
5034 // exist candidate operator functions of the form
5035 //
5036 // LR operator*(L, R);
5037 // LR operator/(L, R);
5038 // LR operator+(L, R);
5039 // LR operator-(L, R);
5040 // bool operator<(L, R);
5041 // bool operator>(L, R);
5042 // bool operator<=(L, R);
5043 // bool operator>=(L, R);
5044 // bool operator==(L, R);
5045 // bool operator!=(L, R);
5046 //
5047 // where LR is the result of the usual arithmetic conversions
5048 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005049 //
5050 // C++ [over.built]p24:
5051 //
5052 // For every pair of promoted arithmetic types L and R, there exist
5053 // candidate operator functions of the form
5054 //
5055 // LR operator?(bool, L, R);
5056 //
5057 // where LR is the result of the usual arithmetic conversions
5058 // between types L and R.
5059 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005060 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005061 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005062 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005063 Right < LastPromotedArithmeticType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005064 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5065 Context.*ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005066 QualType Result
5067 = isComparison
5068 ? Context.BoolTy
John McCall52872982010-11-13 05:51:15 +00005069 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005070 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5071 }
5072 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005073
5074 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5075 // conditional operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005076 for (BuiltinCandidateTypeSet::iterator
5077 Vec1 = CandidateTypes[0].vector_begin(),
5078 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005079 Vec1 != Vec1End; ++Vec1)
5080 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005081 Vec2 = CandidateTypes[1].vector_begin(),
5082 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005083 Vec2 != Vec2End; ++Vec2) {
5084 QualType LandR[2] = { *Vec1, *Vec2 };
5085 QualType Result;
5086 if (isComparison)
5087 Result = Context.BoolTy;
5088 else {
5089 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5090 Result = *Vec1;
5091 else
5092 Result = *Vec2;
5093 }
5094
5095 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5096 }
5097
Douglas Gregora11693b2008-11-12 17:17:38 +00005098 break;
5099
5100 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00005101 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00005102 case OO_Caret:
5103 case OO_Pipe:
5104 case OO_LessLess:
5105 case OO_GreaterGreater:
5106 // C++ [over.built]p17:
5107 //
5108 // For every pair of promoted integral types L and R, there
5109 // exist candidate operator functions of the form
5110 //
5111 // LR operator%(L, R);
5112 // LR operator&(L, R);
5113 // LR operator^(L, R);
5114 // LR operator|(L, R);
5115 // L operator<<(L, R);
5116 // L operator>>(L, R);
5117 //
5118 // where LR is the result of the usual arithmetic conversions
5119 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00005120 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005121 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005122 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005123 Right < LastPromotedIntegralType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005124 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5125 Context.*ArithmeticTypes[Right] };
Douglas Gregora11693b2008-11-12 17:17:38 +00005126 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5127 ? LandR[0]
John McCall52872982010-11-13 05:51:15 +00005128 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005129 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5130 }
5131 }
5132 break;
5133
5134 case OO_Equal:
5135 // C++ [over.built]p20:
5136 //
5137 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00005138 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00005139 // empty, there exist candidate operator functions of the form
5140 //
5141 // VQ T& operator=(VQ T&, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005142 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5143 for (BuiltinCandidateTypeSet::iterator
5144 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5145 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5146 Enum != EnumEnd; ++Enum) {
5147 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5148 continue;
5149
5150 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5151 CandidateSet);
5152 }
5153
5154 for (BuiltinCandidateTypeSet::iterator
5155 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5156 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5157 MemPtr != MemPtrEnd; ++MemPtr) {
5158 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5159 continue;
5160
5161 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5162 CandidateSet);
5163 }
5164 }
5165 AddedTypes.clear();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005166
5167 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005168
5169 case OO_PlusEqual:
5170 case OO_MinusEqual:
5171 // C++ [over.built]p19:
5172 //
5173 // For every pair (T, VQ), where T is any type and VQ is either
5174 // volatile or empty, there exist candidate operator functions
5175 // of the form
5176 //
5177 // T*VQ& operator=(T*VQ&, T*);
5178 //
5179 // C++ [over.built]p21:
5180 //
5181 // For every pair (T, VQ), where T is a cv-qualified or
5182 // cv-unqualified object type and VQ is either volatile or
5183 // empty, there exist candidate operator functions of the form
5184 //
5185 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5186 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005187 for (BuiltinCandidateTypeSet::iterator
5188 Ptr = CandidateTypes[0].pointer_begin(),
5189 PtrEnd = CandidateTypes[0].pointer_end();
5190 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005191 QualType ParamTypes[2];
5192 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5193
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005194 // If this is operator=, keep track of the builtin candidates we added.
5195 if (Op == OO_Equal)
5196 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5197
Douglas Gregora11693b2008-11-12 17:17:38 +00005198 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005199 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005200 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5201 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005202
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005203 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5204 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00005205 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00005206 ParamTypes[0]
5207 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00005208 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5209 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00005210 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005211 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005212
5213 if (Op == OO_Equal) {
5214 for (BuiltinCandidateTypeSet::iterator
5215 Ptr = CandidateTypes[1].pointer_begin(),
5216 PtrEnd = CandidateTypes[1].pointer_end();
5217 Ptr != PtrEnd; ++Ptr) {
5218 // Make sure we don't add the same candidate twice.
5219 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5220 continue;
5221
5222 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5223
5224 // non-volatile version
5225 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5226 /*IsAssigmentOperator=*/true);
5227
5228 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5229 VisibleTypeConversionsQuals.hasVolatile()) {
5230 // volatile version
5231 ParamTypes[0]
5232 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5233 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5234 /*IsAssigmentOperator=*/true);
5235 }
5236 }
5237 AddedTypes.clear();
5238 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005239 // Fall through.
5240
5241 case OO_StarEqual:
5242 case OO_SlashEqual:
5243 // C++ [over.built]p18:
5244 //
5245 // For every triple (L, VQ, R), where L is an arithmetic type,
5246 // VQ is either volatile or empty, and R is a promoted
5247 // arithmetic type, there exist candidate operator functions of
5248 // the form
5249 //
5250 // VQ L& operator=(VQ L&, R);
5251 // VQ L& operator*=(VQ L&, R);
5252 // VQ L& operator/=(VQ L&, R);
5253 // VQ L& operator+=(VQ L&, R);
5254 // VQ L& operator-=(VQ L&, R);
5255 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005256 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005257 Right < LastPromotedArithmeticType; ++Right) {
5258 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005259 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005260
5261 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005262 ParamTypes[0] =
5263 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005264 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5265 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005266
5267 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005268 if (VisibleTypeConversionsQuals.hasVolatile()) {
John McCall988ffb72010-11-13 02:01:09 +00005269 ParamTypes[0] =
5270 Context.getVolatileType(Context.*ArithmeticTypes[Left]);
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005271 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5272 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5273 /*IsAssigmentOperator=*/Op == OO_Equal);
5274 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005275 }
5276 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005277
5278 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005279 for (BuiltinCandidateTypeSet::iterator
5280 Vec1 = CandidateTypes[0].vector_begin(),
5281 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005282 Vec1 != Vec1End; ++Vec1)
5283 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005284 Vec2 = CandidateTypes[1].vector_begin(),
5285 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005286 Vec2 != Vec2End; ++Vec2) {
5287 QualType ParamTypes[2];
5288 ParamTypes[1] = *Vec2;
5289 // Add this built-in operator as a candidate (VQ is empty).
5290 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5291 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5292 /*IsAssigmentOperator=*/Op == OO_Equal);
5293
5294 // Add this built-in operator as a candidate (VQ is 'volatile').
5295 if (VisibleTypeConversionsQuals.hasVolatile()) {
5296 ParamTypes[0] = Context.getVolatileType(*Vec1);
5297 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5298 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5299 /*IsAssigmentOperator=*/Op == OO_Equal);
5300 }
5301 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005302 break;
5303
5304 case OO_PercentEqual:
5305 case OO_LessLessEqual:
5306 case OO_GreaterGreaterEqual:
5307 case OO_AmpEqual:
5308 case OO_CaretEqual:
5309 case OO_PipeEqual:
5310 // C++ [over.built]p22:
5311 //
5312 // For every triple (L, VQ, R), where L is an integral type, VQ
5313 // is either volatile or empty, and R is a promoted integral
5314 // type, there exist candidate operator functions of the form
5315 //
5316 // VQ L& operator%=(VQ L&, R);
5317 // VQ L& operator<<=(VQ L&, R);
5318 // VQ L& operator>>=(VQ L&, R);
5319 // VQ L& operator&=(VQ L&, R);
5320 // VQ L& operator^=(VQ L&, R);
5321 // VQ L& operator|=(VQ L&, R);
5322 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005323 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005324 Right < LastPromotedIntegralType; ++Right) {
5325 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005326 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005327
5328 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005329 ParamTypes[0] =
5330 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005331 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005332 if (VisibleTypeConversionsQuals.hasVolatile()) {
5333 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall988ffb72010-11-13 02:01:09 +00005334 ParamTypes[0] = Context.*ArithmeticTypes[Left];
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005335 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5336 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5337 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5338 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005339 }
5340 }
5341 break;
5342
Douglas Gregord08452f2008-11-19 15:42:04 +00005343 case OO_Exclaim: {
5344 // C++ [over.operator]p23:
5345 //
5346 // There also exist candidate operator functions of the form
5347 //
Mike Stump11289f42009-09-09 15:08:12 +00005348 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005349 // bool operator&&(bool, bool); [BELOW]
5350 // bool operator||(bool, bool); [BELOW]
5351 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005352 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5353 /*IsAssignmentOperator=*/false,
5354 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005355 break;
5356 }
5357
Douglas Gregora11693b2008-11-12 17:17:38 +00005358 case OO_AmpAmp:
5359 case OO_PipePipe: {
5360 // C++ [over.operator]p23:
5361 //
5362 // There also exist candidate operator functions of the form
5363 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005364 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005365 // bool operator&&(bool, bool);
5366 // bool operator||(bool, bool);
5367 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005368 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5369 /*IsAssignmentOperator=*/false,
5370 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005371 break;
5372 }
5373
5374 case OO_Subscript:
5375 // C++ [over.built]p13:
5376 //
5377 // For every cv-qualified or cv-unqualified object type T there
5378 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005379 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005380 // T* operator+(T*, ptrdiff_t); [ABOVE]
5381 // T& operator[](T*, ptrdiff_t);
5382 // T* operator-(T*, ptrdiff_t); [ABOVE]
5383 // T* operator+(ptrdiff_t, T*); [ABOVE]
5384 // T& operator[](ptrdiff_t, T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005385 for (BuiltinCandidateTypeSet::iterator
5386 Ptr = CandidateTypes[0].pointer_begin(),
5387 PtrEnd = CandidateTypes[0].pointer_end();
5388 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005389 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005390 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005391 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005392
5393 // T& operator[](T*, ptrdiff_t)
5394 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005395 }
5396
5397 for (BuiltinCandidateTypeSet::iterator
5398 Ptr = CandidateTypes[1].pointer_begin(),
5399 PtrEnd = CandidateTypes[1].pointer_end();
5400 Ptr != PtrEnd; ++Ptr) {
5401 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5402 QualType PointeeType = (*Ptr)->getPointeeType();
5403 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5404
5405 // T& operator[](ptrdiff_t, T*)
Douglas Gregora11693b2008-11-12 17:17:38 +00005406 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005407 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005408 break;
5409
5410 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005411 // C++ [over.built]p11:
5412 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5413 // C1 is the same type as C2 or is a derived class of C2, T is an object
5414 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5415 // there exist candidate operator functions of the form
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005416 //
5417 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5418 //
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005419 // where CV12 is the union of CV1 and CV2.
5420 {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005421 for (BuiltinCandidateTypeSet::iterator
5422 Ptr = CandidateTypes[0].pointer_begin(),
5423 PtrEnd = CandidateTypes[0].pointer_end();
5424 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005425 QualType C1Ty = (*Ptr);
5426 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005427 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005428 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5429 if (!isa<RecordType>(C1))
5430 continue;
5431 // heuristic to reduce number of builtin candidates in the set.
5432 // Add volatile/restrict version only if there are conversions to a
5433 // volatile/restrict type.
5434 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5435 continue;
5436 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5437 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005438 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005439 MemPtr = CandidateTypes[1].member_pointer_begin(),
5440 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005441 MemPtr != MemPtrEnd; ++MemPtr) {
5442 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5443 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005444 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005445 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5446 break;
5447 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5448 // build CV12 T&
5449 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005450 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5451 T.isVolatileQualified())
5452 continue;
5453 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5454 T.isRestrictQualified())
5455 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005456 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005457 QualType ResultTy = Context.getLValueReferenceType(T);
5458 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5459 }
5460 }
5461 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005462 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005463
5464 case OO_Conditional:
5465 // Note that we don't consider the first argument, since it has been
5466 // contextually converted to bool long ago. The candidates below are
5467 // therefore added as binary.
5468 //
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005469 // C++ [over.built]p25:
5470 // For every type T, where T is a pointer, pointer-to-member, or scoped
5471 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl1a99f442009-04-16 17:51:27 +00005472 //
5473 // T operator?(bool, T, T);
5474 //
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005475 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5476 for (BuiltinCandidateTypeSet::iterator
5477 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5478 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5479 Ptr != PtrEnd; ++Ptr) {
5480 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5481 continue;
5482
5483 QualType ParamTypes[2] = { *Ptr, *Ptr };
5484 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5485 }
5486
5487 for (BuiltinCandidateTypeSet::iterator
5488 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5489 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5490 MemPtr != MemPtrEnd; ++MemPtr) {
5491 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5492 continue;
5493
5494 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5495 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5496 }
5497
5498 if (getLangOptions().CPlusPlus0x) {
5499 for (BuiltinCandidateTypeSet::iterator
5500 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5501 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5502 Enum != EnumEnd; ++Enum) {
5503 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5504 continue;
5505
5506 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5507 continue;
5508
5509 QualType ParamTypes[2] = { *Enum, *Enum };
5510 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5511 }
5512 }
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005513 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005514 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005515 }
5516}
5517
Douglas Gregore254f902009-02-04 00:32:51 +00005518/// \brief Add function candidates found via argument-dependent lookup
5519/// to the set of overloading candidates.
5520///
5521/// This routine performs argument-dependent name lookup based on the
5522/// given function name (which may also be an operator name) and adds
5523/// all of the overload candidates found by ADL to the overload
5524/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005525void
Douglas Gregore254f902009-02-04 00:32:51 +00005526Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005527 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005528 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005529 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005530 OverloadCandidateSet& CandidateSet,
5531 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005532 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005533
John McCall91f61fc2010-01-26 06:04:06 +00005534 // FIXME: This approach for uniquing ADL results (and removing
5535 // redundant candidates from the set) relies on pointer-equality,
5536 // which means we need to key off the canonical decl. However,
5537 // always going back to the canonical decl might not get us the
5538 // right set of default arguments. What default arguments are
5539 // we supposed to consider on ADL candidates, anyway?
5540
Douglas Gregorcabea402009-09-22 15:41:20 +00005541 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005542 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005543
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005544 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005545 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5546 CandEnd = CandidateSet.end();
5547 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005548 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005549 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005550 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005551 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005552 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005553
5554 // For each of the ADL candidates we found, add it to the overload
5555 // set.
John McCall8fe68082010-01-26 07:16:45 +00005556 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005557 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005558 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005559 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005560 continue;
5561
John McCalla0296f72010-03-19 07:35:19 +00005562 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005563 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005564 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005565 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005566 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005567 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005568 }
Douglas Gregore254f902009-02-04 00:32:51 +00005569}
5570
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005571/// isBetterOverloadCandidate - Determines whether the first overload
5572/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005573bool
John McCall5c32be02010-08-24 20:38:10 +00005574isBetterOverloadCandidate(Sema &S,
5575 const OverloadCandidate& Cand1,
5576 const OverloadCandidate& Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005577 SourceLocation Loc,
5578 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005579 // Define viable functions to be better candidates than non-viable
5580 // functions.
5581 if (!Cand2.Viable)
5582 return Cand1.Viable;
5583 else if (!Cand1.Viable)
5584 return false;
5585
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005586 // C++ [over.match.best]p1:
5587 //
5588 // -- if F is a static member function, ICS1(F) is defined such
5589 // that ICS1(F) is neither better nor worse than ICS1(G) for
5590 // any function G, and, symmetrically, ICS1(G) is neither
5591 // better nor worse than ICS1(F).
5592 unsigned StartArg = 0;
5593 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5594 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005595
Douglas Gregord3cb3562009-07-07 23:38:56 +00005596 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005597 // A viable function F1 is defined to be a better function than another
5598 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005599 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005600 unsigned NumArgs = Cand1.Conversions.size();
5601 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5602 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005603 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005604 switch (CompareImplicitConversionSequences(S,
5605 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005606 Cand2.Conversions[ArgIdx])) {
5607 case ImplicitConversionSequence::Better:
5608 // Cand1 has a better conversion sequence.
5609 HasBetterConversion = true;
5610 break;
5611
5612 case ImplicitConversionSequence::Worse:
5613 // Cand1 can't be better than Cand2.
5614 return false;
5615
5616 case ImplicitConversionSequence::Indistinguishable:
5617 // Do nothing.
5618 break;
5619 }
5620 }
5621
Mike Stump11289f42009-09-09 15:08:12 +00005622 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005623 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005624 if (HasBetterConversion)
5625 return true;
5626
Mike Stump11289f42009-09-09 15:08:12 +00005627 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005628 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005629 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005630 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5631 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005632
5633 // -- F1 and F2 are function template specializations, and the function
5634 // template for F1 is more specialized than the template for F2
5635 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005636 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005637 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5638 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005639 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005640 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5641 Cand2.Function->getPrimaryTemplate(),
5642 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005643 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5644 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005645 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005646
Douglas Gregora1f013e2008-11-07 22:36:19 +00005647 // -- the context is an initialization by user-defined conversion
5648 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5649 // from the return type of F1 to the destination type (i.e.,
5650 // the type of the entity being initialized) is a better
5651 // conversion sequence than the standard conversion sequence
5652 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005653 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005654 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005655 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005656 switch (CompareStandardConversionSequences(S,
5657 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005658 Cand2.FinalConversion)) {
5659 case ImplicitConversionSequence::Better:
5660 // Cand1 has a better conversion sequence.
5661 return true;
5662
5663 case ImplicitConversionSequence::Worse:
5664 // Cand1 can't be better than Cand2.
5665 return false;
5666
5667 case ImplicitConversionSequence::Indistinguishable:
5668 // Do nothing
5669 break;
5670 }
5671 }
5672
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005673 return false;
5674}
5675
Mike Stump11289f42009-09-09 15:08:12 +00005676/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005677/// within an overload candidate set.
5678///
5679/// \param CandidateSet the set of candidate functions.
5680///
5681/// \param Loc the location of the function name (or operator symbol) for
5682/// which overload resolution occurs.
5683///
Mike Stump11289f42009-09-09 15:08:12 +00005684/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005685/// function, Best points to the candidate function found.
5686///
5687/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005688OverloadingResult
5689OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005690 iterator& Best,
5691 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005692 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005693 Best = end();
5694 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5695 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005696 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5697 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005698 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005699 }
5700
5701 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005702 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005703 return OR_No_Viable_Function;
5704
5705 // Make sure that this function is better than every other viable
5706 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005707 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005708 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005709 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005710 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5711 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005712 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005713 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005714 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005715 }
Mike Stump11289f42009-09-09 15:08:12 +00005716
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005717 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005718 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005719 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005720 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005721 return OR_Deleted;
5722
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005723 // C++ [basic.def.odr]p2:
5724 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005725 // when referred to from a potentially-evaluated expression. [Note: this
5726 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005727 // (clause 13), user-defined conversions (12.3.2), allocation function for
5728 // placement new (5.3.4), as well as non-default initialization (8.5).
5729 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005730 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00005731
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005732 return OR_Success;
5733}
5734
John McCall53262c92010-01-12 02:15:36 +00005735namespace {
5736
5737enum OverloadCandidateKind {
5738 oc_function,
5739 oc_method,
5740 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005741 oc_function_template,
5742 oc_method_template,
5743 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005744 oc_implicit_default_constructor,
5745 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005746 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005747};
5748
John McCalle1ac8d12010-01-13 00:25:19 +00005749OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5750 FunctionDecl *Fn,
5751 std::string &Description) {
5752 bool isTemplate = false;
5753
5754 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5755 isTemplate = true;
5756 Description = S.getTemplateArgumentBindingsText(
5757 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5758 }
John McCallfd0b2f82010-01-06 09:43:14 +00005759
5760 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005761 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005762 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005763
John McCall53262c92010-01-12 02:15:36 +00005764 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5765 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005766 }
5767
5768 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5769 // This actually gets spelled 'candidate function' for now, but
5770 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005771 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005772 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005773
Douglas Gregorec3bec02010-09-27 22:37:28 +00005774 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005775 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005776 return oc_implicit_copy_assignment;
5777 }
5778
John McCalle1ac8d12010-01-13 00:25:19 +00005779 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005780}
5781
5782} // end anonymous namespace
5783
5784// Notes the location of an overload candidate.
5785void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005786 std::string FnDesc;
5787 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5788 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5789 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005790}
5791
John McCall0d1da222010-01-12 00:44:57 +00005792/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5793/// "lead" diagnostic; it will be given two arguments, the source and
5794/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005795void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5796 Sema &S,
5797 SourceLocation CaretLoc,
5798 const PartialDiagnostic &PDiag) const {
5799 S.Diag(CaretLoc, PDiag)
5800 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005801 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005802 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5803 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005804 }
John McCall12f97bc2010-01-08 04:41:39 +00005805}
5806
John McCall0d1da222010-01-12 00:44:57 +00005807namespace {
5808
John McCall6a61b522010-01-13 09:16:55 +00005809void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5810 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5811 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005812 assert(Cand->Function && "for now, candidate must be a function");
5813 FunctionDecl *Fn = Cand->Function;
5814
5815 // There's a conversion slot for the object argument if this is a
5816 // non-constructor method. Note that 'I' corresponds the
5817 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005818 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005819 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005820 if (I == 0)
5821 isObjectArgument = true;
5822 else
5823 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005824 }
5825
John McCalle1ac8d12010-01-13 00:25:19 +00005826 std::string FnDesc;
5827 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5828
John McCall6a61b522010-01-13 09:16:55 +00005829 Expr *FromExpr = Conv.Bad.FromExpr;
5830 QualType FromTy = Conv.Bad.getFromType();
5831 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005832
John McCallfb7ad0f2010-02-02 02:42:52 +00005833 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005834 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005835 Expr *E = FromExpr->IgnoreParens();
5836 if (isa<UnaryOperator>(E))
5837 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005838 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005839
5840 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5841 << (unsigned) FnKind << FnDesc
5842 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5843 << ToTy << Name << I+1;
5844 return;
5845 }
5846
John McCall6d174642010-01-23 08:10:49 +00005847 // Do some hand-waving analysis to see if the non-viability is due
5848 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005849 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5850 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5851 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5852 CToTy = RT->getPointeeType();
5853 else {
5854 // TODO: detect and diagnose the full richness of const mismatches.
5855 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5856 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5857 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5858 }
5859
5860 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5861 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5862 // It is dumb that we have to do this here.
5863 while (isa<ArrayType>(CFromTy))
5864 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5865 while (isa<ArrayType>(CToTy))
5866 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5867
5868 Qualifiers FromQs = CFromTy.getQualifiers();
5869 Qualifiers ToQs = CToTy.getQualifiers();
5870
5871 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5872 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5873 << (unsigned) FnKind << FnDesc
5874 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5875 << FromTy
5876 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5877 << (unsigned) isObjectArgument << I+1;
5878 return;
5879 }
5880
5881 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5882 assert(CVR && "unexpected qualifiers mismatch");
5883
5884 if (isObjectArgument) {
5885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5886 << (unsigned) FnKind << FnDesc
5887 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5888 << FromTy << (CVR - 1);
5889 } else {
5890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5891 << (unsigned) FnKind << FnDesc
5892 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5893 << FromTy << (CVR - 1) << I+1;
5894 }
5895 return;
5896 }
5897
John McCall6d174642010-01-23 08:10:49 +00005898 // Diagnose references or pointers to incomplete types differently,
5899 // since it's far from impossible that the incompleteness triggered
5900 // the failure.
5901 QualType TempFromTy = FromTy.getNonReferenceType();
5902 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5903 TempFromTy = PTy->getPointeeType();
5904 if (TempFromTy->isIncompleteType()) {
5905 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5906 << (unsigned) FnKind << FnDesc
5907 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5908 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5909 return;
5910 }
5911
Douglas Gregor56f2e342010-06-30 23:01:39 +00005912 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005913 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005914 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5915 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5916 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5917 FromPtrTy->getPointeeType()) &&
5918 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5919 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5920 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5921 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005922 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005923 }
5924 } else if (const ObjCObjectPointerType *FromPtrTy
5925 = FromTy->getAs<ObjCObjectPointerType>()) {
5926 if (const ObjCObjectPointerType *ToPtrTy
5927 = ToTy->getAs<ObjCObjectPointerType>())
5928 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5929 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5930 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5931 FromPtrTy->getPointeeType()) &&
5932 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005933 BaseToDerivedConversion = 2;
5934 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5935 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5936 !FromTy->isIncompleteType() &&
5937 !ToRefTy->getPointeeType()->isIncompleteType() &&
5938 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5939 BaseToDerivedConversion = 3;
5940 }
5941
5942 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005943 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005944 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005945 << (unsigned) FnKind << FnDesc
5946 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005947 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005948 << FromTy << ToTy << I+1;
5949 return;
5950 }
5951
John McCall47000992010-01-14 03:28:57 +00005952 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005953 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5954 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005955 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005956 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005957}
5958
5959void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5960 unsigned NumFormalArgs) {
5961 // TODO: treat calls to a missing default constructor as a special case
5962
5963 FunctionDecl *Fn = Cand->Function;
5964 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5965
5966 unsigned MinParams = Fn->getMinRequiredArguments();
5967
5968 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005969 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005970 unsigned mode, modeCount;
5971 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005972 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5973 (Cand->FailureKind == ovl_fail_bad_deduction &&
5974 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005975 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5976 mode = 0; // "at least"
5977 else
5978 mode = 2; // "exactly"
5979 modeCount = MinParams;
5980 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005981 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5982 (Cand->FailureKind == ovl_fail_bad_deduction &&
5983 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005984 if (MinParams != FnTy->getNumArgs())
5985 mode = 1; // "at most"
5986 else
5987 mode = 2; // "exactly"
5988 modeCount = FnTy->getNumArgs();
5989 }
5990
5991 std::string Description;
5992 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5993
5994 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005995 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5996 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005997}
5998
John McCall8b9ed552010-02-01 18:53:26 +00005999/// Diagnose a failed template-argument deduction.
6000void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6001 Expr **Args, unsigned NumArgs) {
6002 FunctionDecl *Fn = Cand->Function; // pattern
6003
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006004 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006005 NamedDecl *ParamD;
6006 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6007 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6008 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006009 switch (Cand->DeductionFailure.Result) {
6010 case Sema::TDK_Success:
6011 llvm_unreachable("TDK_success while diagnosing bad deduction");
6012
6013 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006014 assert(ParamD && "no parameter found for incomplete deduction result");
6015 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6016 << ParamD->getDeclName();
6017 return;
6018 }
6019
John McCall42d7d192010-08-05 09:05:08 +00006020 case Sema::TDK_Underqualified: {
6021 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6022 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6023
6024 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6025
6026 // Param will have been canonicalized, but it should just be a
6027 // qualified version of ParamD, so move the qualifiers to that.
6028 QualifierCollector Qs(S.Context);
6029 Qs.strip(Param);
6030 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
6031 assert(S.Context.hasSameType(Param, NonCanonParam));
6032
6033 // Arg has also been canonicalized, but there's nothing we can do
6034 // about that. It also doesn't matter as much, because it won't
6035 // have any template parameters in it (because deduction isn't
6036 // done on dependent types).
6037 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6038
6039 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6040 << ParamD->getDeclName() << Arg << NonCanonParam;
6041 return;
6042 }
6043
6044 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006045 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006046 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006047 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006048 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006049 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006050 which = 1;
6051 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006052 which = 2;
6053 }
6054
6055 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6056 << which << ParamD->getDeclName()
6057 << *Cand->DeductionFailure.getFirstArg()
6058 << *Cand->DeductionFailure.getSecondArg();
6059 return;
6060 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006061
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006062 case Sema::TDK_InvalidExplicitArguments:
6063 assert(ParamD && "no parameter found for invalid explicit arguments");
6064 if (ParamD->getDeclName())
6065 S.Diag(Fn->getLocation(),
6066 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6067 << ParamD->getDeclName();
6068 else {
6069 int index = 0;
6070 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6071 index = TTP->getIndex();
6072 else if (NonTypeTemplateParmDecl *NTTP
6073 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6074 index = NTTP->getIndex();
6075 else
6076 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6077 S.Diag(Fn->getLocation(),
6078 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6079 << (index + 1);
6080 }
6081 return;
6082
Douglas Gregor02eb4832010-05-08 18:13:28 +00006083 case Sema::TDK_TooManyArguments:
6084 case Sema::TDK_TooFewArguments:
6085 DiagnoseArityMismatch(S, Cand, NumArgs);
6086 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006087
6088 case Sema::TDK_InstantiationDepth:
6089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6090 return;
6091
6092 case Sema::TDK_SubstitutionFailure: {
6093 std::string ArgString;
6094 if (TemplateArgumentList *Args
6095 = Cand->DeductionFailure.getTemplateArgumentList())
6096 ArgString = S.getTemplateArgumentBindingsText(
6097 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6098 *Args);
6099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6100 << ArgString;
6101 return;
6102 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006103
John McCall8b9ed552010-02-01 18:53:26 +00006104 // TODO: diagnose these individually, then kill off
6105 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006106 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006107 case Sema::TDK_FailedOverloadResolution:
6108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6109 return;
6110 }
6111}
6112
6113/// Generates a 'note' diagnostic for an overload candidate. We've
6114/// already generated a primary error at the call site.
6115///
6116/// It really does need to be a single diagnostic with its caret
6117/// pointed at the candidate declaration. Yes, this creates some
6118/// major challenges of technical writing. Yes, this makes pointing
6119/// out problems with specific arguments quite awkward. It's still
6120/// better than generating twenty screens of text for every failed
6121/// overload.
6122///
6123/// It would be great to be able to express per-candidate problems
6124/// more richly for those diagnostic clients that cared, but we'd
6125/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006126void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6127 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006128 FunctionDecl *Fn = Cand->Function;
6129
John McCall12f97bc2010-01-08 04:41:39 +00006130 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006131 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006132 std::string FnDesc;
6133 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006134
6135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006136 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006137 return;
John McCall12f97bc2010-01-08 04:41:39 +00006138 }
6139
John McCalle1ac8d12010-01-13 00:25:19 +00006140 // We don't really have anything else to say about viable candidates.
6141 if (Cand->Viable) {
6142 S.NoteOverloadCandidate(Fn);
6143 return;
6144 }
John McCall0d1da222010-01-12 00:44:57 +00006145
John McCall6a61b522010-01-13 09:16:55 +00006146 switch (Cand->FailureKind) {
6147 case ovl_fail_too_many_arguments:
6148 case ovl_fail_too_few_arguments:
6149 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006150
John McCall6a61b522010-01-13 09:16:55 +00006151 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006152 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6153
John McCallfe796dd2010-01-23 05:17:32 +00006154 case ovl_fail_trivial_conversion:
6155 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006156 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006157 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006158
John McCall65eb8792010-02-25 01:37:24 +00006159 case ovl_fail_bad_conversion: {
6160 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6161 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006162 if (Cand->Conversions[I].isBad())
6163 return DiagnoseBadConversion(S, Cand, I);
6164
6165 // FIXME: this currently happens when we're called from SemaInit
6166 // when user-conversion overload fails. Figure out how to handle
6167 // those conditions and diagnose them well.
6168 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006169 }
John McCall65eb8792010-02-25 01:37:24 +00006170 }
John McCalld3224162010-01-08 00:58:21 +00006171}
6172
6173void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6174 // Desugar the type of the surrogate down to a function type,
6175 // retaining as many typedefs as possible while still showing
6176 // the function type (and, therefore, its parameter types).
6177 QualType FnType = Cand->Surrogate->getConversionType();
6178 bool isLValueReference = false;
6179 bool isRValueReference = false;
6180 bool isPointer = false;
6181 if (const LValueReferenceType *FnTypeRef =
6182 FnType->getAs<LValueReferenceType>()) {
6183 FnType = FnTypeRef->getPointeeType();
6184 isLValueReference = true;
6185 } else if (const RValueReferenceType *FnTypeRef =
6186 FnType->getAs<RValueReferenceType>()) {
6187 FnType = FnTypeRef->getPointeeType();
6188 isRValueReference = true;
6189 }
6190 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6191 FnType = FnTypePtr->getPointeeType();
6192 isPointer = true;
6193 }
6194 // Desugar down to a function type.
6195 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6196 // Reconstruct the pointer/reference as appropriate.
6197 if (isPointer) FnType = S.Context.getPointerType(FnType);
6198 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6199 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6200
6201 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6202 << FnType;
6203}
6204
6205void NoteBuiltinOperatorCandidate(Sema &S,
6206 const char *Opc,
6207 SourceLocation OpLoc,
6208 OverloadCandidate *Cand) {
6209 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6210 std::string TypeStr("operator");
6211 TypeStr += Opc;
6212 TypeStr += "(";
6213 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6214 if (Cand->Conversions.size() == 1) {
6215 TypeStr += ")";
6216 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6217 } else {
6218 TypeStr += ", ";
6219 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6220 TypeStr += ")";
6221 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6222 }
6223}
6224
6225void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6226 OverloadCandidate *Cand) {
6227 unsigned NoOperands = Cand->Conversions.size();
6228 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6229 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006230 if (ICS.isBad()) break; // all meaningless after first invalid
6231 if (!ICS.isAmbiguous()) continue;
6232
John McCall5c32be02010-08-24 20:38:10 +00006233 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006234 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006235 }
6236}
6237
John McCall3712d9e2010-01-15 23:32:50 +00006238SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6239 if (Cand->Function)
6240 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006241 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006242 return Cand->Surrogate->getLocation();
6243 return SourceLocation();
6244}
6245
John McCallad2587a2010-01-12 00:48:53 +00006246struct CompareOverloadCandidatesForDisplay {
6247 Sema &S;
6248 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006249
6250 bool operator()(const OverloadCandidate *L,
6251 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006252 // Fast-path this check.
6253 if (L == R) return false;
6254
John McCall12f97bc2010-01-08 04:41:39 +00006255 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006256 if (L->Viable) {
6257 if (!R->Viable) return true;
6258
6259 // TODO: introduce a tri-valued comparison for overload
6260 // candidates. Would be more worthwhile if we had a sort
6261 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006262 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6263 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006264 } else if (R->Viable)
6265 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006266
John McCall3712d9e2010-01-15 23:32:50 +00006267 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006268
John McCall3712d9e2010-01-15 23:32:50 +00006269 // Criteria by which we can sort non-viable candidates:
6270 if (!L->Viable) {
6271 // 1. Arity mismatches come after other candidates.
6272 if (L->FailureKind == ovl_fail_too_many_arguments ||
6273 L->FailureKind == ovl_fail_too_few_arguments)
6274 return false;
6275 if (R->FailureKind == ovl_fail_too_many_arguments ||
6276 R->FailureKind == ovl_fail_too_few_arguments)
6277 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006278
John McCallfe796dd2010-01-23 05:17:32 +00006279 // 2. Bad conversions come first and are ordered by the number
6280 // of bad conversions and quality of good conversions.
6281 if (L->FailureKind == ovl_fail_bad_conversion) {
6282 if (R->FailureKind != ovl_fail_bad_conversion)
6283 return true;
6284
6285 // If there's any ordering between the defined conversions...
6286 // FIXME: this might not be transitive.
6287 assert(L->Conversions.size() == R->Conversions.size());
6288
6289 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006290 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6291 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006292 switch (CompareImplicitConversionSequences(S,
6293 L->Conversions[I],
6294 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006295 case ImplicitConversionSequence::Better:
6296 leftBetter++;
6297 break;
6298
6299 case ImplicitConversionSequence::Worse:
6300 leftBetter--;
6301 break;
6302
6303 case ImplicitConversionSequence::Indistinguishable:
6304 break;
6305 }
6306 }
6307 if (leftBetter > 0) return true;
6308 if (leftBetter < 0) return false;
6309
6310 } else if (R->FailureKind == ovl_fail_bad_conversion)
6311 return false;
6312
John McCall3712d9e2010-01-15 23:32:50 +00006313 // TODO: others?
6314 }
6315
6316 // Sort everything else by location.
6317 SourceLocation LLoc = GetLocationForCandidate(L);
6318 SourceLocation RLoc = GetLocationForCandidate(R);
6319
6320 // Put candidates without locations (e.g. builtins) at the end.
6321 if (LLoc.isInvalid()) return false;
6322 if (RLoc.isInvalid()) return true;
6323
6324 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006325 }
6326};
6327
John McCallfe796dd2010-01-23 05:17:32 +00006328/// CompleteNonViableCandidate - Normally, overload resolution only
6329/// computes up to the first
6330void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6331 Expr **Args, unsigned NumArgs) {
6332 assert(!Cand->Viable);
6333
6334 // Don't do anything on failures other than bad conversion.
6335 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6336
6337 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006338 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006339 unsigned ConvCount = Cand->Conversions.size();
6340 while (true) {
6341 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6342 ConvIdx++;
6343 if (Cand->Conversions[ConvIdx - 1].isBad())
6344 break;
6345 }
6346
6347 if (ConvIdx == ConvCount)
6348 return;
6349
John McCall65eb8792010-02-25 01:37:24 +00006350 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6351 "remaining conversion is initialized?");
6352
Douglas Gregoradc7a702010-04-16 17:45:54 +00006353 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006354 // operation somehow.
6355 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006356
6357 const FunctionProtoType* Proto;
6358 unsigned ArgIdx = ConvIdx;
6359
6360 if (Cand->IsSurrogate) {
6361 QualType ConvType
6362 = Cand->Surrogate->getConversionType().getNonReferenceType();
6363 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6364 ConvType = ConvPtrType->getPointeeType();
6365 Proto = ConvType->getAs<FunctionProtoType>();
6366 ArgIdx--;
6367 } else if (Cand->Function) {
6368 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6369 if (isa<CXXMethodDecl>(Cand->Function) &&
6370 !isa<CXXConstructorDecl>(Cand->Function))
6371 ArgIdx--;
6372 } else {
6373 // Builtin binary operator with a bad first conversion.
6374 assert(ConvCount <= 3);
6375 for (; ConvIdx != ConvCount; ++ConvIdx)
6376 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006377 = TryCopyInitialization(S, Args[ConvIdx],
6378 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6379 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006380 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006381 return;
6382 }
6383
6384 // Fill in the rest of the conversions.
6385 unsigned NumArgsInProto = Proto->getNumArgs();
6386 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6387 if (ArgIdx < NumArgsInProto)
6388 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006389 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6390 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006391 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006392 else
6393 Cand->Conversions[ConvIdx].setEllipsis();
6394 }
6395}
6396
John McCalld3224162010-01-08 00:58:21 +00006397} // end anonymous namespace
6398
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006399/// PrintOverloadCandidates - When overload resolution fails, prints
6400/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006401/// set.
John McCall5c32be02010-08-24 20:38:10 +00006402void OverloadCandidateSet::NoteCandidates(Sema &S,
6403 OverloadCandidateDisplayKind OCD,
6404 Expr **Args, unsigned NumArgs,
6405 const char *Opc,
6406 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006407 // Sort the candidates by viability and position. Sorting directly would
6408 // be prohibitive, so we make a set of pointers and sort those.
6409 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006410 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6411 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006412 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006413 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006414 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006415 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006416 if (Cand->Function || Cand->IsSurrogate)
6417 Cands.push_back(Cand);
6418 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6419 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006420 }
6421 }
6422
John McCallad2587a2010-01-12 00:48:53 +00006423 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006424 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006425
John McCall0d1da222010-01-12 00:44:57 +00006426 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006427
John McCall12f97bc2010-01-08 04:41:39 +00006428 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006429 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006430 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006431 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6432 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006433
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006434 // Set an arbitrary limit on the number of candidate functions we'll spam
6435 // the user with. FIXME: This limit should depend on details of the
6436 // candidate list.
6437 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6438 break;
6439 }
6440 ++CandsShown;
6441
John McCalld3224162010-01-08 00:58:21 +00006442 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006443 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006444 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006445 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006446 else {
6447 assert(Cand->Viable &&
6448 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006449 // Generally we only see ambiguities including viable builtin
6450 // operators if overload resolution got screwed up by an
6451 // ambiguous user-defined conversion.
6452 //
6453 // FIXME: It's quite possible for different conversions to see
6454 // different ambiguities, though.
6455 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006456 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006457 ReportedAmbiguousConversions = true;
6458 }
John McCalld3224162010-01-08 00:58:21 +00006459
John McCall0d1da222010-01-12 00:44:57 +00006460 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006461 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006462 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006463 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006464
6465 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006466 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006467}
6468
John McCalla0296f72010-03-19 07:35:19 +00006469static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006470 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006471 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006472
John McCalla0296f72010-03-19 07:35:19 +00006473 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006474}
6475
Douglas Gregorcd695e52008-11-10 20:40:00 +00006476/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6477/// an overloaded function (C++ [over.over]), where @p From is an
6478/// expression with overloaded function type and @p ToType is the type
6479/// we're trying to resolve to. For example:
6480///
6481/// @code
6482/// int f(double);
6483/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006484///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006485/// int (*pfd)(double) = f; // selects f(double)
6486/// @endcode
6487///
6488/// This routine returns the resulting FunctionDecl if it could be
6489/// resolved, and NULL otherwise. When @p Complain is true, this
6490/// routine will emit diagnostics if there is an error.
6491FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006492Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006493 bool Complain,
6494 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006495 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006496 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006497 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006498 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006499 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006500 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006501 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006502 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006503 FunctionType = MemTypePtr->getPointeeType();
6504 IsMember = true;
6505 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006506
Douglas Gregorcd695e52008-11-10 20:40:00 +00006507 // C++ [over.over]p1:
6508 // [...] [Note: any redundant set of parentheses surrounding the
6509 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006510 // C++ [over.over]p1:
6511 // [...] The overloaded function name can be preceded by the &
6512 // operator.
John McCall7d460512010-08-24 23:26:21 +00006513 // However, remember whether the expression has member-pointer form:
6514 // C++ [expr.unary.op]p4:
6515 // A pointer to member is only formed when an explicit & is used
6516 // and its operand is a qualified-id not enclosed in
6517 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006518 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6519 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006520
Douglas Gregor064fdb22010-04-14 23:11:21 +00006521 // We expect a pointer or reference to function, or a function pointer.
6522 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6523 if (!FunctionType->isFunctionType()) {
6524 if (Complain)
6525 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6526 << OvlExpr->getName() << ToType;
6527
6528 return 0;
6529 }
6530
John McCall24d18942010-08-24 22:52:39 +00006531 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006532 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006533 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006534 if (!Complain) return 0;
6535
6536 // TODO: Should we condition this on whether any functions might
6537 // have matched, or is it more appropriate to do that in callers?
6538 // TODO: a fixit wouldn't hurt.
6539 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6540 << ToType << OvlExpr->getSourceRange();
6541 return 0;
6542 }
6543
6544 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6545 if (OvlExpr->hasExplicitTemplateArgs()) {
6546 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6547 ExplicitTemplateArgs = &ETABuffer;
6548 }
6549
Douglas Gregor064fdb22010-04-14 23:11:21 +00006550 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006551
Douglas Gregorcd695e52008-11-10 20:40:00 +00006552 // Look through all of the overloaded functions, searching for one
6553 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006554 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006555 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006556
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006557 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006558 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6559 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006560 // Look through any using declarations to find the underlying function.
6561 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6562
Douglas Gregorcd695e52008-11-10 20:40:00 +00006563 // C++ [over.over]p3:
6564 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006565 // targets of type "pointer-to-function" or "reference-to-function."
6566 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006567 // type "pointer-to-member-function."
6568 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006569
Mike Stump11289f42009-09-09 15:08:12 +00006570 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006571 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006572 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006573 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006574 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006575 // static when converting to member pointer.
6576 if (Method->isStatic() == IsMember)
6577 continue;
6578 } else if (IsMember)
6579 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006580
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006581 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006582 // If the name is a function template, template argument deduction is
6583 // done (14.8.2.2), and if the argument deduction succeeds, the
6584 // resulting template argument list is used to generate a single
6585 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006586 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006587 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006588 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006589 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006590 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006591 FunctionType, Specialization, Info)) {
6592 // FIXME: make a note of the failed deduction for diagnostics.
6593 (void)Result;
6594 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006595 // Template argument deduction ensures that we have an exact match.
6596 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006597 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006598 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006599 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006600 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006601 }
John McCalld14a8642009-11-21 08:51:07 +00006602
6603 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006604 }
Mike Stump11289f42009-09-09 15:08:12 +00006605
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006606 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006607 // Skip non-static functions when converting to pointer, and static
6608 // when converting to member pointer.
6609 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006610 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006611
6612 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006613 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006614 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006615 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006616 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006617
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006618 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006619 QualType ResultTy;
6620 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6621 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6622 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006623 Matches.push_back(std::make_pair(I.getPair(),
6624 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006625 FoundNonTemplateFunction = true;
6626 }
Mike Stump11289f42009-09-09 15:08:12 +00006627 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006628 }
6629
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006630 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006631 if (Matches.empty()) {
6632 if (Complain) {
6633 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6634 << OvlExpr->getName() << FunctionType;
6635 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6636 E = OvlExpr->decls_end();
6637 I != E; ++I)
6638 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6639 NoteOverloadCandidate(F);
6640 }
6641
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006642 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006643 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006644 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006645 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006646 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006647 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006648 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006649 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006650 return Result;
6651 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006652
6653 // C++ [over.over]p4:
6654 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006655 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006656 // [...] and any given function template specialization F1 is
6657 // eliminated if the set contains a second function template
6658 // specialization whose function template is more specialized
6659 // than the function template of F1 according to the partial
6660 // ordering rules of 14.5.5.2.
6661
6662 // The algorithm specified above is quadratic. We instead use a
6663 // two-pass algorithm (similar to the one used to identify the
6664 // best viable function in an overload set) that identifies the
6665 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006666
6667 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6668 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6669 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006670
6671 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006672 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006673 TPOC_Other, From->getLocStart(),
6674 PDiag(),
6675 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006676 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006677 PDiag(diag::note_ovl_candidate)
6678 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006679 if (Result == MatchesCopy.end())
6680 return 0;
6681
John McCall58cc69d2010-01-27 01:50:18 +00006682 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006683 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006684 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006685 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006686 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006687 }
Mike Stump11289f42009-09-09 15:08:12 +00006688
Douglas Gregorfae1d712009-09-26 03:56:17 +00006689 // [...] any function template specializations in the set are
6690 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006691 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006692 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006693 ++I;
6694 else {
John McCalla0296f72010-03-19 07:35:19 +00006695 Matches[I] = Matches[--N];
6696 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006697 }
6698 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006699
Mike Stump11289f42009-09-09 15:08:12 +00006700 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006701 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006702 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006703 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006704 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006705 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006706 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6707 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006708 }
Mike Stump11289f42009-09-09 15:08:12 +00006709
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006710 // FIXME: We should probably return the same thing that BestViableFunction
6711 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00006712 if (Complain) {
6713 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6714 << Matches[0].second->getDeclName();
6715 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6716 NoteOverloadCandidate(Matches[I].second);
6717 }
6718
Douglas Gregorcd695e52008-11-10 20:40:00 +00006719 return 0;
6720}
6721
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006722/// \brief Given an expression that refers to an overloaded function, try to
6723/// resolve that overloaded function expression down to a single function.
6724///
6725/// This routine can only resolve template-ids that refer to a single function
6726/// template, where that template-id refers to a single template whose template
6727/// arguments are either provided by the template-id or have defaults,
6728/// as described in C++0x [temp.arg.explicit]p3.
6729FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6730 // C++ [over.over]p1:
6731 // [...] [Note: any redundant set of parentheses surrounding the
6732 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006733 // C++ [over.over]p1:
6734 // [...] The overloaded function name can be preceded by the &
6735 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006736
6737 if (From->getType() != Context.OverloadTy)
6738 return 0;
6739
John McCall8d08b9b2010-08-27 09:08:28 +00006740 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006741
6742 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006743 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006744 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006745
6746 TemplateArgumentListInfo ExplicitTemplateArgs;
6747 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006748
6749 // Look through all of the overloaded functions, searching for one
6750 // whose type matches exactly.
6751 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006752 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6753 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006754 // C++0x [temp.arg.explicit]p3:
6755 // [...] In contexts where deduction is done and fails, or in contexts
6756 // where deduction is not done, if a template argument list is
6757 // specified and it, along with any default template arguments,
6758 // identifies a single function template specialization, then the
6759 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006760 FunctionTemplateDecl *FunctionTemplate
6761 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006762
6763 // C++ [over.over]p2:
6764 // If the name is a function template, template argument deduction is
6765 // done (14.8.2.2), and if the argument deduction succeeds, the
6766 // resulting template argument list is used to generate a single
6767 // function template specialization, which is added to the set of
6768 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006769 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006770 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006771 if (TemplateDeductionResult Result
6772 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6773 Specialization, Info)) {
6774 // FIXME: make a note of the failed deduction for diagnostics.
6775 (void)Result;
6776 continue;
6777 }
6778
6779 // Multiple matches; we can't resolve to a single declaration.
6780 if (Matched)
6781 return 0;
6782
6783 Matched = Specialization;
6784 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006785
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006786 return Matched;
6787}
6788
Douglas Gregorcabea402009-09-22 15:41:20 +00006789/// \brief Add a single candidate to the overload set.
6790static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006791 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006792 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006793 Expr **Args, unsigned NumArgs,
6794 OverloadCandidateSet &CandidateSet,
6795 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006796 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006797 if (isa<UsingShadowDecl>(Callee))
6798 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6799
Douglas Gregorcabea402009-09-22 15:41:20 +00006800 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006801 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006802 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006803 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006804 return;
John McCalld14a8642009-11-21 08:51:07 +00006805 }
6806
6807 if (FunctionTemplateDecl *FuncTemplate
6808 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006809 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6810 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006811 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006812 return;
6813 }
6814
6815 assert(false && "unhandled case in overloaded call candidate");
6816
6817 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006818}
6819
6820/// \brief Add the overload candidates named by callee and/or found by argument
6821/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006822void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006823 Expr **Args, unsigned NumArgs,
6824 OverloadCandidateSet &CandidateSet,
6825 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006826
6827#ifndef NDEBUG
6828 // Verify that ArgumentDependentLookup is consistent with the rules
6829 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006830 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006831 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6832 // and let Y be the lookup set produced by argument dependent
6833 // lookup (defined as follows). If X contains
6834 //
6835 // -- a declaration of a class member, or
6836 //
6837 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006838 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006839 //
6840 // -- a declaration that is neither a function or a function
6841 // template
6842 //
6843 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006844
John McCall57500772009-12-16 12:17:52 +00006845 if (ULE->requiresADL()) {
6846 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6847 E = ULE->decls_end(); I != E; ++I) {
6848 assert(!(*I)->getDeclContext()->isRecord());
6849 assert(isa<UsingShadowDecl>(*I) ||
6850 !(*I)->getDeclContext()->isFunctionOrMethod());
6851 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006852 }
6853 }
6854#endif
6855
John McCall57500772009-12-16 12:17:52 +00006856 // It would be nice to avoid this copy.
6857 TemplateArgumentListInfo TABuffer;
6858 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6859 if (ULE->hasExplicitTemplateArgs()) {
6860 ULE->copyTemplateArgumentsInto(TABuffer);
6861 ExplicitTemplateArgs = &TABuffer;
6862 }
6863
6864 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6865 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006866 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006867 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006868 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006869
John McCall57500772009-12-16 12:17:52 +00006870 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006871 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6872 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006873 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006874 CandidateSet,
6875 PartialOverloading);
6876}
John McCalld681c392009-12-16 08:11:27 +00006877
6878/// Attempts to recover from a call where no functions were found.
6879///
6880/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006881static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006882BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006883 UnresolvedLookupExpr *ULE,
6884 SourceLocation LParenLoc,
6885 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006886 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006887
6888 CXXScopeSpec SS;
6889 if (ULE->getQualifier()) {
6890 SS.setScopeRep(ULE->getQualifier());
6891 SS.setRange(ULE->getQualifierRange());
6892 }
6893
John McCall57500772009-12-16 12:17:52 +00006894 TemplateArgumentListInfo TABuffer;
6895 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6896 if (ULE->hasExplicitTemplateArgs()) {
6897 ULE->copyTemplateArgumentsInto(TABuffer);
6898 ExplicitTemplateArgs = &TABuffer;
6899 }
6900
John McCalld681c392009-12-16 08:11:27 +00006901 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6902 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006903 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00006904 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00006905
John McCall57500772009-12-16 12:17:52 +00006906 assert(!R.empty() && "lookup results empty despite recovery");
6907
6908 // Build an implicit member call if appropriate. Just drop the
6909 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00006910 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00006911 if ((*R.begin())->isCXXClassMember())
6912 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6913 else if (ExplicitTemplateArgs)
6914 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6915 else
6916 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6917
6918 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006919 return ExprError();
John McCall57500772009-12-16 12:17:52 +00006920
6921 // This shouldn't cause an infinite loop because we're giving it
6922 // an expression with non-empty lookup results, which should never
6923 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006924 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006925 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006926}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006927
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006928/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006929/// (which eventually refers to the declaration Func) and the call
6930/// arguments Args/NumArgs, attempt to resolve the function call down
6931/// to a specific function. If overload resolution succeeds, returns
6932/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006933/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006934/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006935ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006936Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006937 SourceLocation LParenLoc,
6938 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006939 SourceLocation RParenLoc) {
6940#ifndef NDEBUG
6941 if (ULE->requiresADL()) {
6942 // To do ADL, we must have found an unqualified name.
6943 assert(!ULE->getQualifier() && "qualified name with ADL");
6944
6945 // We don't perform ADL for implicit declarations of builtins.
6946 // Verify that this was correctly set up.
6947 FunctionDecl *F;
6948 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6949 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6950 F->getBuiltinID() && F->isImplicit())
6951 assert(0 && "performing ADL for builtin");
6952
6953 // We don't perform ADL in C.
6954 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6955 }
6956#endif
6957
John McCallbc077cf2010-02-08 23:07:23 +00006958 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006959
John McCall57500772009-12-16 12:17:52 +00006960 // Add the functions denoted by the callee to the set of candidate
6961 // functions, including those from argument-dependent lookup.
6962 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006963
6964 // If we found nothing, try to recover.
6965 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6966 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006967 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006968 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006969 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006970
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006971 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006972 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006973 case OR_Success: {
6974 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006975 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor7731d3f2010-10-13 00:27:52 +00006976 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006977 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006978 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6979 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006980
6981 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006982 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006983 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006984 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006985 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006986 break;
6987
6988 case OR_Ambiguous:
6989 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006990 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006991 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006992 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006993
6994 case OR_Deleted:
6995 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6996 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006997 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006998 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006999 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007000 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007001 }
7002
Douglas Gregorb412e172010-07-25 18:17:45 +00007003 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007004 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007005}
7006
John McCall4c4c1df2010-01-26 03:27:55 +00007007static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007008 return Functions.size() > 1 ||
7009 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7010}
7011
Douglas Gregor084d8552009-03-13 23:49:33 +00007012/// \brief Create a unary operation that may resolve to an overloaded
7013/// operator.
7014///
7015/// \param OpLoc The location of the operator itself (e.g., '*').
7016///
7017/// \param OpcIn The UnaryOperator::Opcode that describes this
7018/// operator.
7019///
7020/// \param Functions The set of non-member functions that will be
7021/// considered by overload resolution. The caller needs to build this
7022/// set based on the context using, e.g.,
7023/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7024/// set should not contain any member functions; those will be added
7025/// by CreateOverloadedUnaryOp().
7026///
7027/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007028ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007029Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7030 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007031 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007032 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007033
7034 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7035 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7036 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007037 // TODO: provide better source location info.
7038 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007039
7040 Expr *Args[2] = { Input, 0 };
7041 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007042
Douglas Gregor084d8552009-03-13 23:49:33 +00007043 // For post-increment and post-decrement, add the implicit '0' as
7044 // the second argument, so that we know this is a post-increment or
7045 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007046 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007047 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007048 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7049 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007050 NumArgs = 2;
7051 }
7052
7053 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007054 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007055 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007056 Opc,
7057 Context.DependentTy,
7058 OpLoc));
7059
John McCall58cc69d2010-01-27 01:50:18 +00007060 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007061 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007062 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007063 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007064 /*ADL*/ true, IsOverloaded(Fns),
7065 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007066 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7067 &Args[0], NumArgs,
7068 Context.DependentTy,
7069 OpLoc));
7070 }
7071
7072 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007073 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007074
7075 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007076 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007077
7078 // Add operator candidates that are member functions.
7079 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7080
John McCall4c4c1df2010-01-26 03:27:55 +00007081 // Add candidates from ADL.
7082 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007083 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007084 /*ExplicitTemplateArgs*/ 0,
7085 CandidateSet);
7086
Douglas Gregor084d8552009-03-13 23:49:33 +00007087 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007088 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007089
7090 // Perform overload resolution.
7091 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007092 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007093 case OR_Success: {
7094 // We found a built-in operator or an overloaded operator.
7095 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007096
Douglas Gregor084d8552009-03-13 23:49:33 +00007097 if (FnDecl) {
7098 // We matched an overloaded operator. Build a call to that
7099 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007100
Douglas Gregor084d8552009-03-13 23:49:33 +00007101 // Convert the arguments.
7102 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007103 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007104
John McCall16df1e52010-03-30 21:47:33 +00007105 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7106 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007107 return ExprError();
7108 } else {
7109 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007110 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007111 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007112 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007113 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007114 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007115 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007116 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007117 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007118 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007119 }
7120
John McCall4fa0d5f2010-05-06 18:15:07 +00007121 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7122
Douglas Gregor084d8552009-03-13 23:49:33 +00007123 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00007124 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00007125
Douglas Gregor084d8552009-03-13 23:49:33 +00007126 // Build the actual expression node.
7127 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7128 SourceLocation());
7129 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00007130
Eli Friedman030eee42009-11-18 03:58:17 +00007131 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007132 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007133 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallb268a282010-08-23 23:25:46 +00007134 Args, NumArgs, ResultTy, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007135
John McCallb268a282010-08-23 23:25:46 +00007136 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007137 FnDecl))
7138 return ExprError();
7139
John McCallb268a282010-08-23 23:25:46 +00007140 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007141 } else {
7142 // We matched a built-in operator. Convert the arguments, then
7143 // break out so that we will build the appropriate built-in
7144 // operator node.
7145 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007146 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007147 return ExprError();
7148
7149 break;
7150 }
7151 }
7152
7153 case OR_No_Viable_Function:
7154 // No viable function; fall through to handling this as a
7155 // built-in operator, which will produce an error message for us.
7156 break;
7157
7158 case OR_Ambiguous:
7159 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7160 << UnaryOperator::getOpcodeStr(Opc)
7161 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007162 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7163 Args, NumArgs,
7164 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007165 return ExprError();
7166
7167 case OR_Deleted:
7168 Diag(OpLoc, diag::err_ovl_deleted_oper)
7169 << Best->Function->isDeleted()
7170 << UnaryOperator::getOpcodeStr(Opc)
7171 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007172 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007173 return ExprError();
7174 }
7175
7176 // Either we found no viable overloaded operator or we matched a
7177 // built-in operator. In either case, fall through to trying to
7178 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007179 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007180}
7181
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007182/// \brief Create a binary operation that may resolve to an overloaded
7183/// operator.
7184///
7185/// \param OpLoc The location of the operator itself (e.g., '+').
7186///
7187/// \param OpcIn The BinaryOperator::Opcode that describes this
7188/// operator.
7189///
7190/// \param Functions The set of non-member functions that will be
7191/// considered by overload resolution. The caller needs to build this
7192/// set based on the context using, e.g.,
7193/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7194/// set should not contain any member functions; those will be added
7195/// by CreateOverloadedBinOp().
7196///
7197/// \param LHS Left-hand argument.
7198/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007199ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007200Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007201 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007202 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007203 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007204 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007205 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007206
7207 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7208 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7209 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7210
7211 // If either side is type-dependent, create an appropriate dependent
7212 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007213 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007214 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007215 // If there are no functions to store, just build a dependent
7216 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007217 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007218 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7219 Context.DependentTy, OpLoc));
7220
7221 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7222 Context.DependentTy,
7223 Context.DependentTy,
7224 Context.DependentTy,
7225 OpLoc));
7226 }
John McCall4c4c1df2010-01-26 03:27:55 +00007227
7228 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007229 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007230 // TODO: provide better source location info in DNLoc component.
7231 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007232 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007233 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007234 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007235 /*ADL*/ true, IsOverloaded(Fns),
7236 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007237 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007238 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007239 Context.DependentTy,
7240 OpLoc));
7241 }
7242
7243 // If this is the .* operator, which is not overloadable, just
7244 // create a built-in binary operator.
John McCalle3027922010-08-25 11:45:40 +00007245 if (Opc == BO_PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00007246 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007247
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007248 // If this is the assignment operator, we only perform overload resolution
7249 // if the left-hand side is a class or enumeration type. This is actually
7250 // a hack. The standard requires that we do overload resolution between the
7251 // various built-in candidates, but as DR507 points out, this can lead to
7252 // problems. So we do it this way, which pretty much follows what GCC does.
7253 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007254 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007255 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007256
Douglas Gregor084d8552009-03-13 23:49:33 +00007257 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007258 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007259
7260 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007261 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007262
7263 // Add operator candidates that are member functions.
7264 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7265
John McCall4c4c1df2010-01-26 03:27:55 +00007266 // Add candidates from ADL.
7267 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7268 Args, 2,
7269 /*ExplicitTemplateArgs*/ 0,
7270 CandidateSet);
7271
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007272 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007273 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007274
7275 // Perform overload resolution.
7276 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007277 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007278 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007279 // We found a built-in operator or an overloaded operator.
7280 FunctionDecl *FnDecl = Best->Function;
7281
7282 if (FnDecl) {
7283 // We matched an overloaded operator. Build a call to that
7284 // operator.
7285
7286 // Convert the arguments.
7287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007288 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007289 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007290
John McCalldadc5752010-08-24 06:29:42 +00007291 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007292 = PerformCopyInitialization(
7293 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007294 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007295 FnDecl->getParamDecl(0)),
7296 SourceLocation(),
7297 Owned(Args[1]));
7298 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007299 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007300
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007301 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007302 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007303 return ExprError();
7304
7305 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007306 } else {
7307 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007308 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007309 = PerformCopyInitialization(
7310 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007311 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007312 FnDecl->getParamDecl(0)),
7313 SourceLocation(),
7314 Owned(Args[0]));
7315 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007316 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007317
John McCalldadc5752010-08-24 06:29:42 +00007318 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007319 = PerformCopyInitialization(
7320 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007321 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007322 FnDecl->getParamDecl(1)),
7323 SourceLocation(),
7324 Owned(Args[1]));
7325 if (Arg1.isInvalid())
7326 return ExprError();
7327 Args[0] = LHS = Arg0.takeAs<Expr>();
7328 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007329 }
7330
John McCall4fa0d5f2010-05-06 18:15:07 +00007331 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7332
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007333 // Determine the result type
7334 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007335 = FnDecl->getType()->getAs<FunctionType>()
7336 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007337
7338 // Build the actual expression node.
7339 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00007340 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007341 UsualUnaryConversions(FnExpr);
7342
John McCallb268a282010-08-23 23:25:46 +00007343 CXXOperatorCallExpr *TheCall =
7344 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7345 Args, 2, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007346
John McCallb268a282010-08-23 23:25:46 +00007347 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007348 FnDecl))
7349 return ExprError();
7350
John McCallb268a282010-08-23 23:25:46 +00007351 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007352 } else {
7353 // We matched a built-in operator. Convert the arguments, then
7354 // break out so that we will build the appropriate built-in
7355 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007356 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007357 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007358 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007359 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007360 return ExprError();
7361
7362 break;
7363 }
7364 }
7365
Douglas Gregor66950a32009-09-30 21:46:01 +00007366 case OR_No_Viable_Function: {
7367 // C++ [over.match.oper]p9:
7368 // If the operator is the operator , [...] and there are no
7369 // viable functions, then the operator is assumed to be the
7370 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007371 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007372 break;
7373
Sebastian Redl027de2a2009-05-21 11:50:50 +00007374 // For class as left operand for assignment or compound assigment operator
7375 // do not fall through to handling in built-in, but report that no overloaded
7376 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007377 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007378 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007379 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007380 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7381 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007382 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007383 } else {
7384 // No viable function; try to create a built-in operation, which will
7385 // produce an error. Then, show the non-viable candidates.
7386 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007387 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007388 assert(Result.isInvalid() &&
7389 "C++ binary operator overloading is missing candidates!");
7390 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007391 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7392 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007393 return move(Result);
7394 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007395
7396 case OR_Ambiguous:
7397 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7398 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007399 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007400 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7401 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007402 return ExprError();
7403
7404 case OR_Deleted:
7405 Diag(OpLoc, diag::err_ovl_deleted_oper)
7406 << Best->Function->isDeleted()
7407 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007408 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007409 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007410 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007411 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007412
Douglas Gregor66950a32009-09-30 21:46:01 +00007413 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007414 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007415}
7416
John McCalldadc5752010-08-24 06:29:42 +00007417ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007418Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7419 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007420 Expr *Base, Expr *Idx) {
7421 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007422 DeclarationName OpName =
7423 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7424
7425 // If either side is type-dependent, create an appropriate dependent
7426 // expression.
7427 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7428
John McCall58cc69d2010-01-27 01:50:18 +00007429 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007430 // CHECKME: no 'operator' keyword?
7431 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7432 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007433 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007434 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007435 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007436 /*ADL*/ true, /*Overloaded*/ false,
7437 UnresolvedSetIterator(),
7438 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007439 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007440
Sebastian Redladba46e2009-10-29 20:17:01 +00007441 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7442 Args, 2,
7443 Context.DependentTy,
7444 RLoc));
7445 }
7446
7447 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007448 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007449
7450 // Subscript can only be overloaded as a member function.
7451
7452 // Add operator candidates that are member functions.
7453 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7454
7455 // Add builtin operator candidates.
7456 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7457
7458 // Perform overload resolution.
7459 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007460 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007461 case OR_Success: {
7462 // We found a built-in operator or an overloaded operator.
7463 FunctionDecl *FnDecl = Best->Function;
7464
7465 if (FnDecl) {
7466 // We matched an overloaded operator. Build a call to that
7467 // operator.
7468
John McCalla0296f72010-03-19 07:35:19 +00007469 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007470 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007471
Sebastian Redladba46e2009-10-29 20:17:01 +00007472 // Convert the arguments.
7473 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007474 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007475 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007476 return ExprError();
7477
Anders Carlssona68e51e2010-01-29 18:37:50 +00007478 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007479 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007480 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007481 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007482 FnDecl->getParamDecl(0)),
7483 SourceLocation(),
7484 Owned(Args[1]));
7485 if (InputInit.isInvalid())
7486 return ExprError();
7487
7488 Args[1] = InputInit.takeAs<Expr>();
7489
Sebastian Redladba46e2009-10-29 20:17:01 +00007490 // Determine the result type
7491 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007492 = FnDecl->getType()->getAs<FunctionType>()
7493 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007494
7495 // Build the actual expression node.
7496 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7497 LLoc);
7498 UsualUnaryConversions(FnExpr);
7499
John McCallb268a282010-08-23 23:25:46 +00007500 CXXOperatorCallExpr *TheCall =
7501 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7502 FnExpr, Args, 2,
7503 ResultTy, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007504
John McCallb268a282010-08-23 23:25:46 +00007505 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007506 FnDecl))
7507 return ExprError();
7508
John McCallb268a282010-08-23 23:25:46 +00007509 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007510 } else {
7511 // We matched a built-in operator. Convert the arguments, then
7512 // break out so that we will build the appropriate built-in
7513 // operator node.
7514 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007515 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007516 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007517 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007518 return ExprError();
7519
7520 break;
7521 }
7522 }
7523
7524 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007525 if (CandidateSet.empty())
7526 Diag(LLoc, diag::err_ovl_no_oper)
7527 << Args[0]->getType() << /*subscript*/ 0
7528 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7529 else
7530 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7531 << Args[0]->getType()
7532 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007533 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7534 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007535 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007536 }
7537
7538 case OR_Ambiguous:
7539 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7540 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007541 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7542 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007543 return ExprError();
7544
7545 case OR_Deleted:
7546 Diag(LLoc, diag::err_ovl_deleted_oper)
7547 << Best->Function->isDeleted() << "[]"
7548 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007549 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7550 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007551 return ExprError();
7552 }
7553
7554 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007555 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007556}
7557
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007558/// BuildCallToMemberFunction - Build a call to a member
7559/// function. MemExpr is the expression that refers to the member
7560/// function (and includes the object parameter), Args/NumArgs are the
7561/// arguments to the function call (not including the object
7562/// parameter). The caller needs to validate that the member
7563/// expression refers to a member function or an overloaded member
7564/// function.
John McCalldadc5752010-08-24 06:29:42 +00007565ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007566Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7567 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007568 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007569 // Dig out the member expression. This holds both the object
7570 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007571 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7572
John McCall10eae182009-11-30 22:42:35 +00007573 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007574 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007575 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007576 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007577 if (isa<MemberExpr>(NakedMemExpr)) {
7578 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007579 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007580 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007581 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007582 } else {
7583 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007584 Qualifier = UnresExpr->getQualifier();
7585
John McCall6e9f8f62009-12-03 04:06:58 +00007586 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007587
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007588 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007589 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007590
John McCall2d74de92009-12-01 22:10:20 +00007591 // FIXME: avoid copy.
7592 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7593 if (UnresExpr->hasExplicitTemplateArgs()) {
7594 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7595 TemplateArgs = &TemplateArgsBuffer;
7596 }
7597
John McCall10eae182009-11-30 22:42:35 +00007598 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7599 E = UnresExpr->decls_end(); I != E; ++I) {
7600
John McCall6e9f8f62009-12-03 04:06:58 +00007601 NamedDecl *Func = *I;
7602 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7603 if (isa<UsingShadowDecl>(Func))
7604 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7605
John McCall10eae182009-11-30 22:42:35 +00007606 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007607 // If explicit template arguments were provided, we can't call a
7608 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007609 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007610 continue;
7611
John McCalla0296f72010-03-19 07:35:19 +00007612 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007613 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007614 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007615 } else {
John McCall10eae182009-11-30 22:42:35 +00007616 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007617 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007618 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007619 CandidateSet,
7620 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007621 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007622 }
Mike Stump11289f42009-09-09 15:08:12 +00007623
John McCall10eae182009-11-30 22:42:35 +00007624 DeclarationName DeclName = UnresExpr->getMemberName();
7625
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007626 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007627 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7628 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007629 case OR_Success:
7630 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007631 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007632 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007633 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007634 break;
7635
7636 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007637 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007638 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007639 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007640 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007641 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007642 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007643
7644 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007645 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007646 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007647 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007648 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007649 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007650
7651 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007652 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007653 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007654 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007655 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007656 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007657 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007658 }
7659
John McCall16df1e52010-03-30 21:47:33 +00007660 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007661
John McCall2d74de92009-12-01 22:10:20 +00007662 // If overload resolution picked a static member, build a
7663 // non-member call based on that function.
7664 if (Method->isStatic()) {
7665 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7666 Args, NumArgs, RParenLoc);
7667 }
7668
John McCall10eae182009-11-30 22:42:35 +00007669 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007670 }
7671
7672 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007673 CXXMemberCallExpr *TheCall =
7674 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7675 Method->getCallResultType(),
7676 RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007677
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007678 // Check for a valid return type.
7679 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007680 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007681 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007682
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007683 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007684 // We only need to do this if there was actually an overload; otherwise
7685 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007686 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007687 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007688 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7689 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007690 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007691 MemExpr->setBase(ObjectArg);
7692
7693 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007694 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007695 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007696 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007697 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007698
John McCallb268a282010-08-23 23:25:46 +00007699 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007700 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007701
John McCallb268a282010-08-23 23:25:46 +00007702 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007703}
7704
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007705/// BuildCallToObjectOfClassType - Build a call to an object of class
7706/// type (C++ [over.call.object]), which can end up invoking an
7707/// overloaded function call operator (@c operator()) or performing a
7708/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007709ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007710Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007711 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007712 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007713 SourceLocation RParenLoc) {
7714 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007715 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007716
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007717 // C++ [over.call.object]p1:
7718 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007719 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007720 // candidate functions includes at least the function call
7721 // operators of T. The function call operators of T are obtained by
7722 // ordinary lookup of the name operator() in the context of
7723 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007724 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007725 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007726
7727 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007728 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007729 << Object->getSourceRange()))
7730 return true;
7731
John McCall27b18f82009-11-17 02:14:36 +00007732 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7733 LookupQualifiedName(R, Record->getDecl());
7734 R.suppressDiagnostics();
7735
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007736 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007737 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007738 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007739 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007740 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007741 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007742
Douglas Gregorab7897a2008-11-19 22:57:39 +00007743 // C++ [over.call.object]p2:
7744 // In addition, for each conversion function declared in T of the
7745 // form
7746 //
7747 // operator conversion-type-id () cv-qualifier;
7748 //
7749 // where cv-qualifier is the same cv-qualification as, or a
7750 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007751 // denotes the type "pointer to function of (P1,...,Pn) returning
7752 // R", or the type "reference to pointer to function of
7753 // (P1,...,Pn) returning R", or the type "reference to function
7754 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007755 // is also considered as a candidate function. Similarly,
7756 // surrogate call functions are added to the set of candidate
7757 // functions for each conversion function declared in an
7758 // accessible base class provided the function is not hidden
7759 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007760 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007761 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007762 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007763 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007764 NamedDecl *D = *I;
7765 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7766 if (isa<UsingShadowDecl>(D))
7767 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7768
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007769 // Skip over templated conversion functions; they aren't
7770 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007771 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007772 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007773
John McCall6e9f8f62009-12-03 04:06:58 +00007774 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007775
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007776 // Strip the reference type (if any) and then the pointer type (if
7777 // any) to get down to what might be a function type.
7778 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7779 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7780 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007781
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007782 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007783 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007784 Object->getType(), Args, NumArgs,
7785 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007786 }
Mike Stump11289f42009-09-09 15:08:12 +00007787
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007788 // Perform overload resolution.
7789 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007790 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7791 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007792 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007793 // Overload resolution succeeded; we'll build the appropriate call
7794 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007795 break;
7796
7797 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007798 if (CandidateSet.empty())
7799 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7800 << Object->getType() << /*call*/ 1
7801 << Object->getSourceRange();
7802 else
7803 Diag(Object->getSourceRange().getBegin(),
7804 diag::err_ovl_no_viable_object_call)
7805 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007806 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007807 break;
7808
7809 case OR_Ambiguous:
7810 Diag(Object->getSourceRange().getBegin(),
7811 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007812 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007813 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007814 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007815
7816 case OR_Deleted:
7817 Diag(Object->getSourceRange().getBegin(),
7818 diag::err_ovl_deleted_object_call)
7819 << Best->Function->isDeleted()
7820 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007821 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007822 break;
Mike Stump11289f42009-09-09 15:08:12 +00007823 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007824
Douglas Gregorb412e172010-07-25 18:17:45 +00007825 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007826 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007827
Douglas Gregorab7897a2008-11-19 22:57:39 +00007828 if (Best->Function == 0) {
7829 // Since there is no function declaration, this is one of the
7830 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007831 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007832 = cast<CXXConversionDecl>(
7833 Best->Conversions[0].UserDefined.ConversionFunction);
7834
John McCalla0296f72010-03-19 07:35:19 +00007835 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007836 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007837
Douglas Gregorab7897a2008-11-19 22:57:39 +00007838 // We selected one of the surrogate functions that converts the
7839 // object parameter to a function pointer. Perform the conversion
7840 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007841
7842 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007843 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007844 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7845 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007846
John McCallfaf5fb42010-08-26 23:41:50 +00007847 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007848 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007849 }
7850
John McCalla0296f72010-03-19 07:35:19 +00007851 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007852 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007853
Douglas Gregorab7897a2008-11-19 22:57:39 +00007854 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7855 // that calls this method, using Object for the implicit object
7856 // parameter and passing along the remaining arguments.
7857 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007858 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007859
7860 unsigned NumArgsInProto = Proto->getNumArgs();
7861 unsigned NumArgsToCheck = NumArgs;
7862
7863 // Build the full argument list for the method call (the
7864 // implicit object parameter is placed at the beginning of the
7865 // list).
7866 Expr **MethodArgs;
7867 if (NumArgs < NumArgsInProto) {
7868 NumArgsToCheck = NumArgsInProto;
7869 MethodArgs = new Expr*[NumArgsInProto + 1];
7870 } else {
7871 MethodArgs = new Expr*[NumArgs + 1];
7872 }
7873 MethodArgs[0] = Object;
7874 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7875 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007876
7877 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007878 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007879 UsualUnaryConversions(NewFn);
7880
7881 // Once we've built TheCall, all of the expressions are properly
7882 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007883 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007884 CXXOperatorCallExpr *TheCall =
7885 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7886 MethodArgs, NumArgs + 1,
7887 ResultTy, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007888 delete [] MethodArgs;
7889
John McCallb268a282010-08-23 23:25:46 +00007890 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007891 Method))
7892 return true;
7893
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007894 // We may have default arguments. If so, we need to allocate more
7895 // slots in the call for them.
7896 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007897 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007898 else if (NumArgs > NumArgsInProto)
7899 NumArgsToCheck = NumArgsInProto;
7900
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007901 bool IsError = false;
7902
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007903 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007904 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007905 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007906 TheCall->setArg(0, Object);
7907
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007908
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007909 // Check the argument types.
7910 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007911 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007912 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007913 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007914
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007915 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007916
John McCalldadc5752010-08-24 06:29:42 +00007917 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007918 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007919 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007920 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007921 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007922
7923 IsError |= InputInit.isInvalid();
7924 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007925 } else {
John McCalldadc5752010-08-24 06:29:42 +00007926 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007927 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7928 if (DefArg.isInvalid()) {
7929 IsError = true;
7930 break;
7931 }
7932
7933 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007934 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007935
7936 TheCall->setArg(i + 1, Arg);
7937 }
7938
7939 // If this is a variadic call, handle args passed through "...".
7940 if (Proto->isVariadic()) {
7941 // Promote the arguments (C99 6.5.2.2p7).
7942 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7943 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007944 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007945 TheCall->setArg(i + 1, Arg);
7946 }
7947 }
7948
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007949 if (IsError) return true;
7950
John McCallb268a282010-08-23 23:25:46 +00007951 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007952 return true;
7953
John McCalle172be52010-08-24 06:09:16 +00007954 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007955}
7956
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007957/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007958/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007959/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00007960ExprResult
John McCallb268a282010-08-23 23:25:46 +00007961Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007962 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007963
John McCallbc077cf2010-02-08 23:07:23 +00007964 SourceLocation Loc = Base->getExprLoc();
7965
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007966 // C++ [over.ref]p1:
7967 //
7968 // [...] An expression x->m is interpreted as (x.operator->())->m
7969 // for a class object x of type T if T::operator->() exists and if
7970 // the operator is selected as the best match function by the
7971 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007972 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007973 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007974 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007975
John McCallbc077cf2010-02-08 23:07:23 +00007976 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007977 PDiag(diag::err_typecheck_incomplete_tag)
7978 << Base->getSourceRange()))
7979 return ExprError();
7980
John McCall27b18f82009-11-17 02:14:36 +00007981 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7982 LookupQualifiedName(R, BaseRecord->getDecl());
7983 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007984
7985 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007986 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007987 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007988 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007989 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007990
7991 // Perform overload resolution.
7992 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007993 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007994 case OR_Success:
7995 // Overload resolution succeeded; we'll build the call below.
7996 break;
7997
7998 case OR_No_Viable_Function:
7999 if (CandidateSet.empty())
8000 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008001 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008002 else
8003 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008004 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008005 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008006 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008007
8008 case OR_Ambiguous:
8009 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00008010 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008011 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008012 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008013
8014 case OR_Deleted:
8015 Diag(OpLoc, diag::err_ovl_deleted_oper)
8016 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008017 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008018 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008019 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008020 }
8021
John McCalla0296f72010-03-19 07:35:19 +00008022 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008023 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008024
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008025 // Convert the object parameter.
8026 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008027 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8028 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008029 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008030
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008031 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00008032 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
8033 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008034 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008035
Douglas Gregor603d81b2010-07-13 08:18:22 +00008036 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00008037 CXXOperatorCallExpr *TheCall =
8038 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
8039 &Base, 1, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008040
John McCallb268a282010-08-23 23:25:46 +00008041 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008042 Method))
8043 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008044 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008045}
8046
Douglas Gregorcd695e52008-11-10 20:40:00 +00008047/// FixOverloadedFunctionReference - E is an expression that refers to
8048/// a C++ overloaded function (possibly with some parentheses and
8049/// perhaps a '&' around it). We have resolved the overloaded function
8050/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008051/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008052Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008053 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008054 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008055 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8056 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008057 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008058 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008059
8060 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8061 }
8062
8063 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008064 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8065 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008066 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008067 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008068 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008069 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008070 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008071 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008072
John McCallcf142162010-08-07 06:22:56 +00008073 return ImplicitCastExpr::Create(Context, ICE->getType(),
8074 ICE->getCastKind(),
8075 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008076 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008077 }
8078
8079 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008080 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008081 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008082 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8083 if (Method->isStatic()) {
8084 // Do nothing: static member functions aren't any different
8085 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008086 } else {
John McCalle66edc12009-11-24 19:00:30 +00008087 // Fix the sub expression, which really has to be an
8088 // UnresolvedLookupExpr holding an overloaded member function
8089 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008090 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8091 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008092 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008093 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008094
John McCalld14a8642009-11-21 08:51:07 +00008095 assert(isa<DeclRefExpr>(SubExpr)
8096 && "fixed to something other than a decl ref");
8097 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8098 && "fixed to a member ref with no nested name qualifier");
8099
8100 // We have taken the address of a pointer to member
8101 // function. Perform the computation here so that we get the
8102 // appropriate pointer to member type.
8103 QualType ClassType
8104 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8105 QualType MemPtrType
8106 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8107
John McCalle3027922010-08-25 11:45:40 +00008108 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCalld14a8642009-11-21 08:51:07 +00008109 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008110 }
8111 }
John McCall16df1e52010-03-30 21:47:33 +00008112 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8113 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008114 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008115 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008116
John McCalle3027922010-08-25 11:45:40 +00008117 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008118 Context.getPointerType(SubExpr->getType()),
8119 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008120 }
John McCalld14a8642009-11-21 08:51:07 +00008121
8122 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008123 // FIXME: avoid copy.
8124 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008125 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008126 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8127 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008128 }
8129
John McCalld14a8642009-11-21 08:51:07 +00008130 return DeclRefExpr::Create(Context,
8131 ULE->getQualifier(),
8132 ULE->getQualifierRange(),
8133 Fn,
8134 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008135 Fn->getType(),
8136 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008137 }
8138
John McCall10eae182009-11-30 22:42:35 +00008139 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008140 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008141 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8142 if (MemExpr->hasExplicitTemplateArgs()) {
8143 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8144 TemplateArgs = &TemplateArgsBuffer;
8145 }
John McCall6b51f282009-11-23 01:53:49 +00008146
John McCall2d74de92009-12-01 22:10:20 +00008147 Expr *Base;
8148
8149 // If we're filling in
8150 if (MemExpr->isImplicitAccess()) {
8151 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8152 return DeclRefExpr::Create(Context,
8153 MemExpr->getQualifier(),
8154 MemExpr->getQualifierRange(),
8155 Fn,
8156 MemExpr->getMemberLoc(),
8157 Fn->getType(),
8158 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008159 } else {
8160 SourceLocation Loc = MemExpr->getMemberLoc();
8161 if (MemExpr->getQualifier())
8162 Loc = MemExpr->getQualifierRange().getBegin();
8163 Base = new (Context) CXXThisExpr(Loc,
8164 MemExpr->getBaseType(),
8165 /*isImplicit=*/true);
8166 }
John McCall2d74de92009-12-01 22:10:20 +00008167 } else
John McCallc3007a22010-10-26 07:05:15 +00008168 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008169
8170 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008171 MemExpr->isArrow(),
8172 MemExpr->getQualifier(),
8173 MemExpr->getQualifierRange(),
8174 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008175 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008176 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008177 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008178 Fn->getType());
8179 }
8180
John McCallc3007a22010-10-26 07:05:15 +00008181 llvm_unreachable("Invalid reference to overloaded function");
8182 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008183}
8184
John McCalldadc5752010-08-24 06:29:42 +00008185ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8186 DeclAccessPair Found,
8187 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008188 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008189}
8190
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008191} // end namespace clang