blob: f0b1fcb6d05b06cfc19c5fa1d0d1aba0dc556353 [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
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000055 ICC_Conversion,
56 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000057 ICC_Conversion
58 };
59 return Category[(int)Kind];
60}
61
62/// GetConversionRank - Retrieve the implicit conversion rank
63/// corresponding to the given implicit conversion kind.
64ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
65 static const ImplicitConversionRank
66 Rank[(int)ICK_Num_Conversion_Kinds] = {
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Exact_Match,
71 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000072 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000073 ICR_Promotion,
74 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000075 ICR_Promotion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000078 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000083 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000084 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000085 ICR_Conversion,
86 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000087 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000088 };
89 return Rank[(int)Kind];
90}
91
92/// GetImplicitConversionName - Return the name of this kind of
93/// implicit conversion.
94const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000095 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000096 "No conversion",
97 "Lvalue-to-rvalue",
98 "Array-to-pointer",
99 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000100 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Qualification",
102 "Integral promotion",
103 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 "Integral conversion",
106 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000107 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 "Floating-integral conversion",
109 "Pointer conversion",
110 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000113 "Derived-to-base conversion",
114 "Vector conversion",
115 "Vector splat",
116 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 };
118 return Name[Kind];
119}
120
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000121/// StandardConversionSequence - Set the standard conversion
122/// sequence to the identity conversion.
123void StandardConversionSequence::setAsIdentityConversion() {
124 First = ICK_Identity;
125 Second = ICK_Identity;
126 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000127 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000128 ReferenceBinding = false;
129 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000130 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000131 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000132}
133
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134/// getRank - Retrieve the rank of this standard conversion sequence
135/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
136/// implicit conversions.
137ImplicitConversionRank StandardConversionSequence::getRank() const {
138 ImplicitConversionRank Rank = ICR_Exact_Match;
139 if (GetConversionRank(First) > Rank)
140 Rank = GetConversionRank(First);
141 if (GetConversionRank(Second) > Rank)
142 Rank = GetConversionRank(Second);
143 if (GetConversionRank(Third) > Rank)
144 Rank = GetConversionRank(Third);
145 return Rank;
146}
147
148/// isPointerConversionToBool - Determines whether this conversion is
149/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000150/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000152bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 // Note that FromType has not necessarily been transformed by the
154 // array-to-pointer or function-to-pointer implicit conversions, so
155 // check for their presence as well as checking whether FromType is
156 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000157 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000158 (getFromType()->isPointerType() ||
159 getFromType()->isObjCObjectPointerType() ||
160 getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
162 return true;
163
164 return false;
165}
166
Douglas Gregor5c407d92008-10-23 00:40:37 +0000167/// isPointerConversionToVoidPointer - Determines whether this
168/// conversion is a conversion of a pointer to a void pointer. This is
169/// used as part of the ranking of standard conversion sequences (C++
170/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000171bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000172StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000173isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000174 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000175 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000176
177 // Note that FromType has not necessarily been transformed by the
178 // array-to-pointer implicit conversion, so check for its presence
179 // and redo the conversion to get a pointer.
180 if (First == ICK_Array_To_Pointer)
181 FromType = Context.getArrayDecayedType(FromType);
182
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000185 return ToPtrType->getPointeeType()->isVoidType();
186
187 return false;
188}
189
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000190/// DebugPrint - Print this standard conversion sequence to standard
191/// error. Useful for debugging overloading issues.
192void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000193 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194 bool PrintedSomething = false;
195 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000197 PrintedSomething = true;
198 }
199
200 if (Second != ICK_Identity) {
201 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000202 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000203 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000204 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000205
206 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000207 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000208 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000209 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000210 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000211 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000212 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (Third != ICK_Identity) {
217 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000218 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000220 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221 PrintedSomething = true;
222 }
223
224 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000225 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000226 }
227}
228
229/// DebugPrint - Print this user-defined conversion sequence to standard
230/// error. Useful for debugging overloading issues.
231void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000232 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000233 if (Before.First || Before.Second || Before.Third) {
234 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000237 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 After.DebugPrint();
241 }
242}
243
244/// DebugPrint - Print this implicit conversion sequence to standard
245/// error. Useful for debugging overloading issues.
246void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000247 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000248 switch (ConversionKind) {
249 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 Standard.DebugPrint();
252 break;
253 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000254 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 UserDefined.DebugPrint();
256 break;
257 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000258 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000259 break;
John McCall0d1da222010-01-12 00:44:57 +0000260 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000261 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000262 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 break;
266 }
267
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269}
270
John McCall0d1da222010-01-12 00:44:57 +0000271void AmbiguousConversionSequence::construct() {
272 new (&conversions()) ConversionSet();
273}
274
275void AmbiguousConversionSequence::destruct() {
276 conversions().~ConversionSet();
277}
278
279void
280AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
281 FromTypePtr = O.FromTypePtr;
282 ToTypePtr = O.ToTypePtr;
283 new (&conversions()) ConversionSet(O.conversions());
284}
285
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000286namespace {
287 // Structure used by OverloadCandidate::DeductionFailureInfo to store
288 // template parameter and template argument information.
289 struct DFIParamWithArguments {
290 TemplateParameter Param;
291 TemplateArgument FirstArg;
292 TemplateArgument SecondArg;
293 };
294}
295
296/// \brief Convert from Sema's representation of template deduction information
297/// to the form used in overload-candidate information.
298OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000299static MakeDeductionFailureInfo(ASTContext &Context,
300 Sema::TemplateDeductionResult TDK,
Douglas Gregord09efd42010-05-08 20:07:26 +0000301 Sema::TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000302 OverloadCandidate::DeductionFailureInfo Result;
303 Result.Result = static_cast<unsigned>(TDK);
304 Result.Data = 0;
305 switch (TDK) {
306 case Sema::TDK_Success:
307 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000308 case Sema::TDK_TooManyArguments:
309 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000310 break;
311
312 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000313 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000314 Result.Data = Info.Param.getOpaqueValue();
315 break;
316
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000317 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000318 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000319 // FIXME: Should allocate from normal heap so that we can free this later.
320 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000321 Saved->Param = Info.Param;
322 Saved->FirstArg = Info.FirstArg;
323 Saved->SecondArg = Info.SecondArg;
324 Result.Data = Saved;
325 break;
326 }
327
328 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000329 Result.Data = Info.take();
330 break;
331
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000332 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000333 case Sema::TDK_FailedOverloadResolution:
334 break;
335 }
336
337 return Result;
338}
John McCall0d1da222010-01-12 00:44:57 +0000339
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000340void OverloadCandidate::DeductionFailureInfo::Destroy() {
341 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
342 case Sema::TDK_Success:
343 case Sema::TDK_InstantiationDepth:
344 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000345 case Sema::TDK_TooManyArguments:
346 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000347 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000348 break;
349
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000352 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000353 Data = 0;
354 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000355
356 case Sema::TDK_SubstitutionFailure:
357 // FIXME: Destroy the template arugment list?
358 Data = 0;
359 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360
Douglas Gregor461761d2010-05-08 18:20:53 +0000361 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000363 case Sema::TDK_FailedOverloadResolution:
364 break;
365 }
366}
367
368TemplateParameter
369OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
370 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
371 case Sema::TDK_Success:
372 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000373 case Sema::TDK_TooManyArguments:
374 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000375 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 return TemplateParameter();
377
378 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 return TemplateParameter::getFromOpaqueValue(Data);
381
382 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384 return static_cast<DFIParamWithArguments*>(Data)->Param;
385
386 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000387 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_FailedOverloadResolution:
389 break;
390 }
391
392 return TemplateParameter();
393}
Douglas Gregord09efd42010-05-08 20:07:26 +0000394
395TemplateArgumentList *
396OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
397 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
398 case Sema::TDK_Success:
399 case Sema::TDK_InstantiationDepth:
400 case Sema::TDK_TooManyArguments:
401 case Sema::TDK_TooFewArguments:
402 case Sema::TDK_Incomplete:
403 case Sema::TDK_InvalidExplicitArguments:
404 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000405 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000406 return 0;
407
408 case Sema::TDK_SubstitutionFailure:
409 return static_cast<TemplateArgumentList*>(Data);
410
411 // Unhandled
412 case Sema::TDK_NonDeducedMismatch:
413 case Sema::TDK_FailedOverloadResolution:
414 break;
415 }
416
417 return 0;
418}
419
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
421 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
422 case Sema::TDK_Success:
423 case Sema::TDK_InstantiationDepth:
424 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000425 case Sema::TDK_TooManyArguments:
426 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000428 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429 return 0;
430
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000432 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
434
Douglas Gregor461761d2010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440
441 return 0;
442}
443
444const TemplateArgument *
445OverloadCandidate::DeductionFailureInfo::getSecondArg() {
446 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
447 case Sema::TDK_Success:
448 case Sema::TDK_InstantiationDepth:
449 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000450 case Sema::TDK_TooManyArguments:
451 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000452 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000453 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 return 0;
455
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000456 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor461761d2010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000475// overload of the declarations in Old. This routine returns false if
476// New and Old cannot be overloaded, e.g., if New has the same
477// signature as some function in Old (C++ 1.3.10) or if the Old
478// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000479// it does return false, MatchedDecl will point to the decl that New
480// cannot be overloaded with. This decl may be a UsingShadowDecl on
481// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482//
483// Example: Given the following input:
484//
485// void f(int, float); // #1
486// void f(int, int); // #2
487// int f(int, int); // #3
488//
489// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491//
John McCall3d988d92009-12-02 08:47:38 +0000492// When we process #2, Old contains only the FunctionDecl for #1. By
493// comparing the parameter types, we see that #1 and #2 are overloaded
494// (since they have different signatures), so this routine returns
495// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496//
John McCall3d988d92009-12-02 08:47:38 +0000497// When we process #3, Old is an overload set containing #1 and #2. We
498// compare the signatures of #3 to #1 (they're overloaded, so we do
499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
500// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000503//
504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
505// into a class by a using declaration. The rules for whether to hide
506// shadow declarations ignore some properties which otherwise figure
507// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000513 NamedDecl *OldD = *I;
514
515 bool OldIsUsingDecl = false;
516 if (isa<UsingShadowDecl>(OldD)) {
517 OldIsUsingDecl = true;
518
519 // We can always introduce two using declarations into the same
520 // context, even if they have identical signatures.
521 if (NewIsUsingDecl) continue;
522
523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
524 }
525
526 // If either declaration was introduced by a using declaration,
527 // we'll need to use slightly different rules for matching.
528 // Essentially, these rules are the normal rules, except that
529 // function templates hide function templates with different
530 // return types or template parameter lists.
531 bool UseMemberUsingDeclRules =
532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
533
John McCall3d988d92009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
536 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
538 continue;
539 }
540
John McCalldaa3d6b2009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000543 }
John McCall3d988d92009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
546 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
548 continue;
549 }
550
John McCalldaa3d6b2009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000553 }
John McCall84d87672009-12-10 09:41:52 +0000554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
555 // We can overload with these, which can show up when doing
556 // redeclaration checks for UsingDecls.
557 assert(Old.getLookupKind() == LookupUsingDeclName);
558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
559 // Optimistically assume that an unresolved using decl will
560 // overload; if it doesn't, we'll have to diagnose during
561 // template instantiation.
562 } else {
John McCall1f82f242009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000568 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 }
John McCall1f82f242009-11-18 22:49:29 +0000570
John McCalldaa3d6b2009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000572}
573
John McCalle9cccd82010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall1f82f242009-11-18 22:49:29 +0000576 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
577 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
578
579 // C++ [temp.fct]p2:
580 // A function template can be overloaded with other function templates
581 // and with normal (non-template) functions.
582 if ((OldTemplate == 0) != (NewTemplate == 0))
583 return true;
584
585 // Is the function New an overload of the function Old?
586 QualType OldQType = Context.getCanonicalType(Old->getType());
587 QualType NewQType = Context.getCanonicalType(New->getType());
588
589 // Compare the signatures (C++ 1.3.10) of the two functions to
590 // determine whether they are overloads. If we find any mismatch
591 // in the signature, they are overloads.
592
593 // If either of these functions is a K&R-style function (no
594 // prototype), then we consider them to have matching signatures.
595 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
596 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
597 return false;
598
599 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
600 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
601
602 // The signature of a function includes the types of its
603 // parameters (C++ 1.3.10), which includes the presence or absence
604 // of the ellipsis; see C++ DR 357).
605 if (OldQType != NewQType &&
606 (OldType->getNumArgs() != NewType->getNumArgs() ||
607 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000608 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000609 return true;
610
611 // C++ [temp.over.link]p4:
612 // The signature of a function template consists of its function
613 // signature, its return type and its template parameter list. The names
614 // of the template parameters are significant only for establishing the
615 // relationship between the template parameters and the rest of the
616 // signature.
617 //
618 // We check the return type and template parameter lists for function
619 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000620 //
621 // However, we don't consider either of these when deciding whether
622 // a member introduced by a shadow declaration is hidden.
623 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000624 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
625 OldTemplate->getTemplateParameters(),
626 false, TPL_TemplateMatch) ||
627 OldType->getResultType() != NewType->getResultType()))
628 return true;
629
630 // If the function is a class member, its signature includes the
631 // cv-qualifiers (if any) on the function itself.
632 //
633 // As part of this, also check whether one of the member functions
634 // is static, in which case they are not overloads (C++
635 // 13.1p2). While not part of the definition of the signature,
636 // this check is important to determine whether these functions
637 // can be overloaded.
638 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
639 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
640 if (OldMethod && NewMethod &&
641 !OldMethod->isStatic() && !NewMethod->isStatic() &&
642 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
643 return true;
644
645 // The signatures match; this is not an overload.
646 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000647}
648
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000649/// TryImplicitConversion - Attempt to perform an implicit conversion
650/// from the given expression (Expr) to the given type (ToType). This
651/// function returns an implicit conversion sequence that can be used
652/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653///
654/// void f(float f);
655/// void g(int i) { f(i); }
656///
657/// this routine would produce an implicit conversion sequence to
658/// describe the initialization of f from i, which will be a standard
659/// conversion sequence containing an lvalue-to-rvalue conversion (C++
660/// 4.1) followed by a floating-integral conversion (C++ 4.9).
661//
662/// Note that this routine only determines how the conversion can be
663/// performed; it does not actually perform the conversion. As such,
664/// it will not produce any diagnostics if no conversion is available,
665/// but will instead return an implicit conversion sequence of kind
666/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000667///
668/// If @p SuppressUserConversions, then user-defined conversions are
669/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000670/// If @p AllowExplicit, then explicit user-defined conversions are
671/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000672ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000673Sema::TryImplicitConversion(Expr* From, QualType ToType,
674 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000675 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000676 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000677 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000678 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000679 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000680 return ICS;
681 }
682
683 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000684 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000685 return ICS;
686 }
687
Douglas Gregor5ab11652010-04-17 22:01:05 +0000688 if (SuppressUserConversions) {
689 // C++ [over.ics.user]p4:
690 // A conversion of an expression of class type to the same class
691 // type is given Exact Match rank, and a conversion of an
692 // expression of class type to a base class of that type is
693 // given Conversion rank, in spite of the fact that a copy/move
694 // constructor (i.e., a user-defined conversion function) is
695 // called for those cases.
696 QualType FromType = From->getType();
697 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
698 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
699 IsDerivedFrom(FromType, ToType))) {
700 // We're not in the case above, so there is no conversion that
701 // we can perform.
702 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
703 return ICS;
704 }
705
706 ICS.setStandard();
707 ICS.Standard.setAsIdentityConversion();
708 ICS.Standard.setFromType(FromType);
709 ICS.Standard.setAllToTypes(ToType);
710
711 // We don't actually check at this point whether there is a valid
712 // copy/move constructor, since overloading just assumes that it
713 // exists. When we actually perform initialization, we'll find the
714 // appropriate constructor to copy the returned object, if needed.
715 ICS.Standard.CopyConstructor = 0;
716
717 // Determine whether this is considered a derived-to-base conversion.
718 if (!Context.hasSameUnqualifiedType(FromType, ToType))
719 ICS.Standard.Second = ICK_Derived_To_Base;
720
721 return ICS;
722 }
723
724 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000725 OverloadCandidateSet Conversions(From->getExprLoc());
726 OverloadingResult UserDefResult
727 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000728 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000729
730 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000731 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000732 // C++ [over.ics.user]p4:
733 // A conversion of an expression of class type to the same class
734 // type is given Exact Match rank, and a conversion of an
735 // expression of class type to a base class of that type is
736 // given Conversion rank, in spite of the fact that a copy
737 // constructor (i.e., a user-defined conversion function) is
738 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000739 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000740 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000741 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000742 = Context.getCanonicalType(From->getType().getUnqualifiedType());
743 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000744 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000745 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000746 // Turn this into a "standard" conversion sequence, so that it
747 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000748 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000749 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000750 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000751 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000752 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000753 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000754 ICS.Standard.Second = ICK_Derived_To_Base;
755 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000756 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000757
758 // C++ [over.best.ics]p4:
759 // However, when considering the argument of a user-defined
760 // conversion function that is a candidate by 13.3.1.3 when
761 // invoked for the copying of the temporary in the second step
762 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
763 // 13.3.1.6 in all cases, only standard conversion sequences and
764 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000765 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000766 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000767 }
John McCalle8c8cd22010-01-13 22:30:33 +0000768 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000769 ICS.setAmbiguous();
770 ICS.Ambiguous.setFromType(From->getType());
771 ICS.Ambiguous.setToType(ToType);
772 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
773 Cand != Conversions.end(); ++Cand)
774 if (Cand->Viable)
775 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000776 } else {
John McCall65eb8792010-02-25 01:37:24 +0000777 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000778 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000779
780 return ICS;
781}
782
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000783/// PerformImplicitConversion - Perform an implicit conversion of the
784/// expression From to the type ToType. Returns true if there was an
785/// error, false otherwise. The expression From is replaced with the
786/// converted expression. Flavor is the kind of conversion we're
787/// performing, used in the error message. If @p AllowExplicit,
788/// explicit user-defined conversions are permitted.
789bool
790Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
791 AssignmentAction Action, bool AllowExplicit) {
792 ImplicitConversionSequence ICS;
793 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
794}
795
796bool
797Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
798 AssignmentAction Action, bool AllowExplicit,
799 ImplicitConversionSequence& ICS) {
800 ICS = TryImplicitConversion(From, ToType,
801 /*SuppressUserConversions=*/false,
802 AllowExplicit,
803 /*InOverloadResolution=*/false);
804 return PerformImplicitConversion(From, ToType, ICS, Action);
805}
806
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000807/// \brief Determine whether the conversion from FromType to ToType is a valid
808/// conversion that strips "noreturn" off the nested function type.
809static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
810 QualType ToType, QualType &ResultTy) {
811 if (Context.hasSameUnqualifiedType(FromType, ToType))
812 return false;
813
814 // Strip the noreturn off the type we're converting from; noreturn can
815 // safely be removed.
816 FromType = Context.getNoReturnType(FromType, false);
817 if (!Context.hasSameUnqualifiedType(FromType, ToType))
818 return false;
819
820 ResultTy = FromType;
821 return true;
822}
Douglas Gregor46188682010-05-18 22:42:18 +0000823
824/// \brief Determine whether the conversion from FromType to ToType is a valid
825/// vector conversion.
826///
827/// \param ICK Will be set to the vector conversion kind, if this is a vector
828/// conversion.
829static bool IsVectorConversion(ASTContext &Context, QualType FromType,
830 QualType ToType, ImplicitConversionKind &ICK) {
831 // We need at least one of these types to be a vector type to have a vector
832 // conversion.
833 if (!ToType->isVectorType() && !FromType->isVectorType())
834 return false;
835
836 // Identical types require no conversions.
837 if (Context.hasSameUnqualifiedType(FromType, ToType))
838 return false;
839
840 // There are no conversions between extended vector types, only identity.
841 if (ToType->isExtVectorType()) {
842 // There are no conversions between extended vector types other than the
843 // identity conversion.
844 if (FromType->isExtVectorType())
845 return false;
846
847 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000848 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000849 ICK = ICK_Vector_Splat;
850 return true;
851 }
852 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000853
854 // We can perform the conversion between vector types in the following cases:
855 // 1)vector types are equivalent AltiVec and GCC vector types
856 // 2)lax vector conversions are permitted and the vector types are of the
857 // same size
858 if (ToType->isVectorType() && FromType->isVectorType()) {
859 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000860 (Context.getLangOptions().LaxVectorConversions &&
861 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000862 ICK = ICK_Vector_Conversion;
863 return true;
864 }
Douglas Gregor46188682010-05-18 22:42:18 +0000865 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000866
Douglas Gregor46188682010-05-18 22:42:18 +0000867 return false;
868}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000869
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000870/// IsStandardConversion - Determines whether there is a standard
871/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
872/// expression From to the type ToType. Standard conversion sequences
873/// only consider non-class types; for conversions that involve class
874/// types, use TryImplicitConversion. If a conversion exists, SCS will
875/// contain the standard conversion sequence required to perform this
876/// conversion and this routine will return true. Otherwise, this
877/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000878bool
879Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000880 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000881 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000882 QualType FromType = From->getType();
883
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000884 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000885 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000886 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000887 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000888 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000889 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000890
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000891 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000892 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000893 if (FromType->isRecordType() || ToType->isRecordType()) {
894 if (getLangOptions().CPlusPlus)
895 return false;
896
Mike Stump11289f42009-09-09 15:08:12 +0000897 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000898 }
899
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000900 // The first conversion can be an lvalue-to-rvalue conversion,
901 // array-to-pointer conversion, or function-to-pointer conversion
902 // (C++ 4p1).
903
Douglas Gregor980fb162010-04-29 18:24:40 +0000904 if (FromType == Context.OverloadTy) {
905 DeclAccessPair AccessPair;
906 if (FunctionDecl *Fn
907 = ResolveAddressOfOverloadedFunction(From, ToType, false,
908 AccessPair)) {
909 // We were able to resolve the address of the overloaded function,
910 // so we can convert to the type of that function.
911 FromType = Fn->getType();
912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
913 if (!Method->isStatic()) {
914 Type *ClassType
915 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
916 FromType = Context.getMemberPointerType(FromType, ClassType);
917 }
918 }
919
920 // If the "from" expression takes the address of the overloaded
921 // function, update the type of the resulting expression accordingly.
922 if (FromType->getAs<FunctionType>())
923 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
924 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
925 FromType = Context.getPointerType(FromType);
926
927 // Check that we've computed the proper type after overload resolution.
928 assert(Context.hasSameType(FromType,
929 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
930 } else {
931 return false;
932 }
933 }
Mike Stump11289f42009-09-09 15:08:12 +0000934 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000935 // An lvalue (3.10) of a non-function, non-array type T can be
936 // converted to an rvalue.
937 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000938 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000939 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000940 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000941 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942
943 // If T is a non-class type, the type of the rvalue is the
944 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000945 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
946 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000947 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000948 } else if (FromType->isArrayType()) {
949 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000950 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951
952 // An lvalue or rvalue of type "array of N T" or "array of unknown
953 // bound of T" can be converted to an rvalue of type "pointer to
954 // T" (C++ 4.2p1).
955 FromType = Context.getArrayDecayedType(FromType);
956
957 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
958 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000959 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000960
961 // For the purpose of ranking in overload resolution
962 // (13.3.3.1.1), this conversion is considered an
963 // array-to-pointer conversion followed by a qualification
964 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000965 SCS.Second = ICK_Identity;
966 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000967 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000968 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000970 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
971 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000972 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000973
974 // An lvalue of function type T can be converted to an rvalue of
975 // type "pointer to T." The result is a pointer to the
976 // function. (C++ 4.3p1).
977 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000978 } else {
979 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000980 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000981 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000982 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000983
984 // The second conversion can be an integral promotion, floating
985 // point promotion, integral conversion, floating point conversion,
986 // floating-integral conversion, pointer conversion,
987 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000988 // For overloading in C, this can also be a "compatible-type"
989 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000990 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000991 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000992 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000993 // The unqualified versions of the types are the same: there's no
994 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000995 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000996 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000997 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000998 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000999 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001000 } else if (IsFloatingPointPromotion(FromType, ToType)) {
1001 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001002 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001003 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001004 } else if (IsComplexPromotion(FromType, ToType)) {
1005 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001006 SCS.Second = ICK_Complex_Promotion;
1007 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001008 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001009 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001010 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001011 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001012 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001013 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1014 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001015 SCS.Second = ICK_Complex_Conversion;
1016 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001017 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1018 (ToType->isComplexType() && FromType->isArithmeticType())) {
1019 // Complex-real conversions (C99 6.3.1.7)
1020 SCS.Second = ICK_Complex_Real;
1021 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001022 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001023 // Floating point conversions (C++ 4.8).
1024 SCS.Second = ICK_Floating_Conversion;
1025 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001026 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001027 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001028 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001029 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001030 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001031 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001032 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +00001033 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1034 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001035 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001036 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001037 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +00001038 } else if (IsMemberPointerConversion(From, FromType, ToType,
1039 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001040 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001041 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001042 } else if (ToType->isBooleanType() &&
1043 (FromType->isArithmeticType() ||
1044 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001045 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001046 FromType->isBlockPointerType() ||
1047 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001048 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001049 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001050 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001051 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001052 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1053 SCS.Second = SecondICK;
1054 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001055 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001056 Context.typesAreCompatible(ToType, FromType)) {
1057 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001058 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001059 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001060 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1061 // Treat a conversion that strips "noreturn" as an identity conversion.
1062 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001063 } else {
1064 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001065 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001066 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001067 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001069 QualType CanonFrom;
1070 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001072 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001073 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001074 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001075 CanonFrom = Context.getCanonicalType(FromType);
1076 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001077 } else {
1078 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001079 SCS.Third = ICK_Identity;
1080
Mike Stump11289f42009-09-09 15:08:12 +00001081 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001082 // [...] Any difference in top-level cv-qualification is
1083 // subsumed by the initialization itself and does not constitute
1084 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001085 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001086 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001087 if (CanonFrom.getLocalUnqualifiedType()
1088 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001089 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1090 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001091 FromType = ToType;
1092 CanonFrom = CanonTo;
1093 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001094 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001095 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001096
1097 // If we have not converted the argument type to the parameter type,
1098 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001099 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001100 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001101
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001102 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103}
1104
1105/// IsIntegralPromotion - Determines whether the conversion from the
1106/// expression From (whose potentially-adjusted type is FromType) to
1107/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1108/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001109bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001110 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001111 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001112 if (!To) {
1113 return false;
1114 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115
1116 // An rvalue of type char, signed char, unsigned char, short int, or
1117 // unsigned short int can be converted to an rvalue of type int if
1118 // int can represent all the values of the source type; otherwise,
1119 // the source rvalue can be converted to an rvalue of type unsigned
1120 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001121 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1122 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001123 if (// We can promote any signed, promotable integer type to an int
1124 (FromType->isSignedIntegerType() ||
1125 // We can promote any unsigned integer type whose size is
1126 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001127 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001128 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001130 }
1131
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132 return To->getKind() == BuiltinType::UInt;
1133 }
1134
1135 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1136 // can be converted to an rvalue of the first of the following types
1137 // that can represent all the values of its underlying type: int,
1138 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001139
1140 // We pre-calculate the promotion type for enum types.
1141 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1142 if (ToType->isIntegerType())
1143 return Context.hasSameUnqualifiedType(ToType,
1144 FromEnumType->getDecl()->getPromotionType());
1145
1146 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001147 // Determine whether the type we're converting from is signed or
1148 // unsigned.
1149 bool FromIsSigned;
1150 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001151
1152 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1153 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001154
1155 // The types we'll try to promote to, in the appropriate
1156 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001157 QualType PromoteTypes[6] = {
1158 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001159 Context.LongTy, Context.UnsignedLongTy ,
1160 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001161 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001162 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1164 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001165 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1167 // We found the type that we can promote to. If this is the
1168 // type we wanted, we have a promotion. Otherwise, no
1169 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001170 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171 }
1172 }
1173 }
1174
1175 // An rvalue for an integral bit-field (9.6) can be converted to an
1176 // rvalue of type int if int can represent all the values of the
1177 // bit-field; otherwise, it can be converted to unsigned int if
1178 // unsigned int can represent all the values of the bit-field. If
1179 // the bit-field is larger yet, no integral promotion applies to
1180 // it. If the bit-field has an enumerated type, it is treated as any
1181 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001182 // FIXME: We should delay checking of bit-fields until we actually perform the
1183 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001184 using llvm::APSInt;
1185 if (From)
1186 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001187 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001188 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001189 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1190 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1191 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001192
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001193 // Are we promoting to an int from a bitfield that fits in an int?
1194 if (BitWidth < ToSize ||
1195 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1196 return To->getKind() == BuiltinType::Int;
1197 }
Mike Stump11289f42009-09-09 15:08:12 +00001198
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001199 // Are we promoting to an unsigned int from an unsigned bitfield
1200 // that fits into an unsigned int?
1201 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1202 return To->getKind() == BuiltinType::UInt;
1203 }
Mike Stump11289f42009-09-09 15:08:12 +00001204
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001205 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001206 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001207 }
Mike Stump11289f42009-09-09 15:08:12 +00001208
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001209 // An rvalue of type bool can be converted to an rvalue of type int,
1210 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001211 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001212 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001213 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001214
1215 return false;
1216}
1217
1218/// IsFloatingPointPromotion - Determines whether the conversion from
1219/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1220/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001221bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222 /// An rvalue of type float can be converted to an rvalue of type
1223 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001224 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1225 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226 if (FromBuiltin->getKind() == BuiltinType::Float &&
1227 ToBuiltin->getKind() == BuiltinType::Double)
1228 return true;
1229
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001230 // C99 6.3.1.5p1:
1231 // When a float is promoted to double or long double, or a
1232 // double is promoted to long double [...].
1233 if (!getLangOptions().CPlusPlus &&
1234 (FromBuiltin->getKind() == BuiltinType::Float ||
1235 FromBuiltin->getKind() == BuiltinType::Double) &&
1236 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1237 return true;
1238 }
1239
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240 return false;
1241}
1242
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001243/// \brief Determine if a conversion is a complex promotion.
1244///
1245/// A complex promotion is defined as a complex -> complex conversion
1246/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001247/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001248bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001249 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001250 if (!FromComplex)
1251 return false;
1252
John McCall9dd450b2009-09-21 23:43:11 +00001253 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001254 if (!ToComplex)
1255 return false;
1256
1257 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001258 ToComplex->getElementType()) ||
1259 IsIntegralPromotion(0, FromComplex->getElementType(),
1260 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001261}
1262
Douglas Gregor237f96c2008-11-26 23:31:11 +00001263/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1264/// the pointer type FromPtr to a pointer to type ToPointee, with the
1265/// same type qualifiers as FromPtr has on its pointee type. ToType,
1266/// if non-empty, will be a pointer to ToType that may or may not have
1267/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001268static QualType
1269BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001270 QualType ToPointee, QualType ToType,
1271 ASTContext &Context) {
1272 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1273 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001274 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001275
1276 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001277 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001278 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001279 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001280 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001281
1282 // Build a pointer to ToPointee. It has the right qualifiers
1283 // already.
1284 return Context.getPointerType(ToPointee);
1285 }
1286
1287 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001288 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001289 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1290 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001291}
1292
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001293/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1294/// the FromType, which is an objective-c pointer, to ToType, which may or may
1295/// not have the right set of qualifiers.
1296static QualType
1297BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1298 QualType ToType,
1299 ASTContext &Context) {
1300 QualType CanonFromType = Context.getCanonicalType(FromType);
1301 QualType CanonToType = Context.getCanonicalType(ToType);
1302 Qualifiers Quals = CanonFromType.getQualifiers();
1303
1304 // Exact qualifier match -> return the pointer type we're converting to.
1305 if (CanonToType.getLocalQualifiers() == Quals)
1306 return ToType;
1307
1308 // Just build a canonical type that has the right qualifiers.
1309 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1310}
1311
Mike Stump11289f42009-09-09 15:08:12 +00001312static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001313 bool InOverloadResolution,
1314 ASTContext &Context) {
1315 // Handle value-dependent integral null pointer constants correctly.
1316 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1317 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001318 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001319 return !InOverloadResolution;
1320
Douglas Gregor56751b52009-09-25 04:25:58 +00001321 return Expr->isNullPointerConstant(Context,
1322 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1323 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001324}
Mike Stump11289f42009-09-09 15:08:12 +00001325
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001326/// IsPointerConversion - Determines whether the conversion of the
1327/// expression From, which has the (possibly adjusted) type FromType,
1328/// can be converted to the type ToType via a pointer conversion (C++
1329/// 4.10). If so, returns true and places the converted type (that
1330/// might differ from ToType in its cv-qualifiers at some level) into
1331/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001332///
Douglas Gregora29dc052008-11-27 01:19:21 +00001333/// This routine also supports conversions to and from block pointers
1334/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1335/// pointers to interfaces. FIXME: Once we've determined the
1336/// appropriate overloading rules for Objective-C, we may want to
1337/// split the Objective-C checks into a different routine; however,
1338/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001339/// conversions, so for now they live here. IncompatibleObjC will be
1340/// set if the conversion is an allowed Objective-C conversion that
1341/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001342bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001343 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001344 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001345 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001346 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001347 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1348 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001349
Mike Stump11289f42009-09-09 15:08:12 +00001350 // Conversion from a null pointer constant to any Objective-C pointer type.
1351 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001352 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001353 ConvertedType = ToType;
1354 return true;
1355 }
1356
Douglas Gregor231d1c62008-11-27 00:15:41 +00001357 // Blocks: Block pointers can be converted to void*.
1358 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001359 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001360 ConvertedType = ToType;
1361 return true;
1362 }
1363 // Blocks: A null pointer constant can be converted to a block
1364 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001365 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001366 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001367 ConvertedType = ToType;
1368 return true;
1369 }
1370
Sebastian Redl576fd422009-05-10 18:38:11 +00001371 // If the left-hand-side is nullptr_t, the right side can be a null
1372 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001373 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001374 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001375 ConvertedType = ToType;
1376 return true;
1377 }
1378
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001379 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001380 if (!ToTypePtr)
1381 return false;
1382
1383 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001384 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001385 ConvertedType = ToType;
1386 return true;
1387 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001388
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001389 // Beyond this point, both types need to be pointers
1390 // , including objective-c pointers.
1391 QualType ToPointeeType = ToTypePtr->getPointeeType();
1392 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1393 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1394 ToType, Context);
1395 return true;
1396
1397 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001398 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001399 if (!FromTypePtr)
1400 return false;
1401
1402 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001403
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001404 // An rvalue of type "pointer to cv T," where T is an object type,
1405 // can be converted to an rvalue of type "pointer to cv void" (C++
1406 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001407 if (FromPointeeType->isIncompleteOrObjectType() &&
1408 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001409 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001410 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001411 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001412 return true;
1413 }
1414
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001415 // When we're overloading in C, we allow a special kind of pointer
1416 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001417 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001418 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001419 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001420 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001421 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001422 return true;
1423 }
1424
Douglas Gregor5c407d92008-10-23 00:40:37 +00001425 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001426 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001427 // An rvalue of type "pointer to cv D," where D is a class type,
1428 // can be converted to an rvalue of type "pointer to cv B," where
1429 // B is a base class (clause 10) of D. If B is an inaccessible
1430 // (clause 11) or ambiguous (10.2) base class of D, a program that
1431 // necessitates this conversion is ill-formed. The result of the
1432 // conversion is a pointer to the base class sub-object of the
1433 // derived class object. The null pointer value is converted to
1434 // the null pointer value of the destination type.
1435 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001436 // Note that we do not check for ambiguity or inaccessibility
1437 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001438 if (getLangOptions().CPlusPlus &&
1439 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001440 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001441 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001442 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001443 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001444 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001445 ToType, Context);
1446 return true;
1447 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001448
Douglas Gregora119f102008-12-19 19:13:09 +00001449 return false;
1450}
1451
1452/// isObjCPointerConversion - Determines whether this is an
1453/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1454/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001455bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001456 QualType& ConvertedType,
1457 bool &IncompatibleObjC) {
1458 if (!getLangOptions().ObjC1)
1459 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001460
Steve Naroff7cae42b2009-07-10 23:34:53 +00001461 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001462 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001463 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001464 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001465
Steve Naroff7cae42b2009-07-10 23:34:53 +00001466 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001467 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001468 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001469 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001470 ConvertedType = ToType;
1471 return true;
1472 }
1473 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001474 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001475 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001476 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001477 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001478 ConvertedType = ToType;
1479 return true;
1480 }
1481 // Objective C++: We're able to convert from a pointer to an
1482 // interface to a pointer to a different interface.
1483 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001484 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1485 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1486 if (getLangOptions().CPlusPlus && LHS && RHS &&
1487 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1488 FromObjCPtr->getPointeeType()))
1489 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001490 ConvertedType = ToType;
1491 return true;
1492 }
1493
1494 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1495 // Okay: this is some kind of implicit downcast of Objective-C
1496 // interfaces, which is permitted. However, we're going to
1497 // complain about it.
1498 IncompatibleObjC = true;
1499 ConvertedType = FromType;
1500 return true;
1501 }
Mike Stump11289f42009-09-09 15:08:12 +00001502 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001503 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001504 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001505 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001506 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001507 else if (const BlockPointerType *ToBlockPtr =
1508 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001509 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001510 // to a block pointer type.
1511 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1512 ConvertedType = ToType;
1513 return true;
1514 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001515 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001516 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001517 else if (FromType->getAs<BlockPointerType>() &&
1518 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1519 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001520 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001521 ConvertedType = ToType;
1522 return true;
1523 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001524 else
Douglas Gregora119f102008-12-19 19:13:09 +00001525 return false;
1526
Douglas Gregor033f56d2008-12-23 00:53:59 +00001527 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001528 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001529 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001530 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001531 FromPointeeType = FromBlockPtr->getPointeeType();
1532 else
Douglas Gregora119f102008-12-19 19:13:09 +00001533 return false;
1534
Douglas Gregora119f102008-12-19 19:13:09 +00001535 // If we have pointers to pointers, recursively check whether this
1536 // is an Objective-C conversion.
1537 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1538 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1539 IncompatibleObjC)) {
1540 // We always complain about this conversion.
1541 IncompatibleObjC = true;
1542 ConvertedType = ToType;
1543 return true;
1544 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001545 // Allow conversion of pointee being objective-c pointer to another one;
1546 // as in I* to id.
1547 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1548 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1549 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1550 IncompatibleObjC)) {
1551 ConvertedType = ToType;
1552 return true;
1553 }
1554
Douglas Gregor033f56d2008-12-23 00:53:59 +00001555 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001556 // differences in the argument and result types are in Objective-C
1557 // pointer conversions. If so, we permit the conversion (but
1558 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001559 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001560 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001561 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001562 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001563 if (FromFunctionType && ToFunctionType) {
1564 // If the function types are exactly the same, this isn't an
1565 // Objective-C pointer conversion.
1566 if (Context.getCanonicalType(FromPointeeType)
1567 == Context.getCanonicalType(ToPointeeType))
1568 return false;
1569
1570 // Perform the quick checks that will tell us whether these
1571 // function types are obviously different.
1572 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1573 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1574 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1575 return false;
1576
1577 bool HasObjCConversion = false;
1578 if (Context.getCanonicalType(FromFunctionType->getResultType())
1579 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1580 // Okay, the types match exactly. Nothing to do.
1581 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1582 ToFunctionType->getResultType(),
1583 ConvertedType, IncompatibleObjC)) {
1584 // Okay, we have an Objective-C pointer conversion.
1585 HasObjCConversion = true;
1586 } else {
1587 // Function types are too different. Abort.
1588 return false;
1589 }
Mike Stump11289f42009-09-09 15:08:12 +00001590
Douglas Gregora119f102008-12-19 19:13:09 +00001591 // Check argument types.
1592 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1593 ArgIdx != NumArgs; ++ArgIdx) {
1594 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1595 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1596 if (Context.getCanonicalType(FromArgType)
1597 == Context.getCanonicalType(ToArgType)) {
1598 // Okay, the types match exactly. Nothing to do.
1599 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1600 ConvertedType, IncompatibleObjC)) {
1601 // Okay, we have an Objective-C pointer conversion.
1602 HasObjCConversion = true;
1603 } else {
1604 // Argument types are too different. Abort.
1605 return false;
1606 }
1607 }
1608
1609 if (HasObjCConversion) {
1610 // We had an Objective-C conversion. Allow this pointer
1611 // conversion, but complain about it.
1612 ConvertedType = ToType;
1613 IncompatibleObjC = true;
1614 return true;
1615 }
1616 }
1617
Sebastian Redl72b597d2009-01-25 19:43:20 +00001618 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001620
1621/// FunctionArgTypesAreEqual - This routine checks two function proto types
1622/// for equlity of their argument types. Caller has already checked that
1623/// they have same number of arguments. This routine assumes that Objective-C
1624/// pointer types which only differ in their protocol qualifiers are equal.
1625bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1626 FunctionProtoType* NewType){
1627 if (!getLangOptions().ObjC1)
1628 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1629 NewType->arg_type_begin());
1630
1631 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1632 N = NewType->arg_type_begin(),
1633 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1634 QualType ToType = (*O);
1635 QualType FromType = (*N);
1636 if (ToType != FromType) {
1637 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1638 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001639 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1640 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1641 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1642 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001643 continue;
1644 }
John McCall8b07ec22010-05-15 11:32:37 +00001645 else if (const ObjCObjectPointerType *PTTo =
1646 ToType->getAs<ObjCObjectPointerType>()) {
1647 if (const ObjCObjectPointerType *PTFr =
1648 FromType->getAs<ObjCObjectPointerType>())
1649 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1650 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001651 }
1652 return false;
1653 }
1654 }
1655 return true;
1656}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657
Douglas Gregor39c16d42008-10-24 04:54:22 +00001658/// CheckPointerConversion - Check the pointer conversion from the
1659/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001660/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001661/// conversions for which IsPointerConversion has already returned
1662/// true. It returns true and produces a diagnostic if there was an
1663/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001664bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001665 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001666 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001667 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001668 QualType FromType = From->getType();
1669
Douglas Gregor4038cf42010-06-08 17:35:15 +00001670 if (CXXBoolLiteralExpr* LitBool
1671 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1672 if (LitBool->getValue() == false)
1673 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1674 << ToType;
1675
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001676 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1677 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001678 QualType FromPointeeType = FromPtrType->getPointeeType(),
1679 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001680
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001681 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1682 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001683 // We must have a derived-to-base conversion. Check an
1684 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001685 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1686 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001687 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001688 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001689 return true;
1690
1691 // The conversion was successful.
1692 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001693 }
1694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001696 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001697 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001698 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001699 // Objective-C++ conversions are always okay.
1700 // FIXME: We should have a different class of conversions for the
1701 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001702 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001703 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001704
Steve Naroff7cae42b2009-07-10 23:34:53 +00001705 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001706 return false;
1707}
1708
Sebastian Redl72b597d2009-01-25 19:43:20 +00001709/// IsMemberPointerConversion - Determines whether the conversion of the
1710/// expression From, which has the (possibly adjusted) type FromType, can be
1711/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1712/// If so, returns true and places the converted type (that might differ from
1713/// ToType in its cv-qualifiers at some level) into ConvertedType.
1714bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001715 QualType ToType,
1716 bool InOverloadResolution,
1717 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001718 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001719 if (!ToTypePtr)
1720 return false;
1721
1722 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001723 if (From->isNullPointerConstant(Context,
1724 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1725 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001726 ConvertedType = ToType;
1727 return true;
1728 }
1729
1730 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001731 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001732 if (!FromTypePtr)
1733 return false;
1734
1735 // A pointer to member of B can be converted to a pointer to member of D,
1736 // where D is derived from B (C++ 4.11p2).
1737 QualType FromClass(FromTypePtr->getClass(), 0);
1738 QualType ToClass(ToTypePtr->getClass(), 0);
1739 // FIXME: What happens when these are dependent? Is this function even called?
1740
1741 if (IsDerivedFrom(ToClass, FromClass)) {
1742 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1743 ToClass.getTypePtr());
1744 return true;
1745 }
1746
1747 return false;
1748}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001749
Sebastian Redl72b597d2009-01-25 19:43:20 +00001750/// CheckMemberPointerConversion - Check the member pointer conversion from the
1751/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001752/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001753/// for which IsMemberPointerConversion has already returned true. It returns
1754/// true and produces a diagnostic if there was an error, or returns false
1755/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001756bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001757 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001758 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001759 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001760 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001761 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001762 if (!FromPtrType) {
1763 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001764 assert(From->isNullPointerConstant(Context,
1765 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001766 "Expr must be null pointer constant!");
1767 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001768 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001769 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001770
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001771 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001772 assert(ToPtrType && "No member pointer cast has a target type "
1773 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001774
Sebastian Redled8f2002009-01-28 18:33:18 +00001775 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1776 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001777
Sebastian Redled8f2002009-01-28 18:33:18 +00001778 // FIXME: What about dependent types?
1779 assert(FromClass->isRecordType() && "Pointer into non-class.");
1780 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001781
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001782 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001783 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001784 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1785 assert(DerivationOkay &&
1786 "Should not have been called if derivation isn't OK.");
1787 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001788
Sebastian Redled8f2002009-01-28 18:33:18 +00001789 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1790 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001791 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1792 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1793 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1794 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001795 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001796
Douglas Gregor89ee6822009-02-28 01:32:25 +00001797 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001798 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1799 << FromClass << ToClass << QualType(VBase, 0)
1800 << From->getSourceRange();
1801 return true;
1802 }
1803
John McCall5b0829a2010-02-10 09:31:12 +00001804 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001805 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1806 Paths.front(),
1807 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001808
Anders Carlssond7923c62009-08-22 23:33:40 +00001809 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001810 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001811 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001812 return false;
1813}
1814
Douglas Gregor9a657932008-10-21 23:43:52 +00001815/// IsQualificationConversion - Determines whether the conversion from
1816/// an rvalue of type FromType to ToType is a qualification conversion
1817/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001818bool
1819Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001820 FromType = Context.getCanonicalType(FromType);
1821 ToType = Context.getCanonicalType(ToType);
1822
1823 // If FromType and ToType are the same type, this is not a
1824 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001825 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001826 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001827
Douglas Gregor9a657932008-10-21 23:43:52 +00001828 // (C++ 4.4p4):
1829 // A conversion can add cv-qualifiers at levels other than the first
1830 // in multi-level pointers, subject to the following rules: [...]
1831 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001832 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001833 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001834 // Within each iteration of the loop, we check the qualifiers to
1835 // determine if this still looks like a qualification
1836 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001837 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001838 // until there are no more pointers or pointers-to-members left to
1839 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001840 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001841
1842 // -- for every j > 0, if const is in cv 1,j then const is in cv
1843 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001844 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001845 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001846
Douglas Gregor9a657932008-10-21 23:43:52 +00001847 // -- if the cv 1,j and cv 2,j are different, then const is in
1848 // every cv for 0 < k < j.
1849 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001850 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001851 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001852
Douglas Gregor9a657932008-10-21 23:43:52 +00001853 // Keep track of whether all prior cv-qualifiers in the "to" type
1854 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001855 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001856 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001857 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001858
1859 // We are left with FromType and ToType being the pointee types
1860 // after unwrapping the original FromType and ToType the same number
1861 // of types. If we unwrapped any pointers, and if FromType and
1862 // ToType have the same unqualified type (since we checked
1863 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001864 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001865}
1866
Douglas Gregor576e98c2009-01-30 23:27:23 +00001867/// Determines whether there is a user-defined conversion sequence
1868/// (C++ [over.ics.user]) that converts expression From to the type
1869/// ToType. If such a conversion exists, User will contain the
1870/// user-defined conversion sequence that performs such a conversion
1871/// and this routine will return true. Otherwise, this routine returns
1872/// false and User is unspecified.
1873///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001874/// \param AllowExplicit true if the conversion should consider C++0x
1875/// "explicit" conversion functions as well as non-explicit conversion
1876/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001877OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1878 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001879 OverloadCandidateSet& CandidateSet,
1880 bool AllowExplicit) {
1881 // Whether we will only visit constructors.
1882 bool ConstructorsOnly = false;
1883
1884 // If the type we are conversion to is a class type, enumerate its
1885 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001886 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001887 // C++ [over.match.ctor]p1:
1888 // When objects of class type are direct-initialized (8.5), or
1889 // copy-initialized from an expression of the same or a
1890 // derived class type (8.5), overload resolution selects the
1891 // constructor. [...] For copy-initialization, the candidate
1892 // functions are all the converting constructors (12.3.1) of
1893 // that class. The argument list is the expression-list within
1894 // the parentheses of the initializer.
1895 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1896 (From->getType()->getAs<RecordType>() &&
1897 IsDerivedFrom(From->getType(), ToType)))
1898 ConstructorsOnly = true;
1899
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001900 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1901 // We're not going to find any constructors.
1902 } else if (CXXRecordDecl *ToRecordDecl
1903 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001904 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00001905 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001906 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001907 NamedDecl *D = *Con;
1908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1909
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001910 // Find the constructor (which may be a template).
1911 CXXConstructorDecl *Constructor = 0;
1912 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001913 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001914 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001915 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1917 else
John McCalla0296f72010-03-19 07:35:19 +00001918 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001919
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001920 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001921 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001922 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001923 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001924 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001925 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001926 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001927 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001928 // Allow one user-defined conversion when user specifies a
1929 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001930 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001931 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001932 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001933 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001934 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001935 }
1936 }
1937
Douglas Gregor5ab11652010-04-17 22:01:05 +00001938 // Enumerate conversion functions, if we're allowed to.
1939 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001940 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001941 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001942 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001943 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001944 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001945 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001946 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1947 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001948 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001949 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001950 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001951 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001952 DeclAccessPair FoundDecl = I.getPair();
1953 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001954 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1955 if (isa<UsingShadowDecl>(D))
1956 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1957
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001958 CXXConversionDecl *Conv;
1959 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001960 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1961 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001962 else
John McCallda4458e2010-03-31 01:36:47 +00001963 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001964
1965 if (AllowExplicit || !Conv->isExplicit()) {
1966 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001967 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001968 ActingContext, From, ToType,
1969 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001970 else
John McCalla0296f72010-03-19 07:35:19 +00001971 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001972 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001973 }
1974 }
1975 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001976 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001977
1978 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001979 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001980 case OR_Success:
1981 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001982 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001983 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1984 // C++ [over.ics.user]p1:
1985 // If the user-defined conversion is specified by a
1986 // constructor (12.3.1), the initial standard conversion
1987 // sequence converts the source type to the type required by
1988 // the argument of the constructor.
1989 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001990 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001991 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001992 User.EllipsisConversion = true;
1993 else {
1994 User.Before = Best->Conversions[0].Standard;
1995 User.EllipsisConversion = false;
1996 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001997 User.ConversionFunction = Constructor;
1998 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001999 User.After.setFromType(
2000 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002001 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002002 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002003 } else if (CXXConversionDecl *Conversion
2004 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2005 // C++ [over.ics.user]p1:
2006 //
2007 // [...] If the user-defined conversion is specified by a
2008 // conversion function (12.3.2), the initial standard
2009 // conversion sequence converts the source type to the
2010 // implicit object parameter of the conversion function.
2011 User.Before = Best->Conversions[0].Standard;
2012 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002013 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002014
2015 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002016 // The second standard conversion sequence converts the
2017 // result of the user-defined conversion to the target type
2018 // for the sequence. Since an implicit conversion sequence
2019 // is an initialization, the special rules for
2020 // initialization by user-defined conversion apply when
2021 // selecting the best user-defined conversion for a
2022 // user-defined conversion sequence (see 13.3.3 and
2023 // 13.3.3.1).
2024 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002025 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002026 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002027 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002028 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002031 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002032 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002033 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002034 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002035 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002036
2037 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002038 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002039 }
2040
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002041 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002042}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002043
2044bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002045Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002046 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002047 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002048 OverloadingResult OvResult =
2049 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002050 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002051 if (OvResult == OR_Ambiguous)
2052 Diag(From->getSourceRange().getBegin(),
2053 diag::err_typecheck_ambiguous_condition)
2054 << From->getType() << ToType << From->getSourceRange();
2055 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2056 Diag(From->getSourceRange().getBegin(),
2057 diag::err_typecheck_nonviable_condition)
2058 << From->getType() << ToType << From->getSourceRange();
2059 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002060 return false;
John McCallad907772010-01-12 07:18:19 +00002061 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002062 return true;
2063}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002064
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002065/// CompareImplicitConversionSequences - Compare two implicit
2066/// conversion sequences to determine whether one is better than the
2067/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002068ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2070 const ImplicitConversionSequence& ICS2)
2071{
2072 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2073 // conversion sequences (as defined in 13.3.3.1)
2074 // -- a standard conversion sequence (13.3.3.1.1) is a better
2075 // conversion sequence than a user-defined conversion sequence or
2076 // an ellipsis conversion sequence, and
2077 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2078 // conversion sequence than an ellipsis conversion sequence
2079 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002080 //
John McCall0d1da222010-01-12 00:44:57 +00002081 // C++0x [over.best.ics]p10:
2082 // For the purpose of ranking implicit conversion sequences as
2083 // described in 13.3.3.2, the ambiguous conversion sequence is
2084 // treated as a user-defined sequence that is indistinguishable
2085 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002086 if (ICS1.getKindRank() < ICS2.getKindRank())
2087 return ImplicitConversionSequence::Better;
2088 else if (ICS2.getKindRank() < ICS1.getKindRank())
2089 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002090
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002091 // The following checks require both conversion sequences to be of
2092 // the same kind.
2093 if (ICS1.getKind() != ICS2.getKind())
2094 return ImplicitConversionSequence::Indistinguishable;
2095
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002096 // Two implicit conversion sequences of the same form are
2097 // indistinguishable conversion sequences unless one of the
2098 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002099 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002100 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002101 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002102 // User-defined conversion sequence U1 is a better conversion
2103 // sequence than another user-defined conversion sequence U2 if
2104 // they contain the same user-defined conversion function or
2105 // constructor and if the second standard conversion sequence of
2106 // U1 is better than the second standard conversion sequence of
2107 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002108 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002109 ICS2.UserDefined.ConversionFunction)
2110 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2111 ICS2.UserDefined.After);
2112 }
2113
2114 return ImplicitConversionSequence::Indistinguishable;
2115}
2116
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002117static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2118 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2119 Qualifiers Quals;
2120 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2121 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2122 }
2123
2124 return Context.hasSameUnqualifiedType(T1, T2);
2125}
2126
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002127// Per 13.3.3.2p3, compare the given standard conversion sequences to
2128// determine if one is a proper subset of the other.
2129static ImplicitConversionSequence::CompareKind
2130compareStandardConversionSubsets(ASTContext &Context,
2131 const StandardConversionSequence& SCS1,
2132 const StandardConversionSequence& SCS2) {
2133 ImplicitConversionSequence::CompareKind Result
2134 = ImplicitConversionSequence::Indistinguishable;
2135
Douglas Gregore87561a2010-05-23 22:10:15 +00002136 // the identity conversion sequence is considered to be a subsequence of
2137 // any non-identity conversion sequence
2138 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2139 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2140 return ImplicitConversionSequence::Better;
2141 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2142 return ImplicitConversionSequence::Worse;
2143 }
2144
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002145 if (SCS1.Second != SCS2.Second) {
2146 if (SCS1.Second == ICK_Identity)
2147 Result = ImplicitConversionSequence::Better;
2148 else if (SCS2.Second == ICK_Identity)
2149 Result = ImplicitConversionSequence::Worse;
2150 else
2151 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002152 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002153 return ImplicitConversionSequence::Indistinguishable;
2154
2155 if (SCS1.Third == SCS2.Third) {
2156 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2157 : ImplicitConversionSequence::Indistinguishable;
2158 }
2159
2160 if (SCS1.Third == ICK_Identity)
2161 return Result == ImplicitConversionSequence::Worse
2162 ? ImplicitConversionSequence::Indistinguishable
2163 : ImplicitConversionSequence::Better;
2164
2165 if (SCS2.Third == ICK_Identity)
2166 return Result == ImplicitConversionSequence::Better
2167 ? ImplicitConversionSequence::Indistinguishable
2168 : ImplicitConversionSequence::Worse;
2169
2170 return ImplicitConversionSequence::Indistinguishable;
2171}
2172
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002173/// CompareStandardConversionSequences - Compare two standard
2174/// conversion sequences to determine whether one is better than the
2175/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002176ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002177Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2178 const StandardConversionSequence& SCS2)
2179{
2180 // Standard conversion sequence S1 is a better conversion sequence
2181 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2182
2183 // -- S1 is a proper subsequence of S2 (comparing the conversion
2184 // sequences in the canonical form defined by 13.3.3.1.1,
2185 // excluding any Lvalue Transformation; the identity conversion
2186 // sequence is considered to be a subsequence of any
2187 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002188 if (ImplicitConversionSequence::CompareKind CK
2189 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2190 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002191
2192 // -- the rank of S1 is better than the rank of S2 (by the rules
2193 // defined below), or, if not that,
2194 ImplicitConversionRank Rank1 = SCS1.getRank();
2195 ImplicitConversionRank Rank2 = SCS2.getRank();
2196 if (Rank1 < Rank2)
2197 return ImplicitConversionSequence::Better;
2198 else if (Rank2 < Rank1)
2199 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002200
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002201 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2202 // are indistinguishable unless one of the following rules
2203 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002204
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002205 // A conversion that is not a conversion of a pointer, or
2206 // pointer to member, to bool is better than another conversion
2207 // that is such a conversion.
2208 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2209 return SCS2.isPointerConversionToBool()
2210 ? ImplicitConversionSequence::Better
2211 : ImplicitConversionSequence::Worse;
2212
Douglas Gregor5c407d92008-10-23 00:40:37 +00002213 // C++ [over.ics.rank]p4b2:
2214 //
2215 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002216 // conversion of B* to A* is better than conversion of B* to
2217 // void*, and conversion of A* to void* is better than conversion
2218 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002219 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002220 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002221 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002222 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002223 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2224 // Exactly one of the conversion sequences is a conversion to
2225 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002226 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2227 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002228 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2229 // Neither conversion sequence converts to a void pointer; compare
2230 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002231 if (ImplicitConversionSequence::CompareKind DerivedCK
2232 = CompareDerivedToBaseConversions(SCS1, SCS2))
2233 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002234 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2235 // Both conversion sequences are conversions to void
2236 // pointers. Compare the source types to determine if there's an
2237 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002238 QualType FromType1 = SCS1.getFromType();
2239 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002240
2241 // Adjust the types we're converting from via the array-to-pointer
2242 // conversion, if we need to.
2243 if (SCS1.First == ICK_Array_To_Pointer)
2244 FromType1 = Context.getArrayDecayedType(FromType1);
2245 if (SCS2.First == ICK_Array_To_Pointer)
2246 FromType2 = Context.getArrayDecayedType(FromType2);
2247
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002248 QualType FromPointee1
2249 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2250 QualType FromPointee2
2251 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002252
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002253 if (IsDerivedFrom(FromPointee2, FromPointee1))
2254 return ImplicitConversionSequence::Better;
2255 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2256 return ImplicitConversionSequence::Worse;
2257
2258 // Objective-C++: If one interface is more specific than the
2259 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002260 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2261 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002262 if (FromIface1 && FromIface1) {
2263 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2264 return ImplicitConversionSequence::Better;
2265 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2266 return ImplicitConversionSequence::Worse;
2267 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002268 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002269
2270 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2271 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002272 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002273 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002274 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002275
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002276 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002277 // C++0x [over.ics.rank]p3b4:
2278 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2279 // implicit object parameter of a non-static member function declared
2280 // without a ref-qualifier, and S1 binds an rvalue reference to an
2281 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002282 // FIXME: We don't know if we're dealing with the implicit object parameter,
2283 // or if the member function in this case has a ref qualifier.
2284 // (Of course, we don't have ref qualifiers yet.)
2285 if (SCS1.RRefBinding != SCS2.RRefBinding)
2286 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2287 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002288
2289 // C++ [over.ics.rank]p3b4:
2290 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2291 // which the references refer are the same type except for
2292 // top-level cv-qualifiers, and the type to which the reference
2293 // initialized by S2 refers is more cv-qualified than the type
2294 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002295 QualType T1 = SCS1.getToType(2);
2296 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002297 T1 = Context.getCanonicalType(T1);
2298 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002299 Qualifiers T1Quals, T2Quals;
2300 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2301 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2302 if (UnqualT1 == UnqualT2) {
2303 // If the type is an array type, promote the element qualifiers to the type
2304 // for comparison.
2305 if (isa<ArrayType>(T1) && T1Quals)
2306 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2307 if (isa<ArrayType>(T2) && T2Quals)
2308 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002309 if (T2.isMoreQualifiedThan(T1))
2310 return ImplicitConversionSequence::Better;
2311 else if (T1.isMoreQualifiedThan(T2))
2312 return ImplicitConversionSequence::Worse;
2313 }
2314 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002315
2316 return ImplicitConversionSequence::Indistinguishable;
2317}
2318
2319/// CompareQualificationConversions - Compares two standard conversion
2320/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002321/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2322ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002323Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002324 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002325 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002326 // -- S1 and S2 differ only in their qualification conversion and
2327 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2328 // cv-qualification signature of type T1 is a proper subset of
2329 // the cv-qualification signature of type T2, and S1 is not the
2330 // deprecated string literal array-to-pointer conversion (4.2).
2331 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2332 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2333 return ImplicitConversionSequence::Indistinguishable;
2334
2335 // FIXME: the example in the standard doesn't use a qualification
2336 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002337 QualType T1 = SCS1.getToType(2);
2338 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002339 T1 = Context.getCanonicalType(T1);
2340 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002341 Qualifiers T1Quals, T2Quals;
2342 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2343 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002344
2345 // If the types are the same, we won't learn anything by unwrapped
2346 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002347 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002348 return ImplicitConversionSequence::Indistinguishable;
2349
Chandler Carruth607f38e2009-12-29 07:16:59 +00002350 // If the type is an array type, promote the element qualifiers to the type
2351 // for comparison.
2352 if (isa<ArrayType>(T1) && T1Quals)
2353 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2354 if (isa<ArrayType>(T2) && T2Quals)
2355 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2356
Mike Stump11289f42009-09-09 15:08:12 +00002357 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002358 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002359 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002360 // Within each iteration of the loop, we check the qualifiers to
2361 // determine if this still looks like a qualification
2362 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002363 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002364 // until there are no more pointers or pointers-to-members left
2365 // to unwrap. This essentially mimics what
2366 // IsQualificationConversion does, but here we're checking for a
2367 // strict subset of qualifiers.
2368 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2369 // The qualifiers are the same, so this doesn't tell us anything
2370 // about how the sequences rank.
2371 ;
2372 else if (T2.isMoreQualifiedThan(T1)) {
2373 // T1 has fewer qualifiers, so it could be the better sequence.
2374 if (Result == ImplicitConversionSequence::Worse)
2375 // Neither has qualifiers that are a subset of the other's
2376 // qualifiers.
2377 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002379 Result = ImplicitConversionSequence::Better;
2380 } else if (T1.isMoreQualifiedThan(T2)) {
2381 // T2 has fewer qualifiers, so it could be the better sequence.
2382 if (Result == ImplicitConversionSequence::Better)
2383 // Neither has qualifiers that are a subset of the other's
2384 // qualifiers.
2385 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002386
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002387 Result = ImplicitConversionSequence::Worse;
2388 } else {
2389 // Qualifiers are disjoint.
2390 return ImplicitConversionSequence::Indistinguishable;
2391 }
2392
2393 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002394 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002395 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002396 }
2397
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002398 // Check that the winning standard conversion sequence isn't using
2399 // the deprecated string literal array to pointer conversion.
2400 switch (Result) {
2401 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002402 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002403 Result = ImplicitConversionSequence::Indistinguishable;
2404 break;
2405
2406 case ImplicitConversionSequence::Indistinguishable:
2407 break;
2408
2409 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002410 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002411 Result = ImplicitConversionSequence::Indistinguishable;
2412 break;
2413 }
2414
2415 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002416}
2417
Douglas Gregor5c407d92008-10-23 00:40:37 +00002418/// CompareDerivedToBaseConversions - Compares two standard conversion
2419/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002420/// various kinds of derived-to-base conversions (C++
2421/// [over.ics.rank]p4b3). As part of these checks, we also look at
2422/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002423ImplicitConversionSequence::CompareKind
2424Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2425 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002426 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002427 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002428 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002429 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002430
2431 // Adjust the types we're converting from via the array-to-pointer
2432 // conversion, if we need to.
2433 if (SCS1.First == ICK_Array_To_Pointer)
2434 FromType1 = Context.getArrayDecayedType(FromType1);
2435 if (SCS2.First == ICK_Array_To_Pointer)
2436 FromType2 = Context.getArrayDecayedType(FromType2);
2437
2438 // Canonicalize all of the types.
2439 FromType1 = Context.getCanonicalType(FromType1);
2440 ToType1 = Context.getCanonicalType(ToType1);
2441 FromType2 = Context.getCanonicalType(FromType2);
2442 ToType2 = Context.getCanonicalType(ToType2);
2443
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002444 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002445 //
2446 // If class B is derived directly or indirectly from class A and
2447 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002448 //
2449 // For Objective-C, we let A, B, and C also be Objective-C
2450 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002451
2452 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002453 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002454 SCS2.Second == ICK_Pointer_Conversion &&
2455 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2456 FromType1->isPointerType() && FromType2->isPointerType() &&
2457 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002458 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002459 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002460 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002461 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002462 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002463 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002464 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002465 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002466
John McCall8b07ec22010-05-15 11:32:37 +00002467 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2468 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2469 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2470 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002471
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002472 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002473 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2474 if (IsDerivedFrom(ToPointee1, ToPointee2))
2475 return ImplicitConversionSequence::Better;
2476 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2477 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002478
2479 if (ToIface1 && ToIface2) {
2480 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2481 return ImplicitConversionSequence::Better;
2482 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2483 return ImplicitConversionSequence::Worse;
2484 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002485 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002486
2487 // -- conversion of B* to A* is better than conversion of C* to A*,
2488 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2489 if (IsDerivedFrom(FromPointee2, FromPointee1))
2490 return ImplicitConversionSequence::Better;
2491 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2492 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002493
Douglas Gregor237f96c2008-11-26 23:31:11 +00002494 if (FromIface1 && FromIface2) {
2495 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2496 return ImplicitConversionSequence::Better;
2497 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2498 return ImplicitConversionSequence::Worse;
2499 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002500 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002501 }
2502
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002503 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002504 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2505 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2506 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2507 const MemberPointerType * FromMemPointer1 =
2508 FromType1->getAs<MemberPointerType>();
2509 const MemberPointerType * ToMemPointer1 =
2510 ToType1->getAs<MemberPointerType>();
2511 const MemberPointerType * FromMemPointer2 =
2512 FromType2->getAs<MemberPointerType>();
2513 const MemberPointerType * ToMemPointer2 =
2514 ToType2->getAs<MemberPointerType>();
2515 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2516 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2517 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2518 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2519 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2520 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2521 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2522 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002523 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002524 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2525 if (IsDerivedFrom(ToPointee1, ToPointee2))
2526 return ImplicitConversionSequence::Worse;
2527 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2528 return ImplicitConversionSequence::Better;
2529 }
2530 // conversion of B::* to C::* is better than conversion of A::* to C::*
2531 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2532 if (IsDerivedFrom(FromPointee1, FromPointee2))
2533 return ImplicitConversionSequence::Better;
2534 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2535 return ImplicitConversionSequence::Worse;
2536 }
2537 }
2538
Douglas Gregor5ab11652010-04-17 22:01:05 +00002539 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002540 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002541 // -- binding of an expression of type C to a reference of type
2542 // B& is better than binding an expression of type C to a
2543 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002544 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2545 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002546 if (IsDerivedFrom(ToType1, ToType2))
2547 return ImplicitConversionSequence::Better;
2548 else if (IsDerivedFrom(ToType2, ToType1))
2549 return ImplicitConversionSequence::Worse;
2550 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002551
Douglas Gregor2fe98832008-11-03 19:09:14 +00002552 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002553 // -- binding of an expression of type B to a reference of type
2554 // A& is better than binding an expression of type C to a
2555 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002556 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2557 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002558 if (IsDerivedFrom(FromType2, FromType1))
2559 return ImplicitConversionSequence::Better;
2560 else if (IsDerivedFrom(FromType1, FromType2))
2561 return ImplicitConversionSequence::Worse;
2562 }
2563 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002564
Douglas Gregor5c407d92008-10-23 00:40:37 +00002565 return ImplicitConversionSequence::Indistinguishable;
2566}
2567
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002568/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2569/// determine whether they are reference-related,
2570/// reference-compatible, reference-compatible with added
2571/// qualification, or incompatible, for use in C++ initialization by
2572/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2573/// type, and the first type (T1) is the pointee type of the reference
2574/// type being initialized.
2575Sema::ReferenceCompareResult
2576Sema::CompareReferenceRelationship(SourceLocation Loc,
2577 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002578 bool &DerivedToBase,
2579 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002580 assert(!OrigT1->isReferenceType() &&
2581 "T1 must be the pointee type of the reference type");
2582 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2583
2584 QualType T1 = Context.getCanonicalType(OrigT1);
2585 QualType T2 = Context.getCanonicalType(OrigT2);
2586 Qualifiers T1Quals, T2Quals;
2587 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2588 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2589
2590 // C++ [dcl.init.ref]p4:
2591 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2592 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2593 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002594 DerivedToBase = false;
2595 ObjCConversion = false;
2596 if (UnqualT1 == UnqualT2) {
2597 // Nothing to do.
2598 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002599 IsDerivedFrom(UnqualT2, UnqualT1))
2600 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002601 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2602 UnqualT2->isObjCObjectOrInterfaceType() &&
2603 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2604 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002605 else
2606 return Ref_Incompatible;
2607
2608 // At this point, we know that T1 and T2 are reference-related (at
2609 // least).
2610
2611 // If the type is an array type, promote the element qualifiers to the type
2612 // for comparison.
2613 if (isa<ArrayType>(T1) && T1Quals)
2614 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2615 if (isa<ArrayType>(T2) && T2Quals)
2616 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2617
2618 // C++ [dcl.init.ref]p4:
2619 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2620 // reference-related to T2 and cv1 is the same cv-qualification
2621 // as, or greater cv-qualification than, cv2. For purposes of
2622 // overload resolution, cases for which cv1 is greater
2623 // cv-qualification than cv2 are identified as
2624 // reference-compatible with added qualification (see 13.3.3.2).
2625 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2626 return Ref_Compatible;
2627 else if (T1.isMoreQualifiedThan(T2))
2628 return Ref_Compatible_With_Added_Qualification;
2629 else
2630 return Ref_Related;
2631}
2632
Sebastian Redld92badf2010-06-30 18:13:39 +00002633/// \brief Look for a user-defined conversion to an lvalue reference-compatible
2634/// with DeclType. Return true if something definite is found.
2635static bool
2636FindConversionToLValue(Sema &S, ImplicitConversionSequence &ICS,
2637 QualType DeclType, SourceLocation DeclLoc,
2638 Expr *Init, QualType T2, bool AllowExplicit) {
2639 assert(T2->isRecordType() && "Can only find conversions of record types.");
2640 CXXRecordDecl *T2RecordDecl
2641 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2642
2643 OverloadCandidateSet CandidateSet(DeclLoc);
2644 const UnresolvedSetImpl *Conversions
2645 = T2RecordDecl->getVisibleConversionFunctions();
2646 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2647 E = Conversions->end(); I != E; ++I) {
2648 NamedDecl *D = *I;
2649 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2650 if (isa<UsingShadowDecl>(D))
2651 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2652
2653 FunctionTemplateDecl *ConvTemplate
2654 = dyn_cast<FunctionTemplateDecl>(D);
2655 CXXConversionDecl *Conv;
2656 if (ConvTemplate)
2657 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2658 else
2659 Conv = cast<CXXConversionDecl>(D);
2660
2661 // If the conversion function doesn't return a reference type,
2662 // it can't be considered for this conversion. An rvalue reference
2663 // is only acceptable if its referencee is a function type.
2664 const ReferenceType *RefType =
2665 Conv->getConversionType()->getAs<ReferenceType>();
2666 if (RefType && (RefType->isLValueReferenceType() ||
2667 RefType->getPointeeType()->isFunctionType()) &&
2668 (AllowExplicit || !Conv->isExplicit())) {
2669 if (ConvTemplate)
2670 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2671 Init, DeclType, CandidateSet);
2672 else
2673 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2674 DeclType, CandidateSet);
2675 }
2676 }
2677
2678 OverloadCandidateSet::iterator Best;
2679 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2680 case OR_Success:
2681 // C++ [over.ics.ref]p1:
2682 //
2683 // [...] If the parameter binds directly to the result of
2684 // applying a conversion function to the argument
2685 // expression, the implicit conversion sequence is a
2686 // user-defined conversion sequence (13.3.3.1.2), with the
2687 // second standard conversion sequence either an identity
2688 // conversion or, if the conversion function returns an
2689 // entity of a type that is a derived class of the parameter
2690 // type, a derived-to-base Conversion.
2691 if (!Best->FinalConversion.DirectBinding)
2692 return false;
2693
2694 ICS.setUserDefined();
2695 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2696 ICS.UserDefined.After = Best->FinalConversion;
2697 ICS.UserDefined.ConversionFunction = Best->Function;
2698 ICS.UserDefined.EllipsisConversion = false;
2699 assert(ICS.UserDefined.After.ReferenceBinding &&
2700 ICS.UserDefined.After.DirectBinding &&
2701 "Expected a direct reference binding!");
2702 return true;
2703
2704 case OR_Ambiguous:
2705 ICS.setAmbiguous();
2706 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2707 Cand != CandidateSet.end(); ++Cand)
2708 if (Cand->Viable)
2709 ICS.Ambiguous.addConversion(Cand->Function);
2710 return true;
2711
2712 case OR_No_Viable_Function:
2713 case OR_Deleted:
2714 // There was no suitable conversion, or we found a deleted
2715 // conversion; continue with other checks.
2716 return false;
2717 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002718
2719 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002720}
2721
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002722/// \brief Compute an implicit conversion sequence for reference
2723/// initialization.
2724static ImplicitConversionSequence
2725TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2726 SourceLocation DeclLoc,
2727 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002728 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002729 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2730
2731 // Most paths end in a failed conversion.
2732 ImplicitConversionSequence ICS;
2733 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2734
2735 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2736 QualType T2 = Init->getType();
2737
2738 // If the initializer is the address of an overloaded function, try
2739 // to resolve the overloaded function. If all goes well, T2 is the
2740 // type of the resulting function.
2741 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2742 DeclAccessPair Found;
2743 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2744 false, Found))
2745 T2 = Fn->getType();
2746 }
2747
2748 // Compute some basic properties of the types and the initializer.
2749 bool isRValRef = DeclType->isRValueReferenceType();
2750 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002751 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002752 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002753 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002754 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2755 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002756
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002757
Sebastian Redld92badf2010-06-30 18:13:39 +00002758 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002759 // A reference to type "cv1 T1" is initialized by an expression
2760 // of type "cv2 T2" as follows:
2761
Sebastian Redld92badf2010-06-30 18:13:39 +00002762 // -- If reference is an lvalue reference and the initializer expression
2763 // The next bullet point (T1 is a function) is pretty much equivalent to this
2764 // one, so it's handled here.
2765 if (!isRValRef || T1->isFunctionType()) {
2766 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2767 // reference-compatible with "cv2 T2," or
2768 //
2769 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2770 if (InitCategory.isLValue() &&
2771 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002772 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002773 // When a parameter of reference type binds directly (8.5.3)
2774 // to an argument expression, the implicit conversion sequence
2775 // is the identity conversion, unless the argument expression
2776 // has a type that is a derived class of the parameter type,
2777 // in which case the implicit conversion sequence is a
2778 // derived-to-base Conversion (13.3.3.1).
2779 ICS.setStandard();
2780 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002781 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2782 : ObjCConversion? ICK_Compatible_Conversion
2783 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002784 ICS.Standard.Third = ICK_Identity;
2785 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2786 ICS.Standard.setToType(0, T2);
2787 ICS.Standard.setToType(1, T1);
2788 ICS.Standard.setToType(2, T1);
2789 ICS.Standard.ReferenceBinding = true;
2790 ICS.Standard.DirectBinding = true;
2791 ICS.Standard.RRefBinding = isRValRef;
2792 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002793
Sebastian Redld92badf2010-06-30 18:13:39 +00002794 // Nothing more to do: the inaccessibility/ambiguity check for
2795 // derived-to-base conversions is suppressed when we're
2796 // computing the implicit conversion sequence (C++
2797 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002798 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002799 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002800
Sebastian Redld92badf2010-06-30 18:13:39 +00002801 // -- has a class type (i.e., T2 is a class type), where T1 is
2802 // not reference-related to T2, and can be implicitly
2803 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2804 // is reference-compatible with "cv3 T3" 92) (this
2805 // conversion is selected by enumerating the applicable
2806 // conversion functions (13.3.1.6) and choosing the best
2807 // one through overload resolution (13.3)),
2808 if (!SuppressUserConversions && T2->isRecordType() &&
2809 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2810 RefRelationship == Sema::Ref_Incompatible) {
2811 if (FindConversionToLValue(S, ICS, DeclType, DeclLoc,
2812 Init, T2, AllowExplicit))
2813 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002814 }
2815 }
2816
Sebastian Redld92badf2010-06-30 18:13:39 +00002817 // -- Otherwise, the reference shall be an lvalue reference to a
2818 // non-volatile const type (i.e., cv1 shall be const), or the reference
2819 // shall be an rvalue reference and the initializer expression shall be
2820 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002821 //
2822 // We actually handle one oddity of C++ [over.ics.ref] at this
2823 // point, which is that, due to p2 (which short-circuits reference
2824 // binding by only attempting a simple conversion for non-direct
2825 // bindings) and p3's strange wording, we allow a const volatile
2826 // reference to bind to an rvalue. Hence the check for the presence
2827 // of "const" rather than checking for "const" being the only
2828 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002829 // This is also the point where rvalue references and lvalue inits no longer
2830 // go together.
2831 if ((!isRValRef && !T1.isConstQualified()) ||
2832 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002833 return ICS;
2834
Sebastian Redld92badf2010-06-30 18:13:39 +00002835 // -- If T1 is a function type, then
2836 // -- if T2 is the same type as T1, the reference is bound to the
2837 // initializer expression lvalue;
2838 // -- if T2 is a class type and the initializer expression can be
2839 // implicitly converted to an lvalue of type T1 [...], the
2840 // reference is bound to the function lvalue that is the result
2841 // of the conversion;
2842 // This is the same as for the lvalue case above, so it was handled there.
2843 // -- otherwise, the program is ill-formed.
2844 // This is the one difference to the lvalue case.
2845 if (T1->isFunctionType())
2846 return ICS;
2847
2848 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002849 // -- the initializer expression is an rvalue and "cv1 T1"
2850 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002851 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002852 // -- T1 is not reference-related to T2 and the initializer
2853 // expression can be implicitly converted to an rvalue
2854 // of type "cv3 T3" (this conversion is selected by
2855 // enumerating the applicable conversion functions
2856 // (13.3.1.6) and choosing the best one through overload
2857 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002858 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002859 // then the reference is bound to the initializer
2860 // expression rvalue in the first case and to the object
2861 // that is the result of the conversion in the second case
2862 // (or, in either case, to the appropriate base class
2863 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002864 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002865 // We're only checking the first case here, which is a direct
2866 // binding in C++0x but not in C++03.
Sebastian Redld92badf2010-06-30 18:13:39 +00002867 if (InitCategory.isRValue() && T2->isRecordType() &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002868 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2869 ICS.setStandard();
2870 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002871 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2872 : ObjCConversion? ICK_Compatible_Conversion
2873 : ICK_Identity;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002874 ICS.Standard.Third = ICK_Identity;
2875 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2876 ICS.Standard.setToType(0, T2);
2877 ICS.Standard.setToType(1, T1);
2878 ICS.Standard.setToType(2, T1);
2879 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002880 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002881 ICS.Standard.RRefBinding = isRValRef;
2882 ICS.Standard.CopyConstructor = 0;
2883 return ICS;
2884 }
2885
2886 // -- Otherwise, a temporary of type "cv1 T1" is created and
2887 // initialized from the initializer expression using the
2888 // rules for a non-reference copy initialization (8.5). The
2889 // reference is then bound to the temporary. If T1 is
2890 // reference-related to T2, cv1 must be the same
2891 // cv-qualification as, or greater cv-qualification than,
2892 // cv2; otherwise, the program is ill-formed.
2893 if (RefRelationship == Sema::Ref_Related) {
2894 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2895 // we would be reference-compatible or reference-compatible with
2896 // added qualification. But that wasn't the case, so the reference
2897 // initialization fails.
2898 return ICS;
2899 }
2900
2901 // If at least one of the types is a class type, the types are not
2902 // related, and we aren't allowed any user conversions, the
2903 // reference binding fails. This case is important for breaking
2904 // recursion, since TryImplicitConversion below will attempt to
2905 // create a temporary through the use of a copy constructor.
2906 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2907 (T1->isRecordType() || T2->isRecordType()))
2908 return ICS;
2909
2910 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002911 // When a parameter of reference type is not bound directly to
2912 // an argument expression, the conversion sequence is the one
2913 // required to convert the argument expression to the
2914 // underlying type of the reference according to
2915 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2916 // to copy-initializing a temporary of the underlying type with
2917 // the argument expression. Any difference in top-level
2918 // cv-qualification is subsumed by the initialization itself
2919 // and does not constitute a conversion.
2920 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2921 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002922 /*InOverloadResolution=*/false);
2923
2924 // Of course, that's still a reference binding.
2925 if (ICS.isStandard()) {
2926 ICS.Standard.ReferenceBinding = true;
2927 ICS.Standard.RRefBinding = isRValRef;
2928 } else if (ICS.isUserDefined()) {
2929 ICS.UserDefined.After.ReferenceBinding = true;
2930 ICS.UserDefined.After.RRefBinding = isRValRef;
2931 }
2932 return ICS;
2933}
2934
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002935/// TryCopyInitialization - Try to copy-initialize a value of type
2936/// ToType from the expression From. Return the implicit conversion
2937/// sequence required to pass this argument, which may be a bad
2938/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002939/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002940/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002941static ImplicitConversionSequence
2942TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002943 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002944 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002945 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002946 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002947 /*FIXME:*/From->getLocStart(),
2948 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002949 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002950
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002951 return S.TryImplicitConversion(From, ToType,
2952 SuppressUserConversions,
2953 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002954 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002955}
2956
Douglas Gregor436424c2008-11-18 23:14:02 +00002957/// TryObjectArgumentInitialization - Try to initialize the object
2958/// parameter of the given member function (@c Method) from the
2959/// expression @p From.
2960ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002961Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002962 CXXMethodDecl *Method,
2963 CXXRecordDecl *ActingContext) {
2964 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002965 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2966 // const volatile object.
2967 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2968 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2969 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002970
2971 // Set up the conversion sequence as a "bad" conversion, to allow us
2972 // to exit early.
2973 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002974
2975 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002976 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002977 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002978 FromType = PT->getPointeeType();
2979
2980 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002981
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002982 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002983 // where X is the class of which the function is a member
2984 // (C++ [over.match.funcs]p4). However, when finding an implicit
2985 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002986 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002987 // (C++ [over.match.funcs]p5). We perform a simplified version of
2988 // reference binding here, that allows class rvalues to bind to
2989 // non-constant references.
2990
2991 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2992 // with the implicit object parameter (C++ [over.match.funcs]p5).
2993 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002994 if (ImplicitParamType.getCVRQualifiers()
2995 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002996 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002997 ICS.setBad(BadConversionSequence::bad_qualifiers,
2998 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002999 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003000 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003001
3002 // Check that we have either the same type or a derived type. It
3003 // affects the conversion rank.
3004 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003005 ImplicitConversionKind SecondKind;
3006 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3007 SecondKind = ICK_Identity;
3008 } else if (IsDerivedFrom(FromType, ClassType))
3009 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003010 else {
John McCall65eb8792010-02-25 01:37:24 +00003011 ICS.setBad(BadConversionSequence::unrelated_class,
3012 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003013 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003014 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003015
3016 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003017 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003018 ICS.Standard.setAsIdentityConversion();
3019 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003020 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003021 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003022 ICS.Standard.ReferenceBinding = true;
3023 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003024 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003025 return ICS;
3026}
3027
3028/// PerformObjectArgumentInitialization - Perform initialization of
3029/// the implicit object parameter for the given Method with the given
3030/// expression.
3031bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003032Sema::PerformObjectArgumentInitialization(Expr *&From,
3033 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003034 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003035 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003036 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003037 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003038 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003039
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003040 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003041 FromRecordType = PT->getPointeeType();
3042 DestType = Method->getThisType(Context);
3043 } else {
3044 FromRecordType = From->getType();
3045 DestType = ImplicitParamRecordType;
3046 }
3047
John McCall6e9f8f62009-12-03 04:06:58 +00003048 // Note that we always use the true parent context when performing
3049 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003050 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003051 = TryObjectArgumentInitialization(From->getType(), Method,
3052 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003053 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003054 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003055 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003056 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003057
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003058 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003059 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003060
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003061 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003062 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003063 From->getType()->isPointerType() ?
3064 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003065 return false;
3066}
3067
Douglas Gregor5fb53972009-01-14 15:45:31 +00003068/// TryContextuallyConvertToBool - Attempt to contextually convert the
3069/// expression From to bool (C++0x [conv]p3).
3070ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003071 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003072 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003073 // FIXME: Are these flags correct?
3074 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003075 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003076 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003077}
3078
3079/// PerformContextuallyConvertToBool - Perform a contextual conversion
3080/// of the expression From to bool (C++0x [conv]p3).
3081bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3082 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003083 if (!ICS.isBad())
3084 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003085
Fariborz Jahanian76197412009-11-18 18:26:29 +00003086 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003087 return Diag(From->getSourceRange().getBegin(),
3088 diag::err_typecheck_bool_condition)
3089 << From->getType() << From->getSourceRange();
3090 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003091}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003092
3093/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3094/// expression From to 'id'.
3095ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003096 QualType Ty = Context.getObjCIdType();
3097 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003098 // FIXME: Are these flags correct?
3099 /*SuppressUserConversions=*/false,
3100 /*AllowExplicit=*/true,
3101 /*InOverloadResolution=*/false);
3102}
3103
3104/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3105/// of the expression From to 'id'.
3106bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003107 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003108 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3109 if (!ICS.isBad())
3110 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3111 return true;
3112}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003113
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003114/// \brief Attempt to convert the given expression to an integral or
3115/// enumeration type.
3116///
3117/// This routine will attempt to convert an expression of class type to an
3118/// integral or enumeration type, if that class type only has a single
3119/// conversion to an integral or enumeration type.
3120///
Douglas Gregor4799d032010-06-30 00:20:43 +00003121/// \param Loc The source location of the construct that requires the
3122/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003123///
Douglas Gregor4799d032010-06-30 00:20:43 +00003124/// \param FromE The expression we're converting from.
3125///
3126/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3127/// have integral or enumeration type.
3128///
3129/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3130/// incomplete class type.
3131///
3132/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3133/// explicit conversion function (because no implicit conversion functions
3134/// were available). This is a recovery mode.
3135///
3136/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3137/// showing which conversion was picked.
3138///
3139/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3140/// conversion function that could convert to integral or enumeration type.
3141///
3142/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3143/// usable conversion function.
3144///
3145/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3146/// function, which may be an extension in this case.
3147///
3148/// \returns The expression, converted to an integral or enumeration type if
3149/// successful.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003150Sema::OwningExprResult
3151Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3152 const PartialDiagnostic &NotIntDiag,
3153 const PartialDiagnostic &IncompleteDiag,
3154 const PartialDiagnostic &ExplicitConvDiag,
3155 const PartialDiagnostic &ExplicitConvNote,
3156 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003157 const PartialDiagnostic &AmbigNote,
3158 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003159 Expr *From = static_cast<Expr *>(FromE.get());
3160
3161 // We can't perform any more checking for type-dependent expressions.
3162 if (From->isTypeDependent())
3163 return move(FromE);
3164
3165 // If the expression already has integral or enumeration type, we're golden.
3166 QualType T = From->getType();
3167 if (T->isIntegralOrEnumerationType())
3168 return move(FromE);
3169
3170 // FIXME: Check for missing '()' if T is a function type?
3171
3172 // If we don't have a class type in C++, there's no way we can get an
3173 // expression of integral or enumeration type.
3174 const RecordType *RecordTy = T->getAs<RecordType>();
3175 if (!RecordTy || !getLangOptions().CPlusPlus) {
3176 Diag(Loc, NotIntDiag)
3177 << T << From->getSourceRange();
Douglas Gregor5823da32010-06-29 23:25:20 +00003178 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003179 }
3180
3181 // We must have a complete class type.
3182 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor4799d032010-06-30 00:20:43 +00003183 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003184
3185 // Look for a conversion to an integral or enumeration type.
3186 UnresolvedSet<4> ViableConversions;
3187 UnresolvedSet<4> ExplicitConversions;
3188 const UnresolvedSetImpl *Conversions
3189 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3190
3191 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3192 E = Conversions->end();
3193 I != E;
3194 ++I) {
3195 if (CXXConversionDecl *Conversion
3196 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3197 if (Conversion->getConversionType().getNonReferenceType()
3198 ->isIntegralOrEnumerationType()) {
3199 if (Conversion->isExplicit())
3200 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3201 else
3202 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3203 }
3204 }
3205
3206 switch (ViableConversions.size()) {
3207 case 0:
3208 if (ExplicitConversions.size() == 1) {
3209 DeclAccessPair Found = ExplicitConversions[0];
3210 CXXConversionDecl *Conversion
3211 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3212
3213 // The user probably meant to invoke the given explicit
3214 // conversion; use it.
3215 QualType ConvTy
3216 = Conversion->getConversionType().getNonReferenceType();
3217 std::string TypeStr;
3218 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3219
3220 Diag(Loc, ExplicitConvDiag)
3221 << T << ConvTy
3222 << FixItHint::CreateInsertion(From->getLocStart(),
3223 "static_cast<" + TypeStr + ">(")
3224 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3225 ")");
3226 Diag(Conversion->getLocation(), ExplicitConvNote)
3227 << ConvTy->isEnumeralType() << ConvTy;
3228
3229 // If we aren't in a SFINAE context, build a call to the
3230 // explicit conversion function.
3231 if (isSFINAEContext())
3232 return ExprError();
3233
3234 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3235 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3236 FromE = Owned(From);
3237 }
3238
3239 // We'll complain below about a non-integral condition type.
3240 break;
3241
3242 case 1: {
3243 // Apply this conversion.
3244 DeclAccessPair Found = ViableConversions[0];
3245 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003246
3247 CXXConversionDecl *Conversion
3248 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3249 QualType ConvTy
3250 = Conversion->getConversionType().getNonReferenceType();
3251 if (ConvDiag.getDiagID()) {
3252 if (isSFINAEContext())
3253 return ExprError();
3254
3255 Diag(Loc, ConvDiag)
3256 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3257 }
3258
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003259 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3260 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3261 FromE = Owned(From);
3262 break;
3263 }
3264
3265 default:
3266 Diag(Loc, AmbigDiag)
3267 << T << From->getSourceRange();
3268 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3269 CXXConversionDecl *Conv
3270 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3271 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3272 Diag(Conv->getLocation(), AmbigNote)
3273 << ConvTy->isEnumeralType() << ConvTy;
3274 }
Douglas Gregor5823da32010-06-29 23:25:20 +00003275 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003276 }
3277
Douglas Gregor5823da32010-06-29 23:25:20 +00003278 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003279 Diag(Loc, NotIntDiag)
3280 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003281
3282 return move(FromE);
3283}
3284
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003285/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003286/// candidate functions, using the given function call arguments. If
3287/// @p SuppressUserConversions, then don't allow user-defined
3288/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003289///
3290/// \para PartialOverloading true if we are performing "partial" overloading
3291/// based on an incomplete set of function arguments. This feature is used by
3292/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003293void
3294Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003295 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003296 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003297 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003298 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003299 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003300 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003301 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003302 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003303 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003304 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003305
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003306 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003307 if (!isa<CXXConstructorDecl>(Method)) {
3308 // If we get here, it's because we're calling a member function
3309 // that is named without a member access expression (e.g.,
3310 // "this->f") that was either written explicitly or created
3311 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003312 // function, e.g., X::f(). We use an empty type for the implied
3313 // object argument (C++ [over.call.func]p3), and the acting context
3314 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003315 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003316 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003317 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003318 return;
3319 }
3320 // We treat a constructor like a non-member function, since its object
3321 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003322 }
3323
Douglas Gregorff7028a2009-11-13 23:59:09 +00003324 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003325 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003326
Douglas Gregor27381f32009-11-23 12:27:39 +00003327 // Overload resolution is always an unevaluated context.
3328 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3329
Douglas Gregorffe14e32009-11-14 01:20:54 +00003330 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3331 // C++ [class.copy]p3:
3332 // A member function template is never instantiated to perform the copy
3333 // of a class object to an object of its class type.
3334 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3335 if (NumArgs == 1 &&
3336 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003337 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3338 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003339 return;
3340 }
3341
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003342 // Add this candidate
3343 CandidateSet.push_back(OverloadCandidate());
3344 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003345 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003346 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003347 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003348 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003349 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003350
3351 unsigned NumArgsInProto = Proto->getNumArgs();
3352
3353 // (C++ 13.3.2p2): A candidate function having fewer than m
3354 // parameters is viable only if it has an ellipsis in its parameter
3355 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003356 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3357 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003358 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003359 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003360 return;
3361 }
3362
3363 // (C++ 13.3.2p2): A candidate function having more than m parameters
3364 // is viable only if the (m+1)st parameter has a default argument
3365 // (8.3.6). For the purposes of overload resolution, the
3366 // parameter list is truncated on the right, so that there are
3367 // exactly m parameters.
3368 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003369 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003370 // Not enough arguments.
3371 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003372 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003373 return;
3374 }
3375
3376 // Determine the implicit conversion sequences for each of the
3377 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003378 Candidate.Conversions.resize(NumArgs);
3379 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3380 if (ArgIdx < NumArgsInProto) {
3381 // (C++ 13.3.2p3): for F to be a viable function, there shall
3382 // exist for each argument an implicit conversion sequence
3383 // (13.3.3.1) that converts that argument to the corresponding
3384 // parameter of F.
3385 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003386 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003387 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003388 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003389 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003390 if (Candidate.Conversions[ArgIdx].isBad()) {
3391 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003392 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003393 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003394 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003395 } else {
3396 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3397 // argument for which there is no corresponding parameter is
3398 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003399 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003400 }
3401 }
3402}
3403
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003404/// \brief Add all of the function declarations in the given function set to
3405/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003406void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003407 Expr **Args, unsigned NumArgs,
3408 OverloadCandidateSet& CandidateSet,
3409 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003410 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003411 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3412 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003413 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003414 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003415 cast<CXXMethodDecl>(FD)->getParent(),
3416 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003417 CandidateSet, SuppressUserConversions);
3418 else
John McCalla0296f72010-03-19 07:35:19 +00003419 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003420 SuppressUserConversions);
3421 } else {
John McCalla0296f72010-03-19 07:35:19 +00003422 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003423 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3424 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003425 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003426 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003427 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003428 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003429 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003430 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003431 else
John McCalla0296f72010-03-19 07:35:19 +00003432 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003433 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003434 Args, NumArgs, CandidateSet,
3435 SuppressUserConversions);
3436 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003437 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003438}
3439
John McCallf0f1cf02009-11-17 07:50:12 +00003440/// AddMethodCandidate - Adds a named decl (which is some kind of
3441/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003442void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003443 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003444 Expr **Args, unsigned NumArgs,
3445 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003446 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003447 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003448 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003449
3450 if (isa<UsingShadowDecl>(Decl))
3451 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3452
3453 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3454 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3455 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003456 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3457 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003458 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003459 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003460 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003461 } else {
John McCalla0296f72010-03-19 07:35:19 +00003462 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003463 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003464 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003465 }
3466}
3467
Douglas Gregor436424c2008-11-18 23:14:02 +00003468/// AddMethodCandidate - Adds the given C++ member function to the set
3469/// of candidate functions, using the given function call arguments
3470/// and the object argument (@c Object). For example, in a call
3471/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3472/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3473/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003474/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003475void
John McCalla0296f72010-03-19 07:35:19 +00003476Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003477 CXXRecordDecl *ActingContext, QualType ObjectType,
3478 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003479 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003480 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003481 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003482 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003483 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003484 assert(!isa<CXXConstructorDecl>(Method) &&
3485 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003486
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003487 if (!CandidateSet.isNewCandidate(Method))
3488 return;
3489
Douglas Gregor27381f32009-11-23 12:27:39 +00003490 // Overload resolution is always an unevaluated context.
3491 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3492
Douglas Gregor436424c2008-11-18 23:14:02 +00003493 // Add this candidate
3494 CandidateSet.push_back(OverloadCandidate());
3495 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003496 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003497 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003498 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003499 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003500
3501 unsigned NumArgsInProto = Proto->getNumArgs();
3502
3503 // (C++ 13.3.2p2): A candidate function having fewer than m
3504 // parameters is viable only if it has an ellipsis in its parameter
3505 // list (8.3.5).
3506 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3507 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003508 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003509 return;
3510 }
3511
3512 // (C++ 13.3.2p2): A candidate function having more than m parameters
3513 // is viable only if the (m+1)st parameter has a default argument
3514 // (8.3.6). For the purposes of overload resolution, the
3515 // parameter list is truncated on the right, so that there are
3516 // exactly m parameters.
3517 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3518 if (NumArgs < MinRequiredArgs) {
3519 // Not enough arguments.
3520 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003521 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003522 return;
3523 }
3524
3525 Candidate.Viable = true;
3526 Candidate.Conversions.resize(NumArgs + 1);
3527
John McCall6e9f8f62009-12-03 04:06:58 +00003528 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003529 // The implicit object argument is ignored.
3530 Candidate.IgnoreObjectArgument = true;
3531 else {
3532 // Determine the implicit conversion sequence for the object
3533 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003534 Candidate.Conversions[0]
3535 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003536 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003537 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003538 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003539 return;
3540 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003541 }
3542
3543 // Determine the implicit conversion sequences for each of the
3544 // arguments.
3545 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3546 if (ArgIdx < NumArgsInProto) {
3547 // (C++ 13.3.2p3): for F to be a viable function, there shall
3548 // exist for each argument an implicit conversion sequence
3549 // (13.3.3.1) that converts that argument to the corresponding
3550 // parameter of F.
3551 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003552 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003553 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003554 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003555 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003556 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003557 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003558 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003559 break;
3560 }
3561 } else {
3562 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3563 // argument for which there is no corresponding parameter is
3564 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003565 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003566 }
3567 }
3568}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003569
Douglas Gregor97628d62009-08-21 00:16:32 +00003570/// \brief Add a C++ member function template as a candidate to the candidate
3571/// set, using template argument deduction to produce an appropriate member
3572/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003573void
Douglas Gregor97628d62009-08-21 00:16:32 +00003574Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003575 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003576 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003577 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003578 QualType ObjectType,
3579 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003580 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003581 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003582 if (!CandidateSet.isNewCandidate(MethodTmpl))
3583 return;
3584
Douglas Gregor97628d62009-08-21 00:16:32 +00003585 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003586 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003587 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003588 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003589 // candidate functions in the usual way.113) A given name can refer to one
3590 // or more function templates and also to a set of overloaded non-template
3591 // functions. In such a case, the candidate functions generated from each
3592 // function template are combined with the set of non-template candidate
3593 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003594 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003595 FunctionDecl *Specialization = 0;
3596 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003597 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003598 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003599 CandidateSet.push_back(OverloadCandidate());
3600 OverloadCandidate &Candidate = CandidateSet.back();
3601 Candidate.FoundDecl = FoundDecl;
3602 Candidate.Function = MethodTmpl->getTemplatedDecl();
3603 Candidate.Viable = false;
3604 Candidate.FailureKind = ovl_fail_bad_deduction;
3605 Candidate.IsSurrogate = false;
3606 Candidate.IgnoreObjectArgument = false;
3607 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3608 Info);
3609 return;
3610 }
Mike Stump11289f42009-09-09 15:08:12 +00003611
Douglas Gregor97628d62009-08-21 00:16:32 +00003612 // Add the function template specialization produced by template argument
3613 // deduction as a candidate.
3614 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003615 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003616 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003617 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003618 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003619 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003620}
3621
Douglas Gregor05155d82009-08-21 23:19:43 +00003622/// \brief Add a C++ function template specialization as a candidate
3623/// in the candidate set, using template argument deduction to produce
3624/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003625void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003626Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003627 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003628 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003629 Expr **Args, unsigned NumArgs,
3630 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003631 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003632 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3633 return;
3634
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003635 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003636 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003637 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003638 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003639 // candidate functions in the usual way.113) A given name can refer to one
3640 // or more function templates and also to a set of overloaded non-template
3641 // functions. In such a case, the candidate functions generated from each
3642 // function template are combined with the set of non-template candidate
3643 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003644 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003645 FunctionDecl *Specialization = 0;
3646 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003647 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003648 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003649 CandidateSet.push_back(OverloadCandidate());
3650 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003651 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003652 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3653 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003654 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003655 Candidate.IsSurrogate = false;
3656 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003657 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3658 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003659 return;
3660 }
Mike Stump11289f42009-09-09 15:08:12 +00003661
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003662 // Add the function template specialization produced by template argument
3663 // deduction as a candidate.
3664 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003665 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003666 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003667}
Mike Stump11289f42009-09-09 15:08:12 +00003668
Douglas Gregora1f013e2008-11-07 22:36:19 +00003669/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003670/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003671/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003672/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003673/// (which may or may not be the same type as the type that the
3674/// conversion function produces).
3675void
3676Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003677 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003678 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003679 Expr *From, QualType ToType,
3680 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003681 assert(!Conversion->getDescribedFunctionTemplate() &&
3682 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003683 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003684 if (!CandidateSet.isNewCandidate(Conversion))
3685 return;
3686
Douglas Gregor27381f32009-11-23 12:27:39 +00003687 // Overload resolution is always an unevaluated context.
3688 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3689
Douglas Gregora1f013e2008-11-07 22:36:19 +00003690 // Add this candidate
3691 CandidateSet.push_back(OverloadCandidate());
3692 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003693 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003694 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003695 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003696 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003697 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003698 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003699 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003700
Douglas Gregor436424c2008-11-18 23:14:02 +00003701 // Determine the implicit conversion sequence for the implicit
3702 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003703 Candidate.Viable = true;
3704 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003705 Candidate.Conversions[0]
3706 = TryObjectArgumentInitialization(From->getType(), Conversion,
3707 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003708 // Conversion functions to a different type in the base class is visible in
3709 // the derived class. So, a derived to base conversion should not participate
3710 // in overload resolution.
3711 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3712 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003713 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003714 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003715 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003716 return;
3717 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003718
3719 // We won't go through a user-define type conversion function to convert a
3720 // derived to base as such conversions are given Conversion Rank. They only
3721 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3722 QualType FromCanon
3723 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3724 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3725 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3726 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003727 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003728 return;
3729 }
3730
Douglas Gregora1f013e2008-11-07 22:36:19 +00003731 // To determine what the conversion from the result of calling the
3732 // conversion function to the type we're eventually trying to
3733 // convert to (ToType), we need to synthesize a call to the
3734 // conversion function and attempt copy initialization from it. This
3735 // makes sure that we get the right semantics with respect to
3736 // lvalues/rvalues and the type. Fortunately, we can allocate this
3737 // call on the stack and we don't need its arguments to be
3738 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003739 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003740 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003741 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3742 Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003743 CastExpr::CK_FunctionToPointerDecay,
John McCallcf142162010-08-07 06:22:56 +00003744 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003745
3746 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003747 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3748 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003749 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003750 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003751 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003752 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003753 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003754 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003755 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003756
John McCall0d1da222010-01-12 00:44:57 +00003757 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003758 case ImplicitConversionSequence::StandardConversion:
3759 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003760
3761 // C++ [over.ics.user]p3:
3762 // If the user-defined conversion is specified by a specialization of a
3763 // conversion function template, the second standard conversion sequence
3764 // shall have exact match rank.
3765 if (Conversion->getPrimaryTemplate() &&
3766 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3767 Candidate.Viable = false;
3768 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3769 }
3770
Douglas Gregora1f013e2008-11-07 22:36:19 +00003771 break;
3772
3773 case ImplicitConversionSequence::BadConversion:
3774 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003775 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003776 break;
3777
3778 default:
Mike Stump11289f42009-09-09 15:08:12 +00003779 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003780 "Can only end up with a standard conversion sequence or failure");
3781 }
3782}
3783
Douglas Gregor05155d82009-08-21 23:19:43 +00003784/// \brief Adds a conversion function template specialization
3785/// candidate to the overload set, using template argument deduction
3786/// to deduce the template arguments of the conversion function
3787/// template from the type that we are converting to (C++
3788/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003789void
Douglas Gregor05155d82009-08-21 23:19:43 +00003790Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003791 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003792 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003793 Expr *From, QualType ToType,
3794 OverloadCandidateSet &CandidateSet) {
3795 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3796 "Only conversion function templates permitted here");
3797
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003798 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3799 return;
3800
John McCallbc077cf2010-02-08 23:07:23 +00003801 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003802 CXXConversionDecl *Specialization = 0;
3803 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003804 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003805 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003806 CandidateSet.push_back(OverloadCandidate());
3807 OverloadCandidate &Candidate = CandidateSet.back();
3808 Candidate.FoundDecl = FoundDecl;
3809 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3810 Candidate.Viable = false;
3811 Candidate.FailureKind = ovl_fail_bad_deduction;
3812 Candidate.IsSurrogate = false;
3813 Candidate.IgnoreObjectArgument = false;
3814 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3815 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003816 return;
3817 }
Mike Stump11289f42009-09-09 15:08:12 +00003818
Douglas Gregor05155d82009-08-21 23:19:43 +00003819 // Add the conversion function template specialization produced by
3820 // template argument deduction as a candidate.
3821 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003822 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003823 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003824}
3825
Douglas Gregorab7897a2008-11-19 22:57:39 +00003826/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3827/// converts the given @c Object to a function pointer via the
3828/// conversion function @c Conversion, and then attempts to call it
3829/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3830/// the type of function that we'll eventually be calling.
3831void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003832 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003833 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003834 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003835 QualType ObjectType,
3836 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003837 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003838 if (!CandidateSet.isNewCandidate(Conversion))
3839 return;
3840
Douglas Gregor27381f32009-11-23 12:27:39 +00003841 // Overload resolution is always an unevaluated context.
3842 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3843
Douglas Gregorab7897a2008-11-19 22:57:39 +00003844 CandidateSet.push_back(OverloadCandidate());
3845 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003846 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003847 Candidate.Function = 0;
3848 Candidate.Surrogate = Conversion;
3849 Candidate.Viable = true;
3850 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003851 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003852 Candidate.Conversions.resize(NumArgs + 1);
3853
3854 // Determine the implicit conversion sequence for the implicit
3855 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003856 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003857 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003858 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003859 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003860 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003861 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003862 return;
3863 }
3864
3865 // The first conversion is actually a user-defined conversion whose
3866 // first conversion is ObjectInit's standard conversion (which is
3867 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003868 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003869 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003870 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003871 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003872 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003873 = Candidate.Conversions[0].UserDefined.Before;
3874 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3875
Mike Stump11289f42009-09-09 15:08:12 +00003876 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003877 unsigned NumArgsInProto = Proto->getNumArgs();
3878
3879 // (C++ 13.3.2p2): A candidate function having fewer than m
3880 // parameters is viable only if it has an ellipsis in its parameter
3881 // list (8.3.5).
3882 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3883 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003884 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003885 return;
3886 }
3887
3888 // Function types don't have any default arguments, so just check if
3889 // we have enough arguments.
3890 if (NumArgs < NumArgsInProto) {
3891 // Not enough arguments.
3892 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003893 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003894 return;
3895 }
3896
3897 // Determine the implicit conversion sequences for each of the
3898 // arguments.
3899 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3900 if (ArgIdx < NumArgsInProto) {
3901 // (C++ 13.3.2p3): for F to be a viable function, there shall
3902 // exist for each argument an implicit conversion sequence
3903 // (13.3.3.1) that converts that argument to the corresponding
3904 // parameter of F.
3905 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003906 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003907 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003908 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003909 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003910 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003911 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003912 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003913 break;
3914 }
3915 } else {
3916 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3917 // argument for which there is no corresponding parameter is
3918 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003919 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003920 }
3921 }
3922}
3923
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003924/// \brief Add overload candidates for overloaded operators that are
3925/// member functions.
3926///
3927/// Add the overloaded operator candidates that are member functions
3928/// for the operator Op that was used in an operator expression such
3929/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3930/// CandidateSet will store the added overload candidates. (C++
3931/// [over.match.oper]).
3932void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3933 SourceLocation OpLoc,
3934 Expr **Args, unsigned NumArgs,
3935 OverloadCandidateSet& CandidateSet,
3936 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003937 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3938
3939 // C++ [over.match.oper]p3:
3940 // For a unary operator @ with an operand of a type whose
3941 // cv-unqualified version is T1, and for a binary operator @ with
3942 // a left operand of a type whose cv-unqualified version is T1 and
3943 // a right operand of a type whose cv-unqualified version is T2,
3944 // three sets of candidate functions, designated member
3945 // candidates, non-member candidates and built-in candidates, are
3946 // constructed as follows:
3947 QualType T1 = Args[0]->getType();
3948 QualType T2;
3949 if (NumArgs > 1)
3950 T2 = Args[1]->getType();
3951
3952 // -- If T1 is a class type, the set of member candidates is the
3953 // result of the qualified lookup of T1::operator@
3954 // (13.3.1.1.1); otherwise, the set of member candidates is
3955 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003956 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003957 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003958 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003959 return;
Mike Stump11289f42009-09-09 15:08:12 +00003960
John McCall27b18f82009-11-17 02:14:36 +00003961 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3962 LookupQualifiedName(Operators, T1Rec->getDecl());
3963 Operators.suppressDiagnostics();
3964
Mike Stump11289f42009-09-09 15:08:12 +00003965 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003966 OperEnd = Operators.end();
3967 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003968 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003969 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003970 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003971 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003972 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003973}
3974
Douglas Gregora11693b2008-11-12 17:17:38 +00003975/// AddBuiltinCandidate - Add a candidate for a built-in
3976/// operator. ResultTy and ParamTys are the result and parameter types
3977/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003978/// arguments being passed to the candidate. IsAssignmentOperator
3979/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003980/// operator. NumContextualBoolArguments is the number of arguments
3981/// (at the beginning of the argument list) that will be contextually
3982/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003983void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003984 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003985 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003986 bool IsAssignmentOperator,
3987 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003988 // Overload resolution is always an unevaluated context.
3989 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3990
Douglas Gregora11693b2008-11-12 17:17:38 +00003991 // Add this candidate
3992 CandidateSet.push_back(OverloadCandidate());
3993 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003994 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003995 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003996 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003997 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003998 Candidate.BuiltinTypes.ResultTy = ResultTy;
3999 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4000 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4001
4002 // Determine the implicit conversion sequences for each of the
4003 // arguments.
4004 Candidate.Viable = true;
4005 Candidate.Conversions.resize(NumArgs);
4006 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004007 // C++ [over.match.oper]p4:
4008 // For the built-in assignment operators, conversions of the
4009 // left operand are restricted as follows:
4010 // -- no temporaries are introduced to hold the left operand, and
4011 // -- no user-defined conversions are applied to the left
4012 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004013 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004014 //
4015 // We block these conversions by turning off user-defined
4016 // conversions, since that is the only way that initialization of
4017 // a reference to a non-class type can occur from something that
4018 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004019 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004020 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004021 "Contextual conversion to bool requires bool type");
4022 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4023 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004024 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004025 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004026 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004027 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004028 }
John McCall0d1da222010-01-12 00:44:57 +00004029 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004030 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004031 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004032 break;
4033 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004034 }
4035}
4036
4037/// BuiltinCandidateTypeSet - A set of types that will be used for the
4038/// candidate operator functions for built-in operators (C++
4039/// [over.built]). The types are separated into pointer types and
4040/// enumeration types.
4041class BuiltinCandidateTypeSet {
4042 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004043 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004044
4045 /// PointerTypes - The set of pointer types that will be used in the
4046 /// built-in candidates.
4047 TypeSet PointerTypes;
4048
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004049 /// MemberPointerTypes - The set of member pointer types that will be
4050 /// used in the built-in candidates.
4051 TypeSet MemberPointerTypes;
4052
Douglas Gregora11693b2008-11-12 17:17:38 +00004053 /// EnumerationTypes - The set of enumeration types that will be
4054 /// used in the built-in candidates.
4055 TypeSet EnumerationTypes;
4056
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004057 /// \brief The set of vector types that will be used in the built-in
4058 /// candidates.
4059 TypeSet VectorTypes;
4060
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004061 /// Sema - The semantic analysis instance where we are building the
4062 /// candidate type set.
4063 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004064
Douglas Gregora11693b2008-11-12 17:17:38 +00004065 /// Context - The AST context in which we will build the type sets.
4066 ASTContext &Context;
4067
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004068 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4069 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004070 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004071
4072public:
4073 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004074 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004075
Mike Stump11289f42009-09-09 15:08:12 +00004076 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004077 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004078
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004079 void AddTypesConvertedFrom(QualType Ty,
4080 SourceLocation Loc,
4081 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004082 bool AllowExplicitConversions,
4083 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004084
4085 /// pointer_begin - First pointer type found;
4086 iterator pointer_begin() { return PointerTypes.begin(); }
4087
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004088 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004089 iterator pointer_end() { return PointerTypes.end(); }
4090
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004091 /// member_pointer_begin - First member pointer type found;
4092 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4093
4094 /// member_pointer_end - Past the last member pointer type found;
4095 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4096
Douglas Gregora11693b2008-11-12 17:17:38 +00004097 /// enumeration_begin - First enumeration type found;
4098 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4099
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004100 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004101 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004102
4103 iterator vector_begin() { return VectorTypes.begin(); }
4104 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004105};
4106
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004107/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004108/// the set of pointer types along with any more-qualified variants of
4109/// that type. For example, if @p Ty is "int const *", this routine
4110/// will add "int const *", "int const volatile *", "int const
4111/// restrict *", and "int const volatile restrict *" to the set of
4112/// pointer types. Returns true if the add of @p Ty itself succeeded,
4113/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004114///
4115/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004116bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004117BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4118 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004119
Douglas Gregora11693b2008-11-12 17:17:38 +00004120 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004121 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004122 return false;
4123
John McCall8ccfcb52009-09-24 19:53:00 +00004124 const PointerType *PointerTy = Ty->getAs<PointerType>();
4125 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00004126
John McCall8ccfcb52009-09-24 19:53:00 +00004127 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004128 // Don't add qualified variants of arrays. For one, they're not allowed
4129 // (the qualifier would sink to the element type), and for another, the
4130 // only overload situation where it matters is subscript or pointer +- int,
4131 // and those shouldn't have qualifier variants anyway.
4132 if (PointeeTy->isArrayType())
4133 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004134 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004135 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004136 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004137 bool hasVolatile = VisibleQuals.hasVolatile();
4138 bool hasRestrict = VisibleQuals.hasRestrict();
4139
John McCall8ccfcb52009-09-24 19:53:00 +00004140 // Iterate through all strict supersets of BaseCVR.
4141 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4142 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004143 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4144 // in the types.
4145 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4146 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004147 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4148 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004149 }
4150
4151 return true;
4152}
4153
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004154/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4155/// to the set of pointer types along with any more-qualified variants of
4156/// that type. For example, if @p Ty is "int const *", this routine
4157/// will add "int const *", "int const volatile *", "int const
4158/// restrict *", and "int const volatile restrict *" to the set of
4159/// pointer types. Returns true if the add of @p Ty itself succeeded,
4160/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004161///
4162/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004163bool
4164BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4165 QualType Ty) {
4166 // Insert this type.
4167 if (!MemberPointerTypes.insert(Ty))
4168 return false;
4169
John McCall8ccfcb52009-09-24 19:53:00 +00004170 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4171 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004172
John McCall8ccfcb52009-09-24 19:53:00 +00004173 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004174 // Don't add qualified variants of arrays. For one, they're not allowed
4175 // (the qualifier would sink to the element type), and for another, the
4176 // only overload situation where it matters is subscript or pointer +- int,
4177 // and those shouldn't have qualifier variants anyway.
4178 if (PointeeTy->isArrayType())
4179 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004180 const Type *ClassTy = PointerTy->getClass();
4181
4182 // Iterate through all strict supersets of the pointee type's CVR
4183 // qualifiers.
4184 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4185 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4186 if ((CVR | BaseCVR) != CVR) continue;
4187
4188 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4189 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004190 }
4191
4192 return true;
4193}
4194
Douglas Gregora11693b2008-11-12 17:17:38 +00004195/// AddTypesConvertedFrom - Add each of the types to which the type @p
4196/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004197/// primarily interested in pointer types and enumeration types. We also
4198/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004199/// AllowUserConversions is true if we should look at the conversion
4200/// functions of a class type, and AllowExplicitConversions if we
4201/// should also include the explicit conversion functions of a class
4202/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004203void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004204BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004205 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004206 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004207 bool AllowExplicitConversions,
4208 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004209 // Only deal with canonical types.
4210 Ty = Context.getCanonicalType(Ty);
4211
4212 // Look through reference types; they aren't part of the type of an
4213 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004214 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004215 Ty = RefTy->getPointeeType();
4216
4217 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004218 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004219
Sebastian Redl65ae2002009-11-05 16:36:20 +00004220 // If we're dealing with an array type, decay to the pointer.
4221 if (Ty->isArrayType())
4222 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4223
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004224 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004225 QualType PointeeTy = PointerTy->getPointeeType();
4226
4227 // Insert our type, and its more-qualified variants, into the set
4228 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004229 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004230 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004231 } else if (Ty->isMemberPointerType()) {
4232 // Member pointers are far easier, since the pointee can't be converted.
4233 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4234 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004235 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004236 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004237 } else if (Ty->isVectorType()) {
4238 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004239 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004240 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004241 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004242 // No conversion functions in incomplete types.
4243 return;
4244 }
Mike Stump11289f42009-09-09 15:08:12 +00004245
Douglas Gregora11693b2008-11-12 17:17:38 +00004246 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004247 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004248 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004249 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004250 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004251 NamedDecl *D = I.getDecl();
4252 if (isa<UsingShadowDecl>(D))
4253 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004254
Mike Stump11289f42009-09-09 15:08:12 +00004255 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004256 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004257 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004258 continue;
4259
John McCallda4458e2010-03-31 01:36:47 +00004260 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004261 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004262 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004263 VisibleQuals);
4264 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004265 }
4266 }
4267 }
4268}
4269
Douglas Gregor84605ae2009-08-24 13:43:27 +00004270/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4271/// the volatile- and non-volatile-qualified assignment operators for the
4272/// given type to the candidate set.
4273static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4274 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004275 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004276 unsigned NumArgs,
4277 OverloadCandidateSet &CandidateSet) {
4278 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004279
Douglas Gregor84605ae2009-08-24 13:43:27 +00004280 // T& operator=(T&, T)
4281 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4282 ParamTypes[1] = T;
4283 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4284 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004285
Douglas Gregor84605ae2009-08-24 13:43:27 +00004286 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4287 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004288 ParamTypes[0]
4289 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004290 ParamTypes[1] = T;
4291 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004292 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004293 }
4294}
Mike Stump11289f42009-09-09 15:08:12 +00004295
Sebastian Redl1054fae2009-10-25 17:03:50 +00004296/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4297/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004298static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4299 Qualifiers VRQuals;
4300 const RecordType *TyRec;
4301 if (const MemberPointerType *RHSMPType =
4302 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004303 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004304 else
4305 TyRec = ArgExpr->getType()->getAs<RecordType>();
4306 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004307 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004308 VRQuals.addVolatile();
4309 VRQuals.addRestrict();
4310 return VRQuals;
4311 }
4312
4313 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004314 if (!ClassDecl->hasDefinition())
4315 return VRQuals;
4316
John McCallad371252010-01-20 00:46:10 +00004317 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004318 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004319
John McCallad371252010-01-20 00:46:10 +00004320 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004321 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004322 NamedDecl *D = I.getDecl();
4323 if (isa<UsingShadowDecl>(D))
4324 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4325 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004326 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4327 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4328 CanTy = ResTypeRef->getPointeeType();
4329 // Need to go down the pointer/mempointer chain and add qualifiers
4330 // as see them.
4331 bool done = false;
4332 while (!done) {
4333 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4334 CanTy = ResTypePtr->getPointeeType();
4335 else if (const MemberPointerType *ResTypeMPtr =
4336 CanTy->getAs<MemberPointerType>())
4337 CanTy = ResTypeMPtr->getPointeeType();
4338 else
4339 done = true;
4340 if (CanTy.isVolatileQualified())
4341 VRQuals.addVolatile();
4342 if (CanTy.isRestrictQualified())
4343 VRQuals.addRestrict();
4344 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4345 return VRQuals;
4346 }
4347 }
4348 }
4349 return VRQuals;
4350}
4351
Douglas Gregord08452f2008-11-19 15:42:04 +00004352/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4353/// operator overloads to the candidate set (C++ [over.built]), based
4354/// on the operator @p Op and the arguments given. For example, if the
4355/// operator is a binary '+', this routine might add "int
4356/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004357void
Mike Stump11289f42009-09-09 15:08:12 +00004358Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004359 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004360 Expr **Args, unsigned NumArgs,
4361 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004362 // The set of "promoted arithmetic types", which are the arithmetic
4363 // types are that preserved by promotion (C++ [over.built]p2). Note
4364 // that the first few of these types are the promoted integral
4365 // types; these types need to be first.
4366 // FIXME: What about complex?
4367 const unsigned FirstIntegralType = 0;
4368 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004369 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004370 LastPromotedIntegralType = 13;
4371 const unsigned FirstPromotedArithmeticType = 7,
4372 LastPromotedArithmeticType = 16;
4373 const unsigned NumArithmeticTypes = 16;
4374 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004375 Context.BoolTy, Context.CharTy, Context.WCharTy,
4376// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004377 Context.SignedCharTy, Context.ShortTy,
4378 Context.UnsignedCharTy, Context.UnsignedShortTy,
4379 Context.IntTy, Context.LongTy, Context.LongLongTy,
4380 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4381 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4382 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004383 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4384 "Invalid first promoted integral type");
4385 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4386 == Context.UnsignedLongLongTy &&
4387 "Invalid last promoted integral type");
4388 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4389 "Invalid first promoted arithmetic type");
4390 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4391 == Context.LongDoubleTy &&
4392 "Invalid last promoted arithmetic type");
4393
Douglas Gregora11693b2008-11-12 17:17:38 +00004394 // Find all of the types that the arguments can convert to, but only
4395 // if the operator we're looking at has built-in operator candidates
4396 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004397 Qualifiers VisibleTypeConversionsQuals;
4398 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004399 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4400 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4401
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004402 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004403 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4404 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4405 OpLoc,
4406 true,
4407 (Op == OO_Exclaim ||
4408 Op == OO_AmpAmp ||
4409 Op == OO_PipePipe),
4410 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004411
4412 bool isComparison = false;
4413 switch (Op) {
4414 case OO_None:
4415 case NUM_OVERLOADED_OPERATORS:
4416 assert(false && "Expected an overloaded operator");
4417 break;
4418
Douglas Gregord08452f2008-11-19 15:42:04 +00004419 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004420 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004421 goto UnaryStar;
4422 else
4423 goto BinaryStar;
4424 break;
4425
4426 case OO_Plus: // '+' is either unary or binary
4427 if (NumArgs == 1)
4428 goto UnaryPlus;
4429 else
4430 goto BinaryPlus;
4431 break;
4432
4433 case OO_Minus: // '-' is either unary or binary
4434 if (NumArgs == 1)
4435 goto UnaryMinus;
4436 else
4437 goto BinaryMinus;
4438 break;
4439
4440 case OO_Amp: // '&' is either unary or binary
4441 if (NumArgs == 1)
4442 goto UnaryAmp;
4443 else
4444 goto BinaryAmp;
4445
4446 case OO_PlusPlus:
4447 case OO_MinusMinus:
4448 // C++ [over.built]p3:
4449 //
4450 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4451 // is either volatile or empty, there exist candidate operator
4452 // functions of the form
4453 //
4454 // VQ T& operator++(VQ T&);
4455 // T operator++(VQ T&, int);
4456 //
4457 // C++ [over.built]p4:
4458 //
4459 // For every pair (T, VQ), where T is an arithmetic type other
4460 // than bool, and VQ is either volatile or empty, there exist
4461 // candidate operator functions of the form
4462 //
4463 // VQ T& operator--(VQ T&);
4464 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004465 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004466 Arith < NumArithmeticTypes; ++Arith) {
4467 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004468 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004469 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004470
4471 // Non-volatile version.
4472 if (NumArgs == 1)
4473 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4474 else
4475 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004476 // heuristic to reduce number of builtin candidates in the set.
4477 // Add volatile version only if there are conversions to a volatile type.
4478 if (VisibleTypeConversionsQuals.hasVolatile()) {
4479 // Volatile version
4480 ParamTypes[0]
4481 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4482 if (NumArgs == 1)
4483 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4484 else
4485 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4486 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004487 }
4488
4489 // C++ [over.built]p5:
4490 //
4491 // For every pair (T, VQ), where T is a cv-qualified or
4492 // cv-unqualified object type, and VQ is either volatile or
4493 // empty, there exist candidate operator functions of the form
4494 //
4495 // T*VQ& operator++(T*VQ&);
4496 // T*VQ& operator--(T*VQ&);
4497 // T* operator++(T*VQ&, int);
4498 // T* operator--(T*VQ&, int);
4499 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4500 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4501 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004502 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004503 continue;
4504
Mike Stump11289f42009-09-09 15:08:12 +00004505 QualType ParamTypes[2] = {
4506 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004507 };
Mike Stump11289f42009-09-09 15:08:12 +00004508
Douglas Gregord08452f2008-11-19 15:42:04 +00004509 // Without volatile
4510 if (NumArgs == 1)
4511 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4512 else
4513 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4514
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004515 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4516 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004517 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004518 ParamTypes[0]
4519 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004520 if (NumArgs == 1)
4521 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4522 else
4523 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4524 }
4525 }
4526 break;
4527
4528 UnaryStar:
4529 // C++ [over.built]p6:
4530 // For every cv-qualified or cv-unqualified object type T, there
4531 // exist candidate operator functions of the form
4532 //
4533 // T& operator*(T*);
4534 //
4535 // C++ [over.built]p7:
4536 // For every function type T, there exist candidate operator
4537 // functions of the form
4538 // T& operator*(T*);
4539 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4540 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4541 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004542 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004543 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004544 &ParamTy, Args, 1, CandidateSet);
4545 }
4546 break;
4547
4548 UnaryPlus:
4549 // C++ [over.built]p8:
4550 // For every type T, there exist candidate operator functions of
4551 // the form
4552 //
4553 // T* operator+(T*);
4554 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4555 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4556 QualType ParamTy = *Ptr;
4557 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4558 }
Mike Stump11289f42009-09-09 15:08:12 +00004559
Douglas Gregord08452f2008-11-19 15:42:04 +00004560 // Fall through
4561
4562 UnaryMinus:
4563 // C++ [over.built]p9:
4564 // For every promoted arithmetic type T, there exist candidate
4565 // operator functions of the form
4566 //
4567 // T operator+(T);
4568 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004569 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004570 Arith < LastPromotedArithmeticType; ++Arith) {
4571 QualType ArithTy = ArithmeticTypes[Arith];
4572 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4573 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004574
4575 // Extension: We also add these operators for vector types.
4576 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4577 VecEnd = CandidateTypes.vector_end();
4578 Vec != VecEnd; ++Vec) {
4579 QualType VecTy = *Vec;
4580 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4581 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004582 break;
4583
4584 case OO_Tilde:
4585 // C++ [over.built]p10:
4586 // For every promoted integral type T, there exist candidate
4587 // operator functions of the form
4588 //
4589 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004590 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004591 Int < LastPromotedIntegralType; ++Int) {
4592 QualType IntTy = ArithmeticTypes[Int];
4593 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4594 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004595
4596 // Extension: We also add this operator for vector types.
4597 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4598 VecEnd = CandidateTypes.vector_end();
4599 Vec != VecEnd; ++Vec) {
4600 QualType VecTy = *Vec;
4601 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4602 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004603 break;
4604
Douglas Gregora11693b2008-11-12 17:17:38 +00004605 case OO_New:
4606 case OO_Delete:
4607 case OO_Array_New:
4608 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004609 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004610 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004611 break;
4612
4613 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004614 UnaryAmp:
4615 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004616 // C++ [over.match.oper]p3:
4617 // -- For the operator ',', the unary operator '&', or the
4618 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004619 break;
4620
Douglas Gregor84605ae2009-08-24 13:43:27 +00004621 case OO_EqualEqual:
4622 case OO_ExclaimEqual:
4623 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004624 // For every pointer to member type T, there exist candidate operator
4625 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004626 //
4627 // bool operator==(T,T);
4628 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004629 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004630 MemPtr = CandidateTypes.member_pointer_begin(),
4631 MemPtrEnd = CandidateTypes.member_pointer_end();
4632 MemPtr != MemPtrEnd;
4633 ++MemPtr) {
4634 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4635 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4636 }
Mike Stump11289f42009-09-09 15:08:12 +00004637
Douglas Gregor84605ae2009-08-24 13:43:27 +00004638 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004639
Douglas Gregora11693b2008-11-12 17:17:38 +00004640 case OO_Less:
4641 case OO_Greater:
4642 case OO_LessEqual:
4643 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004644 // C++ [over.built]p15:
4645 //
4646 // For every pointer or enumeration type T, there exist
4647 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004648 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004649 // bool operator<(T, T);
4650 // bool operator>(T, T);
4651 // bool operator<=(T, T);
4652 // bool operator>=(T, T);
4653 // bool operator==(T, T);
4654 // bool operator!=(T, T);
4655 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4656 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4657 QualType ParamTypes[2] = { *Ptr, *Ptr };
4658 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4659 }
Mike Stump11289f42009-09-09 15:08:12 +00004660 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004661 = CandidateTypes.enumeration_begin();
4662 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4663 QualType ParamTypes[2] = { *Enum, *Enum };
4664 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4665 }
4666
4667 // Fall through.
4668 isComparison = true;
4669
Douglas Gregord08452f2008-11-19 15:42:04 +00004670 BinaryPlus:
4671 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004672 if (!isComparison) {
4673 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4674
4675 // C++ [over.built]p13:
4676 //
4677 // For every cv-qualified or cv-unqualified object type T
4678 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004679 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004680 // T* operator+(T*, ptrdiff_t);
4681 // T& operator[](T*, ptrdiff_t); [BELOW]
4682 // T* operator-(T*, ptrdiff_t);
4683 // T* operator+(ptrdiff_t, T*);
4684 // T& operator[](ptrdiff_t, T*); [BELOW]
4685 //
4686 // C++ [over.built]p14:
4687 //
4688 // For every T, where T is a pointer to object type, there
4689 // exist candidate operator functions of the form
4690 //
4691 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004692 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004693 = CandidateTypes.pointer_begin();
4694 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4695 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4696
4697 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4698 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4699
4700 if (Op == OO_Plus) {
4701 // T* operator+(ptrdiff_t, T*);
4702 ParamTypes[0] = ParamTypes[1];
4703 ParamTypes[1] = *Ptr;
4704 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4705 } else {
4706 // ptrdiff_t operator-(T, T);
4707 ParamTypes[1] = *Ptr;
4708 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4709 Args, 2, CandidateSet);
4710 }
4711 }
4712 }
4713 // Fall through
4714
Douglas Gregora11693b2008-11-12 17:17:38 +00004715 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004716 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004717 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004718 // C++ [over.built]p12:
4719 //
4720 // For every pair of promoted arithmetic types L and R, there
4721 // exist candidate operator functions of the form
4722 //
4723 // LR operator*(L, R);
4724 // LR operator/(L, R);
4725 // LR operator+(L, R);
4726 // LR operator-(L, R);
4727 // bool operator<(L, R);
4728 // bool operator>(L, R);
4729 // bool operator<=(L, R);
4730 // bool operator>=(L, R);
4731 // bool operator==(L, R);
4732 // bool operator!=(L, R);
4733 //
4734 // where LR is the result of the usual arithmetic conversions
4735 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004736 //
4737 // C++ [over.built]p24:
4738 //
4739 // For every pair of promoted arithmetic types L and R, there exist
4740 // candidate operator functions of the form
4741 //
4742 // LR operator?(bool, L, R);
4743 //
4744 // where LR is the result of the usual arithmetic conversions
4745 // between types L and R.
4746 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004747 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004748 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004749 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004750 Right < LastPromotedArithmeticType; ++Right) {
4751 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004752 QualType Result
4753 = isComparison
4754 ? Context.BoolTy
4755 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004756 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4757 }
4758 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004759
4760 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4761 // conditional operator for vector types.
4762 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4763 Vec1End = CandidateTypes.vector_end();
4764 Vec1 != Vec1End; ++Vec1)
4765 for (BuiltinCandidateTypeSet::iterator
4766 Vec2 = CandidateTypes.vector_begin(),
4767 Vec2End = CandidateTypes.vector_end();
4768 Vec2 != Vec2End; ++Vec2) {
4769 QualType LandR[2] = { *Vec1, *Vec2 };
4770 QualType Result;
4771 if (isComparison)
4772 Result = Context.BoolTy;
4773 else {
4774 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4775 Result = *Vec1;
4776 else
4777 Result = *Vec2;
4778 }
4779
4780 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4781 }
4782
Douglas Gregora11693b2008-11-12 17:17:38 +00004783 break;
4784
4785 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004786 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004787 case OO_Caret:
4788 case OO_Pipe:
4789 case OO_LessLess:
4790 case OO_GreaterGreater:
4791 // C++ [over.built]p17:
4792 //
4793 // For every pair of promoted integral types L and R, there
4794 // exist candidate operator functions of the form
4795 //
4796 // LR operator%(L, R);
4797 // LR operator&(L, R);
4798 // LR operator^(L, R);
4799 // LR operator|(L, R);
4800 // L operator<<(L, R);
4801 // L operator>>(L, R);
4802 //
4803 // where LR is the result of the usual arithmetic conversions
4804 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004805 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004806 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004807 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004808 Right < LastPromotedIntegralType; ++Right) {
4809 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4810 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4811 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004812 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004813 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4814 }
4815 }
4816 break;
4817
4818 case OO_Equal:
4819 // C++ [over.built]p20:
4820 //
4821 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004822 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004823 // empty, there exist candidate operator functions of the form
4824 //
4825 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004826 for (BuiltinCandidateTypeSet::iterator
4827 Enum = CandidateTypes.enumeration_begin(),
4828 EnumEnd = CandidateTypes.enumeration_end();
4829 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004830 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004831 CandidateSet);
4832 for (BuiltinCandidateTypeSet::iterator
4833 MemPtr = CandidateTypes.member_pointer_begin(),
4834 MemPtrEnd = CandidateTypes.member_pointer_end();
4835 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004836 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004837 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004838
4839 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004840
4841 case OO_PlusEqual:
4842 case OO_MinusEqual:
4843 // C++ [over.built]p19:
4844 //
4845 // For every pair (T, VQ), where T is any type and VQ is either
4846 // volatile or empty, there exist candidate operator functions
4847 // of the form
4848 //
4849 // T*VQ& operator=(T*VQ&, T*);
4850 //
4851 // C++ [over.built]p21:
4852 //
4853 // For every pair (T, VQ), where T is a cv-qualified or
4854 // cv-unqualified object type and VQ is either volatile or
4855 // empty, there exist candidate operator functions of the form
4856 //
4857 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4858 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4859 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4860 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4861 QualType ParamTypes[2];
4862 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4863
4864 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004865 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004866 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4867 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004868
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004869 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4870 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004871 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004872 ParamTypes[0]
4873 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004874 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4875 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004876 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004877 }
4878 // Fall through.
4879
4880 case OO_StarEqual:
4881 case OO_SlashEqual:
4882 // C++ [over.built]p18:
4883 //
4884 // For every triple (L, VQ, R), where L is an arithmetic type,
4885 // VQ is either volatile or empty, and R is a promoted
4886 // arithmetic type, there exist candidate operator functions of
4887 // the form
4888 //
4889 // VQ L& operator=(VQ L&, R);
4890 // VQ L& operator*=(VQ L&, R);
4891 // VQ L& operator/=(VQ L&, R);
4892 // VQ L& operator+=(VQ L&, R);
4893 // VQ L& operator-=(VQ L&, R);
4894 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004895 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004896 Right < LastPromotedArithmeticType; ++Right) {
4897 QualType ParamTypes[2];
4898 ParamTypes[1] = ArithmeticTypes[Right];
4899
4900 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004901 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004902 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4903 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004904
4905 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004906 if (VisibleTypeConversionsQuals.hasVolatile()) {
4907 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4908 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4909 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4910 /*IsAssigmentOperator=*/Op == OO_Equal);
4911 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004912 }
4913 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004914
4915 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4916 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4917 Vec1End = CandidateTypes.vector_end();
4918 Vec1 != Vec1End; ++Vec1)
4919 for (BuiltinCandidateTypeSet::iterator
4920 Vec2 = CandidateTypes.vector_begin(),
4921 Vec2End = CandidateTypes.vector_end();
4922 Vec2 != Vec2End; ++Vec2) {
4923 QualType ParamTypes[2];
4924 ParamTypes[1] = *Vec2;
4925 // Add this built-in operator as a candidate (VQ is empty).
4926 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4927 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4928 /*IsAssigmentOperator=*/Op == OO_Equal);
4929
4930 // Add this built-in operator as a candidate (VQ is 'volatile').
4931 if (VisibleTypeConversionsQuals.hasVolatile()) {
4932 ParamTypes[0] = Context.getVolatileType(*Vec1);
4933 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4934 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4935 /*IsAssigmentOperator=*/Op == OO_Equal);
4936 }
4937 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004938 break;
4939
4940 case OO_PercentEqual:
4941 case OO_LessLessEqual:
4942 case OO_GreaterGreaterEqual:
4943 case OO_AmpEqual:
4944 case OO_CaretEqual:
4945 case OO_PipeEqual:
4946 // C++ [over.built]p22:
4947 //
4948 // For every triple (L, VQ, R), where L is an integral type, VQ
4949 // is either volatile or empty, and R is a promoted integral
4950 // type, there exist candidate operator functions of the form
4951 //
4952 // VQ L& operator%=(VQ L&, R);
4953 // VQ L& operator<<=(VQ L&, R);
4954 // VQ L& operator>>=(VQ L&, R);
4955 // VQ L& operator&=(VQ L&, R);
4956 // VQ L& operator^=(VQ L&, R);
4957 // VQ L& operator|=(VQ L&, R);
4958 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004959 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004960 Right < LastPromotedIntegralType; ++Right) {
4961 QualType ParamTypes[2];
4962 ParamTypes[1] = ArithmeticTypes[Right];
4963
4964 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004965 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004966 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004967 if (VisibleTypeConversionsQuals.hasVolatile()) {
4968 // Add this built-in operator as a candidate (VQ is 'volatile').
4969 ParamTypes[0] = ArithmeticTypes[Left];
4970 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4971 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4972 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4973 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004974 }
4975 }
4976 break;
4977
Douglas Gregord08452f2008-11-19 15:42:04 +00004978 case OO_Exclaim: {
4979 // C++ [over.operator]p23:
4980 //
4981 // There also exist candidate operator functions of the form
4982 //
Mike Stump11289f42009-09-09 15:08:12 +00004983 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004984 // bool operator&&(bool, bool); [BELOW]
4985 // bool operator||(bool, bool); [BELOW]
4986 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004987 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4988 /*IsAssignmentOperator=*/false,
4989 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004990 break;
4991 }
4992
Douglas Gregora11693b2008-11-12 17:17:38 +00004993 case OO_AmpAmp:
4994 case OO_PipePipe: {
4995 // C++ [over.operator]p23:
4996 //
4997 // There also exist candidate operator functions of the form
4998 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004999 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005000 // bool operator&&(bool, bool);
5001 // bool operator||(bool, bool);
5002 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005003 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5004 /*IsAssignmentOperator=*/false,
5005 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005006 break;
5007 }
5008
5009 case OO_Subscript:
5010 // C++ [over.built]p13:
5011 //
5012 // For every cv-qualified or cv-unqualified object type T there
5013 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005014 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005015 // T* operator+(T*, ptrdiff_t); [ABOVE]
5016 // T& operator[](T*, ptrdiff_t);
5017 // T* operator-(T*, ptrdiff_t); [ABOVE]
5018 // T* operator+(ptrdiff_t, T*); [ABOVE]
5019 // T& operator[](ptrdiff_t, T*);
5020 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5021 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5022 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005023 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005024 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005025
5026 // T& operator[](T*, ptrdiff_t)
5027 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5028
5029 // T& operator[](ptrdiff_t, T*);
5030 ParamTypes[0] = ParamTypes[1];
5031 ParamTypes[1] = *Ptr;
5032 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005033 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005034 break;
5035
5036 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005037 // C++ [over.built]p11:
5038 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5039 // C1 is the same type as C2 or is a derived class of C2, T is an object
5040 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5041 // there exist candidate operator functions of the form
5042 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5043 // where CV12 is the union of CV1 and CV2.
5044 {
5045 for (BuiltinCandidateTypeSet::iterator Ptr =
5046 CandidateTypes.pointer_begin();
5047 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5048 QualType C1Ty = (*Ptr);
5049 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005050 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005051 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005052 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005053 if (!isa<RecordType>(C1))
5054 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005055 // heuristic to reduce number of builtin candidates in the set.
5056 // Add volatile/restrict version only if there are conversions to a
5057 // volatile/restrict type.
5058 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5059 continue;
5060 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5061 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005062 }
5063 for (BuiltinCandidateTypeSet::iterator
5064 MemPtr = CandidateTypes.member_pointer_begin(),
5065 MemPtrEnd = CandidateTypes.member_pointer_end();
5066 MemPtr != MemPtrEnd; ++MemPtr) {
5067 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5068 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005069 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005070 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5071 break;
5072 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5073 // build CV12 T&
5074 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005075 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5076 T.isVolatileQualified())
5077 continue;
5078 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5079 T.isRestrictQualified())
5080 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005081 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005082 QualType ResultTy = Context.getLValueReferenceType(T);
5083 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5084 }
5085 }
5086 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005087 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005088
5089 case OO_Conditional:
5090 // Note that we don't consider the first argument, since it has been
5091 // contextually converted to bool long ago. The candidates below are
5092 // therefore added as binary.
5093 //
5094 // C++ [over.built]p24:
5095 // For every type T, where T is a pointer or pointer-to-member type,
5096 // there exist candidate operator functions of the form
5097 //
5098 // T operator?(bool, T, T);
5099 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005100 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5101 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5102 QualType ParamTypes[2] = { *Ptr, *Ptr };
5103 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5104 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005105 for (BuiltinCandidateTypeSet::iterator Ptr =
5106 CandidateTypes.member_pointer_begin(),
5107 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5108 QualType ParamTypes[2] = { *Ptr, *Ptr };
5109 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5110 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005111 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005112 }
5113}
5114
Douglas Gregore254f902009-02-04 00:32:51 +00005115/// \brief Add function candidates found via argument-dependent lookup
5116/// to the set of overloading candidates.
5117///
5118/// This routine performs argument-dependent name lookup based on the
5119/// given function name (which may also be an operator name) and adds
5120/// all of the overload candidates found by ADL to the overload
5121/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005122void
Douglas Gregore254f902009-02-04 00:32:51 +00005123Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005124 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005125 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005126 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005127 OverloadCandidateSet& CandidateSet,
5128 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005129 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005130
John McCall91f61fc2010-01-26 06:04:06 +00005131 // FIXME: This approach for uniquing ADL results (and removing
5132 // redundant candidates from the set) relies on pointer-equality,
5133 // which means we need to key off the canonical decl. However,
5134 // always going back to the canonical decl might not get us the
5135 // right set of default arguments. What default arguments are
5136 // we supposed to consider on ADL candidates, anyway?
5137
Douglas Gregorcabea402009-09-22 15:41:20 +00005138 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005139 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005140
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005141 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005142 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5143 CandEnd = CandidateSet.end();
5144 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005145 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005146 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005147 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005148 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005149 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005150
5151 // For each of the ADL candidates we found, add it to the overload
5152 // set.
John McCall8fe68082010-01-26 07:16:45 +00005153 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005154 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005155 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005156 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005157 continue;
5158
John McCalla0296f72010-03-19 07:35:19 +00005159 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005160 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005161 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005162 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005163 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005164 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005165 }
Douglas Gregore254f902009-02-04 00:32:51 +00005166}
5167
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005168/// isBetterOverloadCandidate - Determines whether the first overload
5169/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005170bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005171Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00005172 const OverloadCandidate& Cand2,
5173 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005174 // Define viable functions to be better candidates than non-viable
5175 // functions.
5176 if (!Cand2.Viable)
5177 return Cand1.Viable;
5178 else if (!Cand1.Viable)
5179 return false;
5180
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005181 // C++ [over.match.best]p1:
5182 //
5183 // -- if F is a static member function, ICS1(F) is defined such
5184 // that ICS1(F) is neither better nor worse than ICS1(G) for
5185 // any function G, and, symmetrically, ICS1(G) is neither
5186 // better nor worse than ICS1(F).
5187 unsigned StartArg = 0;
5188 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5189 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005190
Douglas Gregord3cb3562009-07-07 23:38:56 +00005191 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005192 // A viable function F1 is defined to be a better function than another
5193 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005194 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005195 unsigned NumArgs = Cand1.Conversions.size();
5196 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5197 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005198 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005199 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5200 Cand2.Conversions[ArgIdx])) {
5201 case ImplicitConversionSequence::Better:
5202 // Cand1 has a better conversion sequence.
5203 HasBetterConversion = true;
5204 break;
5205
5206 case ImplicitConversionSequence::Worse:
5207 // Cand1 can't be better than Cand2.
5208 return false;
5209
5210 case ImplicitConversionSequence::Indistinguishable:
5211 // Do nothing.
5212 break;
5213 }
5214 }
5215
Mike Stump11289f42009-09-09 15:08:12 +00005216 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005217 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005218 if (HasBetterConversion)
5219 return true;
5220
Mike Stump11289f42009-09-09 15:08:12 +00005221 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005222 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005223 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005224 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5225 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005226
5227 // -- F1 and F2 are function template specializations, and the function
5228 // template for F1 is more specialized than the template for F2
5229 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005230 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005231 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5232 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005233 if (FunctionTemplateDecl *BetterTemplate
5234 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5235 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005236 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005237 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5238 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005239 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005240
Douglas Gregora1f013e2008-11-07 22:36:19 +00005241 // -- the context is an initialization by user-defined conversion
5242 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5243 // from the return type of F1 to the destination type (i.e.,
5244 // the type of the entity being initialized) is a better
5245 // conversion sequence than the standard conversion sequence
5246 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005247 if (Cand1.Function && Cand2.Function &&
5248 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005249 isa<CXXConversionDecl>(Cand2.Function)) {
5250 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5251 Cand2.FinalConversion)) {
5252 case ImplicitConversionSequence::Better:
5253 // Cand1 has a better conversion sequence.
5254 return true;
5255
5256 case ImplicitConversionSequence::Worse:
5257 // Cand1 can't be better than Cand2.
5258 return false;
5259
5260 case ImplicitConversionSequence::Indistinguishable:
5261 // Do nothing
5262 break;
5263 }
5264 }
5265
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005266 return false;
5267}
5268
Mike Stump11289f42009-09-09 15:08:12 +00005269/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005270/// within an overload candidate set.
5271///
5272/// \param CandidateSet the set of candidate functions.
5273///
5274/// \param Loc the location of the function name (or operator symbol) for
5275/// which overload resolution occurs.
5276///
Mike Stump11289f42009-09-09 15:08:12 +00005277/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005278/// function, Best points to the candidate function found.
5279///
5280/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005281OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5282 SourceLocation Loc,
5283 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005284 // Find the best viable function.
5285 Best = CandidateSet.end();
5286 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5287 Cand != CandidateSet.end(); ++Cand) {
5288 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005289 if (Best == CandidateSet.end() ||
5290 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005291 Best = Cand;
5292 }
5293 }
5294
5295 // If we didn't find any viable functions, abort.
5296 if (Best == CandidateSet.end())
5297 return OR_No_Viable_Function;
5298
5299 // Make sure that this function is better than every other viable
5300 // function. If not, we have an ambiguity.
5301 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5302 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005303 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005304 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005305 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005306 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005307 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005308 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005311 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005312 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005313 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005314 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005315 return OR_Deleted;
5316
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005317 // C++ [basic.def.odr]p2:
5318 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005319 // when referred to from a potentially-evaluated expression. [Note: this
5320 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005321 // (clause 13), user-defined conversions (12.3.2), allocation function for
5322 // placement new (5.3.4), as well as non-default initialization (8.5).
5323 if (Best->Function)
5324 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005325 return OR_Success;
5326}
5327
John McCall53262c92010-01-12 02:15:36 +00005328namespace {
5329
5330enum OverloadCandidateKind {
5331 oc_function,
5332 oc_method,
5333 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005334 oc_function_template,
5335 oc_method_template,
5336 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005337 oc_implicit_default_constructor,
5338 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005339 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005340};
5341
John McCalle1ac8d12010-01-13 00:25:19 +00005342OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5343 FunctionDecl *Fn,
5344 std::string &Description) {
5345 bool isTemplate = false;
5346
5347 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5348 isTemplate = true;
5349 Description = S.getTemplateArgumentBindingsText(
5350 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5351 }
John McCallfd0b2f82010-01-06 09:43:14 +00005352
5353 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005354 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005355 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005356
John McCall53262c92010-01-12 02:15:36 +00005357 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5358 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005359 }
5360
5361 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5362 // This actually gets spelled 'candidate function' for now, but
5363 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005364 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005365 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005366
5367 assert(Meth->isCopyAssignment()
5368 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005369 return oc_implicit_copy_assignment;
5370 }
5371
John McCalle1ac8d12010-01-13 00:25:19 +00005372 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005373}
5374
5375} // end anonymous namespace
5376
5377// Notes the location of an overload candidate.
5378void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005379 std::string FnDesc;
5380 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5381 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5382 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005383}
5384
John McCall0d1da222010-01-12 00:44:57 +00005385/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5386/// "lead" diagnostic; it will be given two arguments, the source and
5387/// target types of the conversion.
5388void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5389 SourceLocation CaretLoc,
5390 const PartialDiagnostic &PDiag) {
5391 Diag(CaretLoc, PDiag)
5392 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5393 for (AmbiguousConversionSequence::const_iterator
5394 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5395 NoteOverloadCandidate(*I);
5396 }
John McCall12f97bc2010-01-08 04:41:39 +00005397}
5398
John McCall0d1da222010-01-12 00:44:57 +00005399namespace {
5400
John McCall6a61b522010-01-13 09:16:55 +00005401void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5402 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5403 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005404 assert(Cand->Function && "for now, candidate must be a function");
5405 FunctionDecl *Fn = Cand->Function;
5406
5407 // There's a conversion slot for the object argument if this is a
5408 // non-constructor method. Note that 'I' corresponds the
5409 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005410 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005411 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005412 if (I == 0)
5413 isObjectArgument = true;
5414 else
5415 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005416 }
5417
John McCalle1ac8d12010-01-13 00:25:19 +00005418 std::string FnDesc;
5419 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5420
John McCall6a61b522010-01-13 09:16:55 +00005421 Expr *FromExpr = Conv.Bad.FromExpr;
5422 QualType FromTy = Conv.Bad.getFromType();
5423 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005424
John McCallfb7ad0f2010-02-02 02:42:52 +00005425 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005426 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005427 Expr *E = FromExpr->IgnoreParens();
5428 if (isa<UnaryOperator>(E))
5429 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005430 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005431
5432 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5433 << (unsigned) FnKind << FnDesc
5434 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5435 << ToTy << Name << I+1;
5436 return;
5437 }
5438
John McCall6d174642010-01-23 08:10:49 +00005439 // Do some hand-waving analysis to see if the non-viability is due
5440 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005441 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5442 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5443 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5444 CToTy = RT->getPointeeType();
5445 else {
5446 // TODO: detect and diagnose the full richness of const mismatches.
5447 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5448 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5449 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5450 }
5451
5452 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5453 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5454 // It is dumb that we have to do this here.
5455 while (isa<ArrayType>(CFromTy))
5456 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5457 while (isa<ArrayType>(CToTy))
5458 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5459
5460 Qualifiers FromQs = CFromTy.getQualifiers();
5461 Qualifiers ToQs = CToTy.getQualifiers();
5462
5463 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5465 << (unsigned) FnKind << FnDesc
5466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5467 << FromTy
5468 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5469 << (unsigned) isObjectArgument << I+1;
5470 return;
5471 }
5472
5473 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5474 assert(CVR && "unexpected qualifiers mismatch");
5475
5476 if (isObjectArgument) {
5477 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5478 << (unsigned) FnKind << FnDesc
5479 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5480 << FromTy << (CVR - 1);
5481 } else {
5482 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5483 << (unsigned) FnKind << FnDesc
5484 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5485 << FromTy << (CVR - 1) << I+1;
5486 }
5487 return;
5488 }
5489
John McCall6d174642010-01-23 08:10:49 +00005490 // Diagnose references or pointers to incomplete types differently,
5491 // since it's far from impossible that the incompleteness triggered
5492 // the failure.
5493 QualType TempFromTy = FromTy.getNonReferenceType();
5494 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5495 TempFromTy = PTy->getPointeeType();
5496 if (TempFromTy->isIncompleteType()) {
5497 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5498 << (unsigned) FnKind << FnDesc
5499 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5500 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5501 return;
5502 }
5503
Douglas Gregor56f2e342010-06-30 23:01:39 +00005504 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005505 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005506 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5507 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5508 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5509 FromPtrTy->getPointeeType()) &&
5510 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5511 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5512 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5513 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005514 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005515 }
5516 } else if (const ObjCObjectPointerType *FromPtrTy
5517 = FromTy->getAs<ObjCObjectPointerType>()) {
5518 if (const ObjCObjectPointerType *ToPtrTy
5519 = ToTy->getAs<ObjCObjectPointerType>())
5520 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5521 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5522 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5523 FromPtrTy->getPointeeType()) &&
5524 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005525 BaseToDerivedConversion = 2;
5526 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5527 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5528 !FromTy->isIncompleteType() &&
5529 !ToRefTy->getPointeeType()->isIncompleteType() &&
5530 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5531 BaseToDerivedConversion = 3;
5532 }
5533
5534 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005535 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005536 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005537 << (unsigned) FnKind << FnDesc
5538 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005539 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005540 << FromTy << ToTy << I+1;
5541 return;
5542 }
5543
John McCall47000992010-01-14 03:28:57 +00005544 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5546 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005548 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005549}
5550
5551void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5552 unsigned NumFormalArgs) {
5553 // TODO: treat calls to a missing default constructor as a special case
5554
5555 FunctionDecl *Fn = Cand->Function;
5556 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5557
5558 unsigned MinParams = Fn->getMinRequiredArguments();
5559
5560 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005561 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005562 unsigned mode, modeCount;
5563 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005564 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5565 (Cand->FailureKind == ovl_fail_bad_deduction &&
5566 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005567 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5568 mode = 0; // "at least"
5569 else
5570 mode = 2; // "exactly"
5571 modeCount = MinParams;
5572 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005573 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5574 (Cand->FailureKind == ovl_fail_bad_deduction &&
5575 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005576 if (MinParams != FnTy->getNumArgs())
5577 mode = 1; // "at most"
5578 else
5579 mode = 2; // "exactly"
5580 modeCount = FnTy->getNumArgs();
5581 }
5582
5583 std::string Description;
5584 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5585
5586 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005587 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5588 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005589}
5590
John McCall8b9ed552010-02-01 18:53:26 +00005591/// Diagnose a failed template-argument deduction.
5592void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5593 Expr **Args, unsigned NumArgs) {
5594 FunctionDecl *Fn = Cand->Function; // pattern
5595
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005596 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005597 NamedDecl *ParamD;
5598 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5599 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5600 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005601 switch (Cand->DeductionFailure.Result) {
5602 case Sema::TDK_Success:
5603 llvm_unreachable("TDK_success while diagnosing bad deduction");
5604
5605 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005606 assert(ParamD && "no parameter found for incomplete deduction result");
5607 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5608 << ParamD->getDeclName();
5609 return;
5610 }
5611
John McCall42d7d192010-08-05 09:05:08 +00005612 case Sema::TDK_Underqualified: {
5613 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5614 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5615
5616 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5617
5618 // Param will have been canonicalized, but it should just be a
5619 // qualified version of ParamD, so move the qualifiers to that.
5620 QualifierCollector Qs(S.Context);
5621 Qs.strip(Param);
5622 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5623 assert(S.Context.hasSameType(Param, NonCanonParam));
5624
5625 // Arg has also been canonicalized, but there's nothing we can do
5626 // about that. It also doesn't matter as much, because it won't
5627 // have any template parameters in it (because deduction isn't
5628 // done on dependent types).
5629 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5630
5631 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5632 << ParamD->getDeclName() << Arg << NonCanonParam;
5633 return;
5634 }
5635
5636 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005637 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005638 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005639 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005640 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005641 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005642 which = 1;
5643 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005644 which = 2;
5645 }
5646
5647 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5648 << which << ParamD->getDeclName()
5649 << *Cand->DeductionFailure.getFirstArg()
5650 << *Cand->DeductionFailure.getSecondArg();
5651 return;
5652 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005653
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005654 case Sema::TDK_InvalidExplicitArguments:
5655 assert(ParamD && "no parameter found for invalid explicit arguments");
5656 if (ParamD->getDeclName())
5657 S.Diag(Fn->getLocation(),
5658 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5659 << ParamD->getDeclName();
5660 else {
5661 int index = 0;
5662 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5663 index = TTP->getIndex();
5664 else if (NonTypeTemplateParmDecl *NTTP
5665 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5666 index = NTTP->getIndex();
5667 else
5668 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5669 S.Diag(Fn->getLocation(),
5670 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5671 << (index + 1);
5672 }
5673 return;
5674
Douglas Gregor02eb4832010-05-08 18:13:28 +00005675 case Sema::TDK_TooManyArguments:
5676 case Sema::TDK_TooFewArguments:
5677 DiagnoseArityMismatch(S, Cand, NumArgs);
5678 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005679
5680 case Sema::TDK_InstantiationDepth:
5681 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5682 return;
5683
5684 case Sema::TDK_SubstitutionFailure: {
5685 std::string ArgString;
5686 if (TemplateArgumentList *Args
5687 = Cand->DeductionFailure.getTemplateArgumentList())
5688 ArgString = S.getTemplateArgumentBindingsText(
5689 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5690 *Args);
5691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5692 << ArgString;
5693 return;
5694 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005695
John McCall8b9ed552010-02-01 18:53:26 +00005696 // TODO: diagnose these individually, then kill off
5697 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005698 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005699 case Sema::TDK_FailedOverloadResolution:
5700 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5701 return;
5702 }
5703}
5704
5705/// Generates a 'note' diagnostic for an overload candidate. We've
5706/// already generated a primary error at the call site.
5707///
5708/// It really does need to be a single diagnostic with its caret
5709/// pointed at the candidate declaration. Yes, this creates some
5710/// major challenges of technical writing. Yes, this makes pointing
5711/// out problems with specific arguments quite awkward. It's still
5712/// better than generating twenty screens of text for every failed
5713/// overload.
5714///
5715/// It would be great to be able to express per-candidate problems
5716/// more richly for those diagnostic clients that cared, but we'd
5717/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005718void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5719 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005720 FunctionDecl *Fn = Cand->Function;
5721
John McCall12f97bc2010-01-08 04:41:39 +00005722 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005723 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005724 std::string FnDesc;
5725 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005726
5727 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005728 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005729 return;
John McCall12f97bc2010-01-08 04:41:39 +00005730 }
5731
John McCalle1ac8d12010-01-13 00:25:19 +00005732 // We don't really have anything else to say about viable candidates.
5733 if (Cand->Viable) {
5734 S.NoteOverloadCandidate(Fn);
5735 return;
5736 }
John McCall0d1da222010-01-12 00:44:57 +00005737
John McCall6a61b522010-01-13 09:16:55 +00005738 switch (Cand->FailureKind) {
5739 case ovl_fail_too_many_arguments:
5740 case ovl_fail_too_few_arguments:
5741 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005742
John McCall6a61b522010-01-13 09:16:55 +00005743 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005744 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5745
John McCallfe796dd2010-01-23 05:17:32 +00005746 case ovl_fail_trivial_conversion:
5747 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005748 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005749 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005750
John McCall65eb8792010-02-25 01:37:24 +00005751 case ovl_fail_bad_conversion: {
5752 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5753 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005754 if (Cand->Conversions[I].isBad())
5755 return DiagnoseBadConversion(S, Cand, I);
5756
5757 // FIXME: this currently happens when we're called from SemaInit
5758 // when user-conversion overload fails. Figure out how to handle
5759 // those conditions and diagnose them well.
5760 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005761 }
John McCall65eb8792010-02-25 01:37:24 +00005762 }
John McCalld3224162010-01-08 00:58:21 +00005763}
5764
5765void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5766 // Desugar the type of the surrogate down to a function type,
5767 // retaining as many typedefs as possible while still showing
5768 // the function type (and, therefore, its parameter types).
5769 QualType FnType = Cand->Surrogate->getConversionType();
5770 bool isLValueReference = false;
5771 bool isRValueReference = false;
5772 bool isPointer = false;
5773 if (const LValueReferenceType *FnTypeRef =
5774 FnType->getAs<LValueReferenceType>()) {
5775 FnType = FnTypeRef->getPointeeType();
5776 isLValueReference = true;
5777 } else if (const RValueReferenceType *FnTypeRef =
5778 FnType->getAs<RValueReferenceType>()) {
5779 FnType = FnTypeRef->getPointeeType();
5780 isRValueReference = true;
5781 }
5782 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5783 FnType = FnTypePtr->getPointeeType();
5784 isPointer = true;
5785 }
5786 // Desugar down to a function type.
5787 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5788 // Reconstruct the pointer/reference as appropriate.
5789 if (isPointer) FnType = S.Context.getPointerType(FnType);
5790 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5791 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5792
5793 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5794 << FnType;
5795}
5796
5797void NoteBuiltinOperatorCandidate(Sema &S,
5798 const char *Opc,
5799 SourceLocation OpLoc,
5800 OverloadCandidate *Cand) {
5801 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5802 std::string TypeStr("operator");
5803 TypeStr += Opc;
5804 TypeStr += "(";
5805 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5806 if (Cand->Conversions.size() == 1) {
5807 TypeStr += ")";
5808 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5809 } else {
5810 TypeStr += ", ";
5811 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5812 TypeStr += ")";
5813 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5814 }
5815}
5816
5817void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5818 OverloadCandidate *Cand) {
5819 unsigned NoOperands = Cand->Conversions.size();
5820 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5821 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005822 if (ICS.isBad()) break; // all meaningless after first invalid
5823 if (!ICS.isAmbiguous()) continue;
5824
5825 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005826 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005827 }
5828}
5829
John McCall3712d9e2010-01-15 23:32:50 +00005830SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5831 if (Cand->Function)
5832 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005833 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005834 return Cand->Surrogate->getLocation();
5835 return SourceLocation();
5836}
5837
John McCallad2587a2010-01-12 00:48:53 +00005838struct CompareOverloadCandidatesForDisplay {
5839 Sema &S;
5840 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005841
5842 bool operator()(const OverloadCandidate *L,
5843 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005844 // Fast-path this check.
5845 if (L == R) return false;
5846
John McCall12f97bc2010-01-08 04:41:39 +00005847 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005848 if (L->Viable) {
5849 if (!R->Viable) return true;
5850
5851 // TODO: introduce a tri-valued comparison for overload
5852 // candidates. Would be more worthwhile if we had a sort
5853 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005854 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5855 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005856 } else if (R->Viable)
5857 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005858
John McCall3712d9e2010-01-15 23:32:50 +00005859 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005860
John McCall3712d9e2010-01-15 23:32:50 +00005861 // Criteria by which we can sort non-viable candidates:
5862 if (!L->Viable) {
5863 // 1. Arity mismatches come after other candidates.
5864 if (L->FailureKind == ovl_fail_too_many_arguments ||
5865 L->FailureKind == ovl_fail_too_few_arguments)
5866 return false;
5867 if (R->FailureKind == ovl_fail_too_many_arguments ||
5868 R->FailureKind == ovl_fail_too_few_arguments)
5869 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005870
John McCallfe796dd2010-01-23 05:17:32 +00005871 // 2. Bad conversions come first and are ordered by the number
5872 // of bad conversions and quality of good conversions.
5873 if (L->FailureKind == ovl_fail_bad_conversion) {
5874 if (R->FailureKind != ovl_fail_bad_conversion)
5875 return true;
5876
5877 // If there's any ordering between the defined conversions...
5878 // FIXME: this might not be transitive.
5879 assert(L->Conversions.size() == R->Conversions.size());
5880
5881 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005882 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5883 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005884 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5885 R->Conversions[I])) {
5886 case ImplicitConversionSequence::Better:
5887 leftBetter++;
5888 break;
5889
5890 case ImplicitConversionSequence::Worse:
5891 leftBetter--;
5892 break;
5893
5894 case ImplicitConversionSequence::Indistinguishable:
5895 break;
5896 }
5897 }
5898 if (leftBetter > 0) return true;
5899 if (leftBetter < 0) return false;
5900
5901 } else if (R->FailureKind == ovl_fail_bad_conversion)
5902 return false;
5903
John McCall3712d9e2010-01-15 23:32:50 +00005904 // TODO: others?
5905 }
5906
5907 // Sort everything else by location.
5908 SourceLocation LLoc = GetLocationForCandidate(L);
5909 SourceLocation RLoc = GetLocationForCandidate(R);
5910
5911 // Put candidates without locations (e.g. builtins) at the end.
5912 if (LLoc.isInvalid()) return false;
5913 if (RLoc.isInvalid()) return true;
5914
5915 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005916 }
5917};
5918
John McCallfe796dd2010-01-23 05:17:32 +00005919/// CompleteNonViableCandidate - Normally, overload resolution only
5920/// computes up to the first
5921void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5922 Expr **Args, unsigned NumArgs) {
5923 assert(!Cand->Viable);
5924
5925 // Don't do anything on failures other than bad conversion.
5926 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5927
5928 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005929 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005930 unsigned ConvCount = Cand->Conversions.size();
5931 while (true) {
5932 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5933 ConvIdx++;
5934 if (Cand->Conversions[ConvIdx - 1].isBad())
5935 break;
5936 }
5937
5938 if (ConvIdx == ConvCount)
5939 return;
5940
John McCall65eb8792010-02-25 01:37:24 +00005941 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5942 "remaining conversion is initialized?");
5943
Douglas Gregoradc7a702010-04-16 17:45:54 +00005944 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005945 // operation somehow.
5946 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005947
5948 const FunctionProtoType* Proto;
5949 unsigned ArgIdx = ConvIdx;
5950
5951 if (Cand->IsSurrogate) {
5952 QualType ConvType
5953 = Cand->Surrogate->getConversionType().getNonReferenceType();
5954 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5955 ConvType = ConvPtrType->getPointeeType();
5956 Proto = ConvType->getAs<FunctionProtoType>();
5957 ArgIdx--;
5958 } else if (Cand->Function) {
5959 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5960 if (isa<CXXMethodDecl>(Cand->Function) &&
5961 !isa<CXXConstructorDecl>(Cand->Function))
5962 ArgIdx--;
5963 } else {
5964 // Builtin binary operator with a bad first conversion.
5965 assert(ConvCount <= 3);
5966 for (; ConvIdx != ConvCount; ++ConvIdx)
5967 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005968 = TryCopyInitialization(S, Args[ConvIdx],
5969 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5970 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005971 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005972 return;
5973 }
5974
5975 // Fill in the rest of the conversions.
5976 unsigned NumArgsInProto = Proto->getNumArgs();
5977 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5978 if (ArgIdx < NumArgsInProto)
5979 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005980 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5981 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005982 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005983 else
5984 Cand->Conversions[ConvIdx].setEllipsis();
5985 }
5986}
5987
John McCalld3224162010-01-08 00:58:21 +00005988} // end anonymous namespace
5989
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005990/// PrintOverloadCandidates - When overload resolution fails, prints
5991/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005992/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005993void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005994Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005995 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005996 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005997 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005998 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005999 // Sort the candidates by viability and position. Sorting directly would
6000 // be prohibitive, so we make a set of pointers and sort those.
6001 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6002 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
6003 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6004 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00006005 Cand != LastCand; ++Cand) {
6006 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006007 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006008 else if (OCD == OCD_AllCandidates) {
6009 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006010 if (Cand->Function || Cand->IsSurrogate)
6011 Cands.push_back(Cand);
6012 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6013 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006014 }
6015 }
6016
John McCallad2587a2010-01-12 00:48:53 +00006017 std::sort(Cands.begin(), Cands.end(),
6018 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00006019
John McCall0d1da222010-01-12 00:44:57 +00006020 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006021
John McCall12f97bc2010-01-08 04:41:39 +00006022 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006023 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6024 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006025 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6026 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006027
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006028 // Set an arbitrary limit on the number of candidate functions we'll spam
6029 // the user with. FIXME: This limit should depend on details of the
6030 // candidate list.
6031 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6032 break;
6033 }
6034 ++CandsShown;
6035
John McCalld3224162010-01-08 00:58:21 +00006036 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00006037 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006038 else if (Cand->IsSurrogate)
6039 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006040 else {
6041 assert(Cand->Viable &&
6042 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006043 // Generally we only see ambiguities including viable builtin
6044 // operators if overload resolution got screwed up by an
6045 // ambiguous user-defined conversion.
6046 //
6047 // FIXME: It's quite possible for different conversions to see
6048 // different ambiguities, though.
6049 if (!ReportedAmbiguousConversions) {
6050 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6051 ReportedAmbiguousConversions = true;
6052 }
John McCalld3224162010-01-08 00:58:21 +00006053
John McCall0d1da222010-01-12 00:44:57 +00006054 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00006055 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006056 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006057 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006058
6059 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00006060 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006061}
6062
John McCalla0296f72010-03-19 07:35:19 +00006063static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006064 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006065 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006066
John McCalla0296f72010-03-19 07:35:19 +00006067 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006068}
6069
Douglas Gregorcd695e52008-11-10 20:40:00 +00006070/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6071/// an overloaded function (C++ [over.over]), where @p From is an
6072/// expression with overloaded function type and @p ToType is the type
6073/// we're trying to resolve to. For example:
6074///
6075/// @code
6076/// int f(double);
6077/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006078///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006079/// int (*pfd)(double) = f; // selects f(double)
6080/// @endcode
6081///
6082/// This routine returns the resulting FunctionDecl if it could be
6083/// resolved, and NULL otherwise. When @p Complain is true, this
6084/// routine will emit diagnostics if there is an error.
6085FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006086Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006087 bool Complain,
6088 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006089 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006090 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006091 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006092 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006093 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006094 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006095 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006096 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006097 FunctionType = MemTypePtr->getPointeeType();
6098 IsMember = true;
6099 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006100
Douglas Gregorcd695e52008-11-10 20:40:00 +00006101 // C++ [over.over]p1:
6102 // [...] [Note: any redundant set of parentheses surrounding the
6103 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006104 // C++ [over.over]p1:
6105 // [...] The overloaded function name can be preceded by the &
6106 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006107 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6108 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6109 if (OvlExpr->hasExplicitTemplateArgs()) {
6110 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6111 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006112 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00006113
6114 // We expect a pointer or reference to function, or a function pointer.
6115 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6116 if (!FunctionType->isFunctionType()) {
6117 if (Complain)
6118 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6119 << OvlExpr->getName() << ToType;
6120
6121 return 0;
6122 }
6123
6124 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006125
Douglas Gregorcd695e52008-11-10 20:40:00 +00006126 // Look through all of the overloaded functions, searching for one
6127 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006128 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006129 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6130
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006131 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006132 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6133 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006134 // Look through any using declarations to find the underlying function.
6135 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6136
Douglas Gregorcd695e52008-11-10 20:40:00 +00006137 // C++ [over.over]p3:
6138 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006139 // targets of type "pointer-to-function" or "reference-to-function."
6140 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006141 // type "pointer-to-member-function."
6142 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006143
Mike Stump11289f42009-09-09 15:08:12 +00006144 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006145 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006146 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006147 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006148 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006149 // static when converting to member pointer.
6150 if (Method->isStatic() == IsMember)
6151 continue;
6152 } else if (IsMember)
6153 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006154
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006155 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006156 // If the name is a function template, template argument deduction is
6157 // done (14.8.2.2), and if the argument deduction succeeds, the
6158 // resulting template argument list is used to generate a single
6159 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006160 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006161 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006162 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006163 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006164 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006165 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006166 FunctionType, Specialization, Info)) {
6167 // FIXME: make a note of the failed deduction for diagnostics.
6168 (void)Result;
6169 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006170 // FIXME: If the match isn't exact, shouldn't we just drop this as
6171 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006172 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006173 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006174 Matches.push_back(std::make_pair(I.getPair(),
6175 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006176 }
John McCalld14a8642009-11-21 08:51:07 +00006177
6178 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006179 }
Mike Stump11289f42009-09-09 15:08:12 +00006180
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006181 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006182 // Skip non-static functions when converting to pointer, and static
6183 // when converting to member pointer.
6184 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006185 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006186
6187 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006188 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006189 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006190 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006191 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006192
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006193 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006194 QualType ResultTy;
6195 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6196 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6197 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006198 Matches.push_back(std::make_pair(I.getPair(),
6199 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006200 FoundNonTemplateFunction = true;
6201 }
Mike Stump11289f42009-09-09 15:08:12 +00006202 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006203 }
6204
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006205 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006206 if (Matches.empty()) {
6207 if (Complain) {
6208 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6209 << OvlExpr->getName() << FunctionType;
6210 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6211 E = OvlExpr->decls_end();
6212 I != E; ++I)
6213 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6214 NoteOverloadCandidate(F);
6215 }
6216
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006217 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006218 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006219 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006220 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006221 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006222 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006223 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006224 return Result;
6225 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006226
6227 // C++ [over.over]p4:
6228 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006229 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006230 // [...] and any given function template specialization F1 is
6231 // eliminated if the set contains a second function template
6232 // specialization whose function template is more specialized
6233 // than the function template of F1 according to the partial
6234 // ordering rules of 14.5.5.2.
6235
6236 // The algorithm specified above is quadratic. We instead use a
6237 // two-pass algorithm (similar to the one used to identify the
6238 // best viable function in an overload set) that identifies the
6239 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006240
6241 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6242 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6243 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006244
6245 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006246 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006247 TPOC_Other, From->getLocStart(),
6248 PDiag(),
6249 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006250 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006251 PDiag(diag::note_ovl_candidate)
6252 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006253 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006254 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006255 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006256 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006257 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006258 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6259 }
John McCall58cc69d2010-01-27 01:50:18 +00006260 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006261 }
Mike Stump11289f42009-09-09 15:08:12 +00006262
Douglas Gregorfae1d712009-09-26 03:56:17 +00006263 // [...] any function template specializations in the set are
6264 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006265 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006266 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006267 ++I;
6268 else {
John McCalla0296f72010-03-19 07:35:19 +00006269 Matches[I] = Matches[--N];
6270 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006271 }
6272 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006273
Mike Stump11289f42009-09-09 15:08:12 +00006274 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006275 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006276 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006277 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006278 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006279 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006280 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006281 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6282 }
John McCalla0296f72010-03-19 07:35:19 +00006283 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006284 }
Mike Stump11289f42009-09-09 15:08:12 +00006285
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006286 // FIXME: We should probably return the same thing that BestViableFunction
6287 // returns (even if we issue the diagnostics here).
6288 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006289 << Matches[0].second->getDeclName();
6290 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6291 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006292 return 0;
6293}
6294
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006295/// \brief Given an expression that refers to an overloaded function, try to
6296/// resolve that overloaded function expression down to a single function.
6297///
6298/// This routine can only resolve template-ids that refer to a single function
6299/// template, where that template-id refers to a single template whose template
6300/// arguments are either provided by the template-id or have defaults,
6301/// as described in C++0x [temp.arg.explicit]p3.
6302FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6303 // C++ [over.over]p1:
6304 // [...] [Note: any redundant set of parentheses surrounding the
6305 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006306 // C++ [over.over]p1:
6307 // [...] The overloaded function name can be preceded by the &
6308 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006309
6310 if (From->getType() != Context.OverloadTy)
6311 return 0;
6312
6313 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006314
6315 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006316 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006317 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006318
6319 TemplateArgumentListInfo ExplicitTemplateArgs;
6320 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006321
6322 // Look through all of the overloaded functions, searching for one
6323 // whose type matches exactly.
6324 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006325 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6326 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006327 // C++0x [temp.arg.explicit]p3:
6328 // [...] In contexts where deduction is done and fails, or in contexts
6329 // where deduction is not done, if a template argument list is
6330 // specified and it, along with any default template arguments,
6331 // identifies a single function template specialization, then the
6332 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006333 FunctionTemplateDecl *FunctionTemplate
6334 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006335
6336 // C++ [over.over]p2:
6337 // If the name is a function template, template argument deduction is
6338 // done (14.8.2.2), and if the argument deduction succeeds, the
6339 // resulting template argument list is used to generate a single
6340 // function template specialization, which is added to the set of
6341 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006342 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006343 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006344 if (TemplateDeductionResult Result
6345 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6346 Specialization, Info)) {
6347 // FIXME: make a note of the failed deduction for diagnostics.
6348 (void)Result;
6349 continue;
6350 }
6351
6352 // Multiple matches; we can't resolve to a single declaration.
6353 if (Matched)
6354 return 0;
6355
6356 Matched = Specialization;
6357 }
6358
6359 return Matched;
6360}
6361
Douglas Gregorcabea402009-09-22 15:41:20 +00006362/// \brief Add a single candidate to the overload set.
6363static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006364 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006365 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006366 Expr **Args, unsigned NumArgs,
6367 OverloadCandidateSet &CandidateSet,
6368 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006369 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006370 if (isa<UsingShadowDecl>(Callee))
6371 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6372
Douglas Gregorcabea402009-09-22 15:41:20 +00006373 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006374 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006375 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006376 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006377 return;
John McCalld14a8642009-11-21 08:51:07 +00006378 }
6379
6380 if (FunctionTemplateDecl *FuncTemplate
6381 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006382 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6383 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006384 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006385 return;
6386 }
6387
6388 assert(false && "unhandled case in overloaded call candidate");
6389
6390 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006391}
6392
6393/// \brief Add the overload candidates named by callee and/or found by argument
6394/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006395void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006396 Expr **Args, unsigned NumArgs,
6397 OverloadCandidateSet &CandidateSet,
6398 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006399
6400#ifndef NDEBUG
6401 // Verify that ArgumentDependentLookup is consistent with the rules
6402 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006403 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006404 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6405 // and let Y be the lookup set produced by argument dependent
6406 // lookup (defined as follows). If X contains
6407 //
6408 // -- a declaration of a class member, or
6409 //
6410 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006411 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006412 //
6413 // -- a declaration that is neither a function or a function
6414 // template
6415 //
6416 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006417
John McCall57500772009-12-16 12:17:52 +00006418 if (ULE->requiresADL()) {
6419 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6420 E = ULE->decls_end(); I != E; ++I) {
6421 assert(!(*I)->getDeclContext()->isRecord());
6422 assert(isa<UsingShadowDecl>(*I) ||
6423 !(*I)->getDeclContext()->isFunctionOrMethod());
6424 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006425 }
6426 }
6427#endif
6428
John McCall57500772009-12-16 12:17:52 +00006429 // It would be nice to avoid this copy.
6430 TemplateArgumentListInfo TABuffer;
6431 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6432 if (ULE->hasExplicitTemplateArgs()) {
6433 ULE->copyTemplateArgumentsInto(TABuffer);
6434 ExplicitTemplateArgs = &TABuffer;
6435 }
6436
6437 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6438 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006439 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006440 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006441 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006442
John McCall57500772009-12-16 12:17:52 +00006443 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006444 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6445 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006446 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006447 CandidateSet,
6448 PartialOverloading);
6449}
John McCalld681c392009-12-16 08:11:27 +00006450
6451/// Attempts to recover from a call where no functions were found.
6452///
6453/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006454static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006455BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006456 UnresolvedLookupExpr *ULE,
6457 SourceLocation LParenLoc,
6458 Expr **Args, unsigned NumArgs,
6459 SourceLocation *CommaLocs,
6460 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006461
6462 CXXScopeSpec SS;
6463 if (ULE->getQualifier()) {
6464 SS.setScopeRep(ULE->getQualifier());
6465 SS.setRange(ULE->getQualifierRange());
6466 }
6467
John McCall57500772009-12-16 12:17:52 +00006468 TemplateArgumentListInfo TABuffer;
6469 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6470 if (ULE->hasExplicitTemplateArgs()) {
6471 ULE->copyTemplateArgumentsInto(TABuffer);
6472 ExplicitTemplateArgs = &TABuffer;
6473 }
6474
John McCalld681c392009-12-16 08:11:27 +00006475 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6476 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006477 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorb412e172010-07-25 18:17:45 +00006478 return SemaRef.ExprError();
John McCalld681c392009-12-16 08:11:27 +00006479
John McCall57500772009-12-16 12:17:52 +00006480 assert(!R.empty() && "lookup results empty despite recovery");
6481
6482 // Build an implicit member call if appropriate. Just drop the
6483 // casts and such from the call, we don't really care.
6484 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6485 if ((*R.begin())->isCXXClassMember())
6486 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6487 else if (ExplicitTemplateArgs)
6488 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6489 else
6490 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6491
6492 if (NewFn.isInvalid())
Douglas Gregorb412e172010-07-25 18:17:45 +00006493 return SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006494
6495 // This shouldn't cause an infinite loop because we're giving it
6496 // an expression with non-empty lookup results, which should never
6497 // end up here.
6498 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6499 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6500 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006501}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006502
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006503/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006504/// (which eventually refers to the declaration Func) and the call
6505/// arguments Args/NumArgs, attempt to resolve the function call down
6506/// to a specific function. If overload resolution succeeds, returns
6507/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006508/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006509/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006510Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006511Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006512 SourceLocation LParenLoc,
6513 Expr **Args, unsigned NumArgs,
6514 SourceLocation *CommaLocs,
6515 SourceLocation RParenLoc) {
6516#ifndef NDEBUG
6517 if (ULE->requiresADL()) {
6518 // To do ADL, we must have found an unqualified name.
6519 assert(!ULE->getQualifier() && "qualified name with ADL");
6520
6521 // We don't perform ADL for implicit declarations of builtins.
6522 // Verify that this was correctly set up.
6523 FunctionDecl *F;
6524 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6525 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6526 F->getBuiltinID() && F->isImplicit())
6527 assert(0 && "performing ADL for builtin");
6528
6529 // We don't perform ADL in C.
6530 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6531 }
6532#endif
6533
John McCallbc077cf2010-02-08 23:07:23 +00006534 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006535
John McCall57500772009-12-16 12:17:52 +00006536 // Add the functions denoted by the callee to the set of candidate
6537 // functions, including those from argument-dependent lookup.
6538 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006539
6540 // If we found nothing, try to recover.
6541 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6542 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006543 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006544 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006545 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006546
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006547 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006548 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006549 case OR_Success: {
6550 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006551 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006552 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006553 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006554 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6555 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006556
6557 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006558 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006559 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006560 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006561 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006562 break;
6563
6564 case OR_Ambiguous:
6565 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006566 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006567 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006568 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006569
6570 case OR_Deleted:
6571 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6572 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006573 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006574 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006575 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006576 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006577 }
6578
Douglas Gregorb412e172010-07-25 18:17:45 +00006579 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006580 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006581}
6582
John McCall4c4c1df2010-01-26 03:27:55 +00006583static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006584 return Functions.size() > 1 ||
6585 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6586}
6587
Douglas Gregor084d8552009-03-13 23:49:33 +00006588/// \brief Create a unary operation that may resolve to an overloaded
6589/// operator.
6590///
6591/// \param OpLoc The location of the operator itself (e.g., '*').
6592///
6593/// \param OpcIn The UnaryOperator::Opcode that describes this
6594/// operator.
6595///
6596/// \param Functions The set of non-member functions that will be
6597/// considered by overload resolution. The caller needs to build this
6598/// set based on the context using, e.g.,
6599/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6600/// set should not contain any member functions; those will be added
6601/// by CreateOverloadedUnaryOp().
6602///
6603/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006604Sema::OwningExprResult
6605Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6606 const UnresolvedSetImpl &Fns,
6607 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006608 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6609 Expr *Input = (Expr *)input.get();
6610
6611 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6612 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6613 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6614
6615 Expr *Args[2] = { Input, 0 };
6616 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006617
Douglas Gregor084d8552009-03-13 23:49:33 +00006618 // For post-increment and post-decrement, add the implicit '0' as
6619 // the second argument, so that we know this is a post-increment or
6620 // post-decrement.
6621 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6622 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006623 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006624 SourceLocation());
6625 NumArgs = 2;
6626 }
6627
6628 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006629 if (Fns.empty())
6630 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6631 Opc,
6632 Context.DependentTy,
6633 OpLoc));
6634
John McCall58cc69d2010-01-27 01:50:18 +00006635 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006636 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006637 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006638 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006639 /*ADL*/ true, IsOverloaded(Fns),
6640 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006641 input.release();
6642 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6643 &Args[0], NumArgs,
6644 Context.DependentTy,
6645 OpLoc));
6646 }
6647
6648 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006649 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006650
6651 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006652 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006653
6654 // Add operator candidates that are member functions.
6655 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6656
John McCall4c4c1df2010-01-26 03:27:55 +00006657 // Add candidates from ADL.
6658 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006659 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006660 /*ExplicitTemplateArgs*/ 0,
6661 CandidateSet);
6662
Douglas Gregor084d8552009-03-13 23:49:33 +00006663 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006664 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006665
6666 // Perform overload resolution.
6667 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006668 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006669 case OR_Success: {
6670 // We found a built-in operator or an overloaded operator.
6671 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006672
Douglas Gregor084d8552009-03-13 23:49:33 +00006673 if (FnDecl) {
6674 // We matched an overloaded operator. Build a call to that
6675 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006676
Douglas Gregor084d8552009-03-13 23:49:33 +00006677 // Convert the arguments.
6678 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006679 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006680
John McCall16df1e52010-03-30 21:47:33 +00006681 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6682 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006683 return ExprError();
6684 } else {
6685 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006686 OwningExprResult InputInit
6687 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006688 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006689 SourceLocation(),
6690 move(input));
6691 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006692 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006693
Douglas Gregore6600372009-12-23 17:40:29 +00006694 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006695 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006696 }
6697
John McCall4fa0d5f2010-05-06 18:15:07 +00006698 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6699
Douglas Gregor084d8552009-03-13 23:49:33 +00006700 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006701 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006702
Douglas Gregor084d8552009-03-13 23:49:33 +00006703 // Build the actual expression node.
6704 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6705 SourceLocation());
6706 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006707
Douglas Gregor084d8552009-03-13 23:49:33 +00006708 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006709 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006710 ExprOwningPtr<CallExpr> TheCall(this,
6711 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006712 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006713
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006714 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6715 FnDecl))
6716 return ExprError();
6717
6718 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006719 } else {
6720 // We matched a built-in operator. Convert the arguments, then
6721 // break out so that we will build the appropriate built-in
6722 // operator node.
6723 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006724 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006725 return ExprError();
6726
6727 break;
6728 }
6729 }
6730
6731 case OR_No_Viable_Function:
6732 // No viable function; fall through to handling this as a
6733 // built-in operator, which will produce an error message for us.
6734 break;
6735
6736 case OR_Ambiguous:
6737 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6738 << UnaryOperator::getOpcodeStr(Opc)
6739 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006740 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006741 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006742 return ExprError();
6743
6744 case OR_Deleted:
6745 Diag(OpLoc, diag::err_ovl_deleted_oper)
6746 << Best->Function->isDeleted()
6747 << UnaryOperator::getOpcodeStr(Opc)
6748 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006749 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006750 return ExprError();
6751 }
6752
6753 // Either we found no viable overloaded operator or we matched a
6754 // built-in operator. In either case, fall through to trying to
6755 // build a built-in operation.
6756 input.release();
6757 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6758}
6759
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006760/// \brief Create a binary operation that may resolve to an overloaded
6761/// operator.
6762///
6763/// \param OpLoc The location of the operator itself (e.g., '+').
6764///
6765/// \param OpcIn The BinaryOperator::Opcode that describes this
6766/// operator.
6767///
6768/// \param Functions The set of non-member functions that will be
6769/// considered by overload resolution. The caller needs to build this
6770/// set based on the context using, e.g.,
6771/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6772/// set should not contain any member functions; those will be added
6773/// by CreateOverloadedBinOp().
6774///
6775/// \param LHS Left-hand argument.
6776/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006777Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006778Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006779 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006780 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006781 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006782 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006783 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006784
6785 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6786 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6787 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6788
6789 // If either side is type-dependent, create an appropriate dependent
6790 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006791 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006792 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006793 // If there are no functions to store, just build a dependent
6794 // BinaryOperator or CompoundAssignment.
6795 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6796 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6797 Context.DependentTy, OpLoc));
6798
6799 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6800 Context.DependentTy,
6801 Context.DependentTy,
6802 Context.DependentTy,
6803 OpLoc));
6804 }
John McCall4c4c1df2010-01-26 03:27:55 +00006805
6806 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006807 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006808 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006809 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006810 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006811 /*ADL*/ true, IsOverloaded(Fns),
6812 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006813 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006814 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006815 Context.DependentTy,
6816 OpLoc));
6817 }
6818
6819 // If this is the .* operator, which is not overloadable, just
6820 // create a built-in binary operator.
6821 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006822 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006823
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006824 // If this is the assignment operator, we only perform overload resolution
6825 // if the left-hand side is a class or enumeration type. This is actually
6826 // a hack. The standard requires that we do overload resolution between the
6827 // various built-in candidates, but as DR507 points out, this can lead to
6828 // problems. So we do it this way, which pretty much follows what GCC does.
6829 // Note that we go the traditional code path for compound assignment forms.
6830 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006831 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006832
Douglas Gregor084d8552009-03-13 23:49:33 +00006833 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006834 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006835
6836 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006837 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006838
6839 // Add operator candidates that are member functions.
6840 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6841
John McCall4c4c1df2010-01-26 03:27:55 +00006842 // Add candidates from ADL.
6843 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6844 Args, 2,
6845 /*ExplicitTemplateArgs*/ 0,
6846 CandidateSet);
6847
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006848 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006849 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006850
6851 // Perform overload resolution.
6852 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006853 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006854 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006855 // We found a built-in operator or an overloaded operator.
6856 FunctionDecl *FnDecl = Best->Function;
6857
6858 if (FnDecl) {
6859 // We matched an overloaded operator. Build a call to that
6860 // operator.
6861
6862 // Convert the arguments.
6863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006864 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006865 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006866
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006867 OwningExprResult Arg1
6868 = PerformCopyInitialization(
6869 InitializedEntity::InitializeParameter(
6870 FnDecl->getParamDecl(0)),
6871 SourceLocation(),
6872 Owned(Args[1]));
6873 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006874 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006875
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006876 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006877 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006878 return ExprError();
6879
6880 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006881 } else {
6882 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006883 OwningExprResult Arg0
6884 = PerformCopyInitialization(
6885 InitializedEntity::InitializeParameter(
6886 FnDecl->getParamDecl(0)),
6887 SourceLocation(),
6888 Owned(Args[0]));
6889 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006890 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006891
6892 OwningExprResult Arg1
6893 = PerformCopyInitialization(
6894 InitializedEntity::InitializeParameter(
6895 FnDecl->getParamDecl(1)),
6896 SourceLocation(),
6897 Owned(Args[1]));
6898 if (Arg1.isInvalid())
6899 return ExprError();
6900 Args[0] = LHS = Arg0.takeAs<Expr>();
6901 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006902 }
6903
John McCall4fa0d5f2010-05-06 18:15:07 +00006904 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6905
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006906 // Determine the result type
6907 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00006908 = FnDecl->getType()->getAs<FunctionType>()
6909 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006910
6911 // Build the actual expression node.
6912 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006913 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006914 UsualUnaryConversions(FnExpr);
6915
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006916 ExprOwningPtr<CXXOperatorCallExpr>
6917 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6918 Args, 2, ResultTy,
6919 OpLoc));
6920
6921 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6922 FnDecl))
6923 return ExprError();
6924
6925 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006926 } else {
6927 // We matched a built-in operator. Convert the arguments, then
6928 // break out so that we will build the appropriate built-in
6929 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006930 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006931 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006932 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006933 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006934 return ExprError();
6935
6936 break;
6937 }
6938 }
6939
Douglas Gregor66950a32009-09-30 21:46:01 +00006940 case OR_No_Viable_Function: {
6941 // C++ [over.match.oper]p9:
6942 // If the operator is the operator , [...] and there are no
6943 // viable functions, then the operator is assumed to be the
6944 // built-in operator and interpreted according to clause 5.
6945 if (Opc == BinaryOperator::Comma)
6946 break;
6947
Sebastian Redl027de2a2009-05-21 11:50:50 +00006948 // For class as left operand for assignment or compound assigment operator
6949 // do not fall through to handling in built-in, but report that no overloaded
6950 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006951 OwningExprResult Result = ExprError();
6952 if (Args[0]->getType()->isRecordType() &&
6953 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006954 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6955 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006956 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006957 } else {
6958 // No viable function; try to create a built-in operation, which will
6959 // produce an error. Then, show the non-viable candidates.
6960 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006961 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006962 assert(Result.isInvalid() &&
6963 "C++ binary operator overloading is missing candidates!");
6964 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006965 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006966 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006967 return move(Result);
6968 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006969
6970 case OR_Ambiguous:
6971 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6972 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006973 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006974 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006975 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006976 return ExprError();
6977
6978 case OR_Deleted:
6979 Diag(OpLoc, diag::err_ovl_deleted_oper)
6980 << Best->Function->isDeleted()
6981 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006982 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006983 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006984 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006985 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006986
Douglas Gregor66950a32009-09-30 21:46:01 +00006987 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006988 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006989}
6990
Sebastian Redladba46e2009-10-29 20:17:01 +00006991Action::OwningExprResult
6992Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6993 SourceLocation RLoc,
6994 ExprArg Base, ExprArg Idx) {
6995 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6996 static_cast<Expr*>(Idx.get()) };
6997 DeclarationName OpName =
6998 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6999
7000 // If either side is type-dependent, create an appropriate dependent
7001 // expression.
7002 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7003
John McCall58cc69d2010-01-27 01:50:18 +00007004 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007005 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007006 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00007007 0, SourceRange(), OpName, LLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007008 /*ADL*/ true, /*Overloaded*/ false,
7009 UnresolvedSetIterator(),
7010 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007011 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007012
7013 Base.release();
7014 Idx.release();
7015 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7016 Args, 2,
7017 Context.DependentTy,
7018 RLoc));
7019 }
7020
7021 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007022 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007023
7024 // Subscript can only be overloaded as a member function.
7025
7026 // Add operator candidates that are member functions.
7027 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7028
7029 // Add builtin operator candidates.
7030 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7031
7032 // Perform overload resolution.
7033 OverloadCandidateSet::iterator Best;
7034 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7035 case OR_Success: {
7036 // We found a built-in operator or an overloaded operator.
7037 FunctionDecl *FnDecl = Best->Function;
7038
7039 if (FnDecl) {
7040 // We matched an overloaded operator. Build a call to that
7041 // operator.
7042
John McCalla0296f72010-03-19 07:35:19 +00007043 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007044 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007045
Sebastian Redladba46e2009-10-29 20:17:01 +00007046 // Convert the arguments.
7047 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007048 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007049 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007050 return ExprError();
7051
Anders Carlssona68e51e2010-01-29 18:37:50 +00007052 // Convert the arguments.
7053 OwningExprResult InputInit
7054 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7055 FnDecl->getParamDecl(0)),
7056 SourceLocation(),
7057 Owned(Args[1]));
7058 if (InputInit.isInvalid())
7059 return ExprError();
7060
7061 Args[1] = InputInit.takeAs<Expr>();
7062
Sebastian Redladba46e2009-10-29 20:17:01 +00007063 // Determine the result type
7064 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007065 = FnDecl->getType()->getAs<FunctionType>()
7066 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007067
7068 // Build the actual expression node.
7069 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7070 LLoc);
7071 UsualUnaryConversions(FnExpr);
7072
7073 Base.release();
7074 Idx.release();
7075 ExprOwningPtr<CXXOperatorCallExpr>
7076 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7077 FnExpr, Args, 2,
7078 ResultTy, RLoc));
7079
7080 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7081 FnDecl))
7082 return ExprError();
7083
7084 return MaybeBindToTemporary(TheCall.release());
7085 } else {
7086 // We matched a built-in operator. Convert the arguments, then
7087 // break out so that we will build the appropriate built-in
7088 // operator node.
7089 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007090 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007091 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007092 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007093 return ExprError();
7094
7095 break;
7096 }
7097 }
7098
7099 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007100 if (CandidateSet.empty())
7101 Diag(LLoc, diag::err_ovl_no_oper)
7102 << Args[0]->getType() << /*subscript*/ 0
7103 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7104 else
7105 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7106 << Args[0]->getType()
7107 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007108 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00007109 "[]", LLoc);
7110 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007111 }
7112
7113 case OR_Ambiguous:
7114 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7115 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007116 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00007117 "[]", LLoc);
7118 return ExprError();
7119
7120 case OR_Deleted:
7121 Diag(LLoc, diag::err_ovl_deleted_oper)
7122 << Best->Function->isDeleted() << "[]"
7123 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007124 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00007125 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007126 return ExprError();
7127 }
7128
7129 // We matched a built-in operator; build it.
7130 Base.release();
7131 Idx.release();
7132 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7133 Owned(Args[1]), RLoc);
7134}
7135
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007136/// BuildCallToMemberFunction - Build a call to a member
7137/// function. MemExpr is the expression that refers to the member
7138/// function (and includes the object parameter), Args/NumArgs are the
7139/// arguments to the function call (not including the object
7140/// parameter). The caller needs to validate that the member
7141/// expression refers to a member function or an overloaded member
7142/// function.
John McCall2d74de92009-12-01 22:10:20 +00007143Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007144Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7145 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007146 unsigned NumArgs, SourceLocation *CommaLocs,
7147 SourceLocation RParenLoc) {
7148 // Dig out the member expression. This holds both the object
7149 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007150 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7151
John McCall10eae182009-11-30 22:42:35 +00007152 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007153 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007154 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007155 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007156 if (isa<MemberExpr>(NakedMemExpr)) {
7157 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007158 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007159 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007160 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007161 } else {
7162 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007163 Qualifier = UnresExpr->getQualifier();
7164
John McCall6e9f8f62009-12-03 04:06:58 +00007165 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007166
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007167 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007168 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007169
John McCall2d74de92009-12-01 22:10:20 +00007170 // FIXME: avoid copy.
7171 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7172 if (UnresExpr->hasExplicitTemplateArgs()) {
7173 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7174 TemplateArgs = &TemplateArgsBuffer;
7175 }
7176
John McCall10eae182009-11-30 22:42:35 +00007177 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7178 E = UnresExpr->decls_end(); I != E; ++I) {
7179
John McCall6e9f8f62009-12-03 04:06:58 +00007180 NamedDecl *Func = *I;
7181 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7182 if (isa<UsingShadowDecl>(Func))
7183 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7184
John McCall10eae182009-11-30 22:42:35 +00007185 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007186 // If explicit template arguments were provided, we can't call a
7187 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007188 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007189 continue;
7190
John McCalla0296f72010-03-19 07:35:19 +00007191 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007192 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007193 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007194 } else {
John McCall10eae182009-11-30 22:42:35 +00007195 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007196 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007197 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007198 CandidateSet,
7199 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007200 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007201 }
Mike Stump11289f42009-09-09 15:08:12 +00007202
John McCall10eae182009-11-30 22:42:35 +00007203 DeclarationName DeclName = UnresExpr->getMemberName();
7204
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007205 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00007206 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007207 case OR_Success:
7208 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007209 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007210 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007211 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007212 break;
7213
7214 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007215 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007216 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007217 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007218 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007219 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007220 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007221
7222 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007223 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007224 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007225 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007226 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007227 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007228
7229 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007230 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007231 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007232 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007233 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007234 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007235 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007236 }
7237
John McCall16df1e52010-03-30 21:47:33 +00007238 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007239
John McCall2d74de92009-12-01 22:10:20 +00007240 // If overload resolution picked a static member, build a
7241 // non-member call based on that function.
7242 if (Method->isStatic()) {
7243 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7244 Args, NumArgs, RParenLoc);
7245 }
7246
John McCall10eae182009-11-30 22:42:35 +00007247 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007248 }
7249
7250 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00007251 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00007252 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00007253 NumArgs,
Douglas Gregor603d81b2010-07-13 08:18:22 +00007254 Method->getCallResultType(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007255 RParenLoc));
7256
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007257 // Check for a valid return type.
7258 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7259 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00007260 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007261
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007262 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007263 // We only need to do this if there was actually an overload; otherwise
7264 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007265 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007266 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007267 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7268 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007269 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007270 MemExpr->setBase(ObjectArg);
7271
7272 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007273 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00007274 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007275 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007276 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007277
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007278 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00007279 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007280
John McCall2d74de92009-12-01 22:10:20 +00007281 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007282}
7283
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007284/// BuildCallToObjectOfClassType - Build a call to an object of class
7285/// type (C++ [over.call.object]), which can end up invoking an
7286/// overloaded function call operator (@c operator()) or performing a
7287/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007288Sema::ExprResult
7289Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007290 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007291 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007292 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007293 SourceLocation RParenLoc) {
7294 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007295 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007296
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007297 // C++ [over.call.object]p1:
7298 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007299 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007300 // candidate functions includes at least the function call
7301 // operators of T. The function call operators of T are obtained by
7302 // ordinary lookup of the name operator() in the context of
7303 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007304 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007305 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007306
7307 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007308 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007309 << Object->getSourceRange()))
7310 return true;
7311
John McCall27b18f82009-11-17 02:14:36 +00007312 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7313 LookupQualifiedName(R, Record->getDecl());
7314 R.suppressDiagnostics();
7315
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007316 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007317 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007318 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007319 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007320 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007321 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007322
Douglas Gregorab7897a2008-11-19 22:57:39 +00007323 // C++ [over.call.object]p2:
7324 // In addition, for each conversion function declared in T of the
7325 // form
7326 //
7327 // operator conversion-type-id () cv-qualifier;
7328 //
7329 // where cv-qualifier is the same cv-qualification as, or a
7330 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007331 // denotes the type "pointer to function of (P1,...,Pn) returning
7332 // R", or the type "reference to pointer to function of
7333 // (P1,...,Pn) returning R", or the type "reference to function
7334 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007335 // is also considered as a candidate function. Similarly,
7336 // surrogate call functions are added to the set of candidate
7337 // functions for each conversion function declared in an
7338 // accessible base class provided the function is not hidden
7339 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007340 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007341 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007342 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007343 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007344 NamedDecl *D = *I;
7345 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7346 if (isa<UsingShadowDecl>(D))
7347 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7348
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007349 // Skip over templated conversion functions; they aren't
7350 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007351 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007352 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007353
John McCall6e9f8f62009-12-03 04:06:58 +00007354 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007355
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007356 // Strip the reference type (if any) and then the pointer type (if
7357 // any) to get down to what might be a function type.
7358 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7359 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7360 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007361
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007362 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007363 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007364 Object->getType(), Args, NumArgs,
7365 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007366 }
Mike Stump11289f42009-09-09 15:08:12 +00007367
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007368 // Perform overload resolution.
7369 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007370 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007371 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007372 // Overload resolution succeeded; we'll build the appropriate call
7373 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007374 break;
7375
7376 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007377 if (CandidateSet.empty())
7378 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7379 << Object->getType() << /*call*/ 1
7380 << Object->getSourceRange();
7381 else
7382 Diag(Object->getSourceRange().getBegin(),
7383 diag::err_ovl_no_viable_object_call)
7384 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007385 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007386 break;
7387
7388 case OR_Ambiguous:
7389 Diag(Object->getSourceRange().getBegin(),
7390 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007391 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007392 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007393 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007394
7395 case OR_Deleted:
7396 Diag(Object->getSourceRange().getBegin(),
7397 diag::err_ovl_deleted_object_call)
7398 << Best->Function->isDeleted()
7399 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007400 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007401 break;
Mike Stump11289f42009-09-09 15:08:12 +00007402 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007403
Douglas Gregorb412e172010-07-25 18:17:45 +00007404 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007405 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007406
Douglas Gregorab7897a2008-11-19 22:57:39 +00007407 if (Best->Function == 0) {
7408 // Since there is no function declaration, this is one of the
7409 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007410 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007411 = cast<CXXConversionDecl>(
7412 Best->Conversions[0].UserDefined.ConversionFunction);
7413
John McCalla0296f72010-03-19 07:35:19 +00007414 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007415 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007416
Douglas Gregorab7897a2008-11-19 22:57:39 +00007417 // We selected one of the surrogate functions that converts the
7418 // object parameter to a function pointer. Perform the conversion
7419 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007420
7421 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007422 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007423 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7424 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007425
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007426 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007427 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007428 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007429 }
7430
John McCalla0296f72010-03-19 07:35:19 +00007431 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007432 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007433
Douglas Gregorab7897a2008-11-19 22:57:39 +00007434 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7435 // that calls this method, using Object for the implicit object
7436 // parameter and passing along the remaining arguments.
7437 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007438 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007439
7440 unsigned NumArgsInProto = Proto->getNumArgs();
7441 unsigned NumArgsToCheck = NumArgs;
7442
7443 // Build the full argument list for the method call (the
7444 // implicit object parameter is placed at the beginning of the
7445 // list).
7446 Expr **MethodArgs;
7447 if (NumArgs < NumArgsInProto) {
7448 NumArgsToCheck = NumArgsInProto;
7449 MethodArgs = new Expr*[NumArgsInProto + 1];
7450 } else {
7451 MethodArgs = new Expr*[NumArgs + 1];
7452 }
7453 MethodArgs[0] = Object;
7454 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7455 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007456
7457 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007458 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007459 UsualUnaryConversions(NewFn);
7460
7461 // Once we've built TheCall, all of the expressions are properly
7462 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007463 QualType ResultTy = Method->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00007464 ExprOwningPtr<CXXOperatorCallExpr>
7465 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007466 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007467 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007468 delete [] MethodArgs;
7469
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007470 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7471 Method))
7472 return true;
7473
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007474 // We may have default arguments. If so, we need to allocate more
7475 // slots in the call for them.
7476 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007477 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007478 else if (NumArgs > NumArgsInProto)
7479 NumArgsToCheck = NumArgsInProto;
7480
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007481 bool IsError = false;
7482
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007483 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007484 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007485 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007486 TheCall->setArg(0, Object);
7487
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007488
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007489 // Check the argument types.
7490 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007491 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007492 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007493 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007494
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007495 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007496
7497 OwningExprResult InputInit
7498 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7499 Method->getParamDecl(i)),
7500 SourceLocation(), Owned(Arg));
7501
7502 IsError |= InputInit.isInvalid();
7503 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007504 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007505 OwningExprResult DefArg
7506 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7507 if (DefArg.isInvalid()) {
7508 IsError = true;
7509 break;
7510 }
7511
7512 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007513 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007514
7515 TheCall->setArg(i + 1, Arg);
7516 }
7517
7518 // If this is a variadic call, handle args passed through "...".
7519 if (Proto->isVariadic()) {
7520 // Promote the arguments (C99 6.5.2.2p7).
7521 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7522 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007523 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007524 TheCall->setArg(i + 1, Arg);
7525 }
7526 }
7527
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007528 if (IsError) return true;
7529
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007530 if (CheckFunctionCall(Method, TheCall.get()))
7531 return true;
7532
Douglas Gregore5e775b2010-04-13 15:50:39 +00007533 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007534}
7535
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007536/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007537/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007538/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007539Sema::OwningExprResult
7540Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7541 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007542 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007543
John McCallbc077cf2010-02-08 23:07:23 +00007544 SourceLocation Loc = Base->getExprLoc();
7545
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007546 // C++ [over.ref]p1:
7547 //
7548 // [...] An expression x->m is interpreted as (x.operator->())->m
7549 // for a class object x of type T if T::operator->() exists and if
7550 // the operator is selected as the best match function by the
7551 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007552 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007553 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007554 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007555
John McCallbc077cf2010-02-08 23:07:23 +00007556 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007557 PDiag(diag::err_typecheck_incomplete_tag)
7558 << Base->getSourceRange()))
7559 return ExprError();
7560
John McCall27b18f82009-11-17 02:14:36 +00007561 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7562 LookupQualifiedName(R, BaseRecord->getDecl());
7563 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007564
7565 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007566 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007567 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007568 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007569 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007570
7571 // Perform overload resolution.
7572 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007573 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007574 case OR_Success:
7575 // Overload resolution succeeded; we'll build the call below.
7576 break;
7577
7578 case OR_No_Viable_Function:
7579 if (CandidateSet.empty())
7580 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007581 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007582 else
7583 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007584 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007585 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007586 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007587
7588 case OR_Ambiguous:
7589 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007590 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007591 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007592 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007593
7594 case OR_Deleted:
7595 Diag(OpLoc, diag::err_ovl_deleted_oper)
7596 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007597 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007598 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007599 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007600 }
7601
John McCalla0296f72010-03-19 07:35:19 +00007602 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007603 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007604
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007605 // Convert the object parameter.
7606 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007607 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7608 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007609 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007610
7611 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007612 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007613
7614 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007615 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7616 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007617 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007618
Douglas Gregor603d81b2010-07-13 08:18:22 +00007619 QualType ResultTy = Method->getCallResultType();
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007620 ExprOwningPtr<CXXOperatorCallExpr>
7621 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7622 &Base, 1, ResultTy, OpLoc));
7623
7624 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7625 Method))
7626 return ExprError();
7627 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007628}
7629
Douglas Gregorcd695e52008-11-10 20:40:00 +00007630/// FixOverloadedFunctionReference - E is an expression that refers to
7631/// a C++ overloaded function (possibly with some parentheses and
7632/// perhaps a '&' around it). We have resolved the overloaded function
7633/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007634/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007635Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007636 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007637 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007638 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7639 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007640 if (SubExpr == PE->getSubExpr())
7641 return PE->Retain();
7642
7643 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7644 }
7645
7646 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007647 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7648 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007649 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007650 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007651 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007652 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007653 if (SubExpr == ICE->getSubExpr())
7654 return ICE->Retain();
7655
John McCallcf142162010-08-07 06:22:56 +00007656 return ImplicitCastExpr::Create(Context, ICE->getType(),
7657 ICE->getCastKind(),
7658 SubExpr, 0,
7659 ICE->getCategory());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007660 }
7661
7662 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007663 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007664 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007665 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7666 if (Method->isStatic()) {
7667 // Do nothing: static member functions aren't any different
7668 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007669 } else {
John McCalle66edc12009-11-24 19:00:30 +00007670 // Fix the sub expression, which really has to be an
7671 // UnresolvedLookupExpr holding an overloaded member function
7672 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007673 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7674 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007675 if (SubExpr == UnOp->getSubExpr())
7676 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007677
John McCalld14a8642009-11-21 08:51:07 +00007678 assert(isa<DeclRefExpr>(SubExpr)
7679 && "fixed to something other than a decl ref");
7680 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7681 && "fixed to a member ref with no nested name qualifier");
7682
7683 // We have taken the address of a pointer to member
7684 // function. Perform the computation here so that we get the
7685 // appropriate pointer to member type.
7686 QualType ClassType
7687 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7688 QualType MemPtrType
7689 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7690
7691 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7692 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007693 }
7694 }
John McCall16df1e52010-03-30 21:47:33 +00007695 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7696 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007697 if (SubExpr == UnOp->getSubExpr())
7698 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007699
Douglas Gregor51c538b2009-11-20 19:42:02 +00007700 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7701 Context.getPointerType(SubExpr->getType()),
7702 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007703 }
John McCalld14a8642009-11-21 08:51:07 +00007704
7705 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007706 // FIXME: avoid copy.
7707 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007708 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007709 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7710 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007711 }
7712
John McCalld14a8642009-11-21 08:51:07 +00007713 return DeclRefExpr::Create(Context,
7714 ULE->getQualifier(),
7715 ULE->getQualifierRange(),
7716 Fn,
7717 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007718 Fn->getType(),
7719 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007720 }
7721
John McCall10eae182009-11-30 22:42:35 +00007722 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007723 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007724 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7725 if (MemExpr->hasExplicitTemplateArgs()) {
7726 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7727 TemplateArgs = &TemplateArgsBuffer;
7728 }
John McCall6b51f282009-11-23 01:53:49 +00007729
John McCall2d74de92009-12-01 22:10:20 +00007730 Expr *Base;
7731
7732 // If we're filling in
7733 if (MemExpr->isImplicitAccess()) {
7734 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7735 return DeclRefExpr::Create(Context,
7736 MemExpr->getQualifier(),
7737 MemExpr->getQualifierRange(),
7738 Fn,
7739 MemExpr->getMemberLoc(),
7740 Fn->getType(),
7741 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007742 } else {
7743 SourceLocation Loc = MemExpr->getMemberLoc();
7744 if (MemExpr->getQualifier())
7745 Loc = MemExpr->getQualifierRange().getBegin();
7746 Base = new (Context) CXXThisExpr(Loc,
7747 MemExpr->getBaseType(),
7748 /*isImplicit=*/true);
7749 }
John McCall2d74de92009-12-01 22:10:20 +00007750 } else
7751 Base = MemExpr->getBase()->Retain();
7752
7753 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007754 MemExpr->isArrow(),
7755 MemExpr->getQualifier(),
7756 MemExpr->getQualifierRange(),
7757 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007758 Found,
John McCall6b51f282009-11-23 01:53:49 +00007759 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007760 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007761 Fn->getType());
7762 }
7763
Douglas Gregor51c538b2009-11-20 19:42:02 +00007764 assert(false && "Invalid reference to overloaded function");
7765 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007766}
7767
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007768Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007769 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007770 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007771 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007772}
7773
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007774} // end namespace clang