blob: 602ecd66027db773839617f2d1e9702b9459623b [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
John McCall7decc9e2010-11-18 06:31:45 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
John Wiegley01296292011-04-08 18:41:53 +000042 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
43 E = S.DefaultFunctionArrayConversion(E.take());
44 if (E.isInvalid())
45 return ExprError();
46 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000047}
48
John McCall5c32be02010-08-24 20:38:10 +000049static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
50 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000051 StandardConversionSequence &SCS,
52 bool CStyle);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000053
54static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
55 QualType &ToType,
56 bool InOverloadResolution,
57 StandardConversionSequence &SCS,
58 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000059static OverloadingResult
60IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
61 UserDefinedConversionSequence& User,
62 OverloadCandidateSet& Conversions,
63 bool AllowExplicit);
64
65
66static ImplicitConversionSequence::CompareKind
67CompareStandardConversionSequences(Sema &S,
68 const StandardConversionSequence& SCS1,
69 const StandardConversionSequence& SCS2);
70
71static ImplicitConversionSequence::CompareKind
72CompareQualificationConversions(Sema &S,
73 const StandardConversionSequence& SCS1,
74 const StandardConversionSequence& SCS2);
75
76static ImplicitConversionSequence::CompareKind
77CompareDerivedToBaseConversions(Sema &S,
78 const StandardConversionSequence& SCS1,
79 const StandardConversionSequence& SCS2);
80
81
82
Douglas Gregor5251f1b2008-10-21 16:13:35 +000083/// GetConversionCategory - Retrieve the implicit conversion
84/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000085ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086GetConversionCategory(ImplicitConversionKind Kind) {
87 static const ImplicitConversionCategory
88 Category[(int)ICK_Num_Conversion_Kinds] = {
89 ICC_Identity,
90 ICC_Lvalue_Transformation,
91 ICC_Lvalue_Transformation,
92 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000093 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000094 ICC_Qualification_Adjustment,
95 ICC_Promotion,
96 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000097 ICC_Promotion,
98 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Conversion,
101 ICC_Conversion,
102 ICC_Conversion,
103 ICC_Conversion,
104 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000107 ICC_Conversion,
108 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 ICC_Conversion
110 };
111 return Category[(int)Kind];
112}
113
114/// GetConversionRank - Retrieve the implicit conversion rank
115/// corresponding to the given implicit conversion kind.
116ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
117 static const ImplicitConversionRank
118 Rank[(int)ICK_Num_Conversion_Kinds] = {
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000124 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125 ICR_Promotion,
126 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000127 ICR_Promotion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000135 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000136 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000137 ICR_Conversion,
138 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000139 ICR_Complex_Real_Conversion,
140 ICR_Conversion,
141 ICR_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142 };
143 return Rank[(int)Kind];
144}
145
146/// GetImplicitConversionName - Return the name of this kind of
147/// implicit conversion.
148const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000149 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 "No conversion",
151 "Lvalue-to-rvalue",
152 "Array-to-pointer",
153 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000154 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 "Qualification",
156 "Integral promotion",
157 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000158 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "Integral conversion",
160 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000161 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000162 "Floating-integral conversion",
163 "Pointer conversion",
164 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000165 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000166 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000167 "Derived-to-base conversion",
168 "Vector conversion",
169 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000170 "Complex-real conversion",
171 "Block Pointer conversion",
172 "Transparent Union Conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000184 ReferenceBinding = false;
185 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000186 IsLvalueReference = true;
187 BindsToFunctionLvalue = false;
188 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000189 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000190 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191}
192
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000193/// getRank - Retrieve the rank of this standard conversion sequence
194/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
195/// implicit conversions.
196ImplicitConversionRank StandardConversionSequence::getRank() const {
197 ImplicitConversionRank Rank = ICR_Exact_Match;
198 if (GetConversionRank(First) > Rank)
199 Rank = GetConversionRank(First);
200 if (GetConversionRank(Second) > Rank)
201 Rank = GetConversionRank(Second);
202 if (GetConversionRank(Third) > Rank)
203 Rank = GetConversionRank(Third);
204 return Rank;
205}
206
207/// isPointerConversionToBool - Determines whether this conversion is
208/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000209/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000210/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000211bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000212 // Note that FromType has not necessarily been transformed by the
213 // array-to-pointer or function-to-pointer implicit conversions, so
214 // check for their presence as well as checking whether FromType is
215 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000216 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000217 (getFromType()->isPointerType() ||
218 getFromType()->isObjCObjectPointerType() ||
219 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000220 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
222 return true;
223
224 return false;
225}
226
Douglas Gregor5c407d92008-10-23 00:40:37 +0000227/// isPointerConversionToVoidPointer - Determines whether this
228/// conversion is a conversion of a pointer to a void pointer. This is
229/// used as part of the ranking of standard conversion sequences (C++
230/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000231bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000232StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000233isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000234 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000235 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000236
237 // Note that FromType has not necessarily been transformed by the
238 // array-to-pointer implicit conversion, so check for its presence
239 // and redo the conversion to get a pointer.
240 if (First == ICK_Array_To_Pointer)
241 FromType = Context.getArrayDecayedType(FromType);
242
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000243 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000244 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000245 return ToPtrType->getPointeeType()->isVoidType();
246
247 return false;
248}
249
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000250/// DebugPrint - Print this standard conversion sequence to standard
251/// error. Useful for debugging overloading issues.
252void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000254 bool PrintedSomething = false;
255 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 PrintedSomething = true;
258 }
259
260 if (Second != ICK_Identity) {
261 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000262 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000265
266 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000268 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000269 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000270 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000271 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000272 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273 PrintedSomething = true;
274 }
275
276 if (Third != ICK_Identity) {
277 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000285 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000286 }
287}
288
289/// DebugPrint - Print this user-defined conversion sequence to standard
290/// error. Useful for debugging overloading issues.
291void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000292 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000293 if (Before.First || Before.Second || Before.Third) {
294 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000295 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000297 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000298 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000299 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000300 After.DebugPrint();
301 }
302}
303
304/// DebugPrint - Print this implicit conversion sequence to standard
305/// error. Useful for debugging overloading issues.
306void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 switch (ConversionKind) {
309 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000310 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 Standard.DebugPrint();
312 break;
313 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000314 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000315 UserDefined.DebugPrint();
316 break;
317 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000318 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000319 break;
John McCall0d1da222010-01-12 00:44:57 +0000320 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000321 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000322 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000323 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000324 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000325 break;
326 }
327
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000328 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329}
330
John McCall0d1da222010-01-12 00:44:57 +0000331void AmbiguousConversionSequence::construct() {
332 new (&conversions()) ConversionSet();
333}
334
335void AmbiguousConversionSequence::destruct() {
336 conversions().~ConversionSet();
337}
338
339void
340AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
341 FromTypePtr = O.FromTypePtr;
342 ToTypePtr = O.ToTypePtr;
343 new (&conversions()) ConversionSet(O.conversions());
344}
345
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346namespace {
347 // Structure used by OverloadCandidate::DeductionFailureInfo to store
348 // template parameter and template argument information.
349 struct DFIParamWithArguments {
350 TemplateParameter Param;
351 TemplateArgument FirstArg;
352 TemplateArgument SecondArg;
353 };
354}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000356/// \brief Convert from Sema's representation of template deduction information
357/// to the form used in overload-candidate information.
358OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000359static MakeDeductionFailureInfo(ASTContext &Context,
360 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000361 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 OverloadCandidate::DeductionFailureInfo Result;
363 Result.Result = static_cast<unsigned>(TDK);
364 Result.Data = 0;
365 switch (TDK) {
366 case Sema::TDK_Success:
367 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000368 case Sema::TDK_TooManyArguments:
369 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000372 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000373 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000374 Result.Data = Info.Param.getOpaqueValue();
375 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000376
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000377 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000378 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000379 // FIXME: Should allocate from normal heap so that we can free this later.
380 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 Saved->Param = Info.Param;
382 Saved->FirstArg = Info.FirstArg;
383 Saved->SecondArg = Info.SecondArg;
384 Result.Data = Saved;
385 break;
386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000389 Result.Data = Info.take();
390 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000391
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000396
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000397 return Result;
398}
John McCall0d1da222010-01-12 00:44:57 +0000399
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000400void OverloadCandidate::DeductionFailureInfo::Destroy() {
401 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
402 case Sema::TDK_Success:
403 case Sema::TDK_InstantiationDepth:
404 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000407 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000409
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000410 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000411 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000412 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000413 Data = 0;
414 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000415
416 case Sema::TDK_SubstitutionFailure:
417 // FIXME: Destroy the template arugment list?
418 Data = 0;
419 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420
Douglas Gregor461761d2010-05-08 18:20:53 +0000421 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000423 case Sema::TDK_FailedOverloadResolution:
424 break;
425 }
426}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427
428TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000435 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000438 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000439 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000441
442 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000443 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000444 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000446 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000447 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000448 case Sema::TDK_FailedOverloadResolution:
449 break;
450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 return TemplateParameter();
453}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454
Douglas Gregord09efd42010-05-08 20:07:26 +0000455TemplateArgumentList *
456OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
457 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
458 case Sema::TDK_Success:
459 case Sema::TDK_InstantiationDepth:
460 case Sema::TDK_TooManyArguments:
461 case Sema::TDK_TooFewArguments:
462 case Sema::TDK_Incomplete:
463 case Sema::TDK_InvalidExplicitArguments:
464 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000466 return 0;
467
468 case Sema::TDK_SubstitutionFailure:
469 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
Douglas Gregord09efd42010-05-08 20:07:26 +0000471 // Unhandled
472 case Sema::TDK_NonDeducedMismatch:
473 case Sema::TDK_FailedOverloadResolution:
474 break;
475 }
476
477 return 0;
478}
479
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000480const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
481 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
482 case Sema::TDK_Success:
483 case Sema::TDK_InstantiationDepth:
484 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000485 case Sema::TDK_TooManyArguments:
486 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000487 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000488 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 return 0;
490
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000491 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000492 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494
Douglas Gregor461761d2010-05-08 18:20:53 +0000495 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000496 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000497 case Sema::TDK_FailedOverloadResolution:
498 break;
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000501 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503
504const TemplateArgument *
505OverloadCandidate::DeductionFailureInfo::getSecondArg() {
506 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
507 case Sema::TDK_Success:
508 case Sema::TDK_InstantiationDepth:
509 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000510 case Sema::TDK_TooManyArguments:
511 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000512 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000513 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514 return 0;
515
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000516 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000517 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000518 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
519
Douglas Gregor461761d2010-05-08 18:20:53 +0000520 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000521 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000522 case Sema::TDK_FailedOverloadResolution:
523 break;
524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000526 return 0;
527}
528
529void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 inherited::clear();
531 Functions.clear();
532}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000535// overload of the declarations in Old. This routine returns false if
536// New and Old cannot be overloaded, e.g., if New has the same
537// signature as some function in Old (C++ 1.3.10) or if the Old
538// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000539// it does return false, MatchedDecl will point to the decl that New
540// cannot be overloaded with. This decl may be a UsingShadowDecl on
541// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542//
543// Example: Given the following input:
544//
545// void f(int, float); // #1
546// void f(int, int); // #2
547// int f(int, int); // #3
548//
549// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000550// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551//
John McCall3d988d92009-12-02 08:47:38 +0000552// When we process #2, Old contains only the FunctionDecl for #1. By
553// comparing the parameter types, we see that #1 and #2 are overloaded
554// (since they have different signatures), so this routine returns
555// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000556//
John McCall3d988d92009-12-02 08:47:38 +0000557// When we process #3, Old is an overload set containing #1 and #2. We
558// compare the signatures of #3 to #1 (they're overloaded, so we do
559// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
560// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000561// signature), IsOverload returns false and MatchedDecl will be set to
562// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000563//
564// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
565// into a class by a using declaration. The rules for whether to hide
566// shadow declarations ignore some properties which otherwise figure
567// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000568Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000569Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
570 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000571 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000572 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000573 NamedDecl *OldD = *I;
574
575 bool OldIsUsingDecl = false;
576 if (isa<UsingShadowDecl>(OldD)) {
577 OldIsUsingDecl = true;
578
579 // We can always introduce two using declarations into the same
580 // context, even if they have identical signatures.
581 if (NewIsUsingDecl) continue;
582
583 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
584 }
585
586 // If either declaration was introduced by a using declaration,
587 // we'll need to use slightly different rules for matching.
588 // Essentially, these rules are the normal rules, except that
589 // function templates hide function templates with different
590 // return types or template parameter lists.
591 bool UseMemberUsingDeclRules =
592 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
593
John McCall3d988d92009-12-02 08:47:38 +0000594 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000595 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
596 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
597 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
598 continue;
599 }
600
John McCalldaa3d6b2009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 }
John McCall3d988d92009-12-02 08:47:38 +0000604 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000605 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
606 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
607 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
608 continue;
609 }
610
John McCalldaa3d6b2009-12-09 03:35:25 +0000611 Match = *I;
612 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000613 }
John McCalla8987a2942010-11-10 03:01:53 +0000614 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000615 // We can overload with these, which can show up when doing
616 // redeclaration checks for UsingDecls.
617 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000618 } else if (isa<TagDecl>(OldD)) {
619 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000620 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
621 // Optimistically assume that an unresolved using decl will
622 // overload; if it doesn't, we'll have to diagnose during
623 // template instantiation.
624 } else {
John McCall1f82f242009-11-18 22:49:29 +0000625 // (C++ 13p1):
626 // Only function declarations can be overloaded; object and type
627 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000628 Match = *I;
629 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000630 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000631 }
John McCall1f82f242009-11-18 22:49:29 +0000632
John McCalldaa3d6b2009-12-09 03:35:25 +0000633 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000634}
635
John McCalle9cccd82010-06-16 08:42:20 +0000636bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
637 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000638 // If both of the functions are extern "C", then they are not
639 // overloads.
640 if (Old->isExternC() && New->isExternC())
641 return false;
642
John McCall1f82f242009-11-18 22:49:29 +0000643 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
644 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
645
646 // C++ [temp.fct]p2:
647 // A function template can be overloaded with other function templates
648 // and with normal (non-template) functions.
649 if ((OldTemplate == 0) != (NewTemplate == 0))
650 return true;
651
652 // Is the function New an overload of the function Old?
653 QualType OldQType = Context.getCanonicalType(Old->getType());
654 QualType NewQType = Context.getCanonicalType(New->getType());
655
656 // Compare the signatures (C++ 1.3.10) of the two functions to
657 // determine whether they are overloads. If we find any mismatch
658 // in the signature, they are overloads.
659
660 // If either of these functions is a K&R-style function (no
661 // prototype), then we consider them to have matching signatures.
662 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
663 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
664 return false;
665
John McCall424cec92011-01-19 06:33:43 +0000666 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
667 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000668
669 // The signature of a function includes the types of its
670 // parameters (C++ 1.3.10), which includes the presence or absence
671 // of the ellipsis; see C++ DR 357).
672 if (OldQType != NewQType &&
673 (OldType->getNumArgs() != NewType->getNumArgs() ||
674 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000675 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000676 return true;
677
678 // C++ [temp.over.link]p4:
679 // The signature of a function template consists of its function
680 // signature, its return type and its template parameter list. The names
681 // of the template parameters are significant only for establishing the
682 // relationship between the template parameters and the rest of the
683 // signature.
684 //
685 // We check the return type and template parameter lists for function
686 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000687 //
688 // However, we don't consider either of these when deciding whether
689 // a member introduced by a shadow declaration is hidden.
690 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000691 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
692 OldTemplate->getTemplateParameters(),
693 false, TPL_TemplateMatch) ||
694 OldType->getResultType() != NewType->getResultType()))
695 return true;
696
697 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000698 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000699 //
700 // As part of this, also check whether one of the member functions
701 // is static, in which case they are not overloads (C++
702 // 13.1p2). While not part of the definition of the signature,
703 // this check is important to determine whether these functions
704 // can be overloaded.
705 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
706 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
707 if (OldMethod && NewMethod &&
708 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000709 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000710 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
711 if (!UseUsingDeclRules &&
712 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
713 (OldMethod->getRefQualifier() == RQ_None ||
714 NewMethod->getRefQualifier() == RQ_None)) {
715 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716 // - Member function declarations with the same name and the same
717 // parameter-type-list as well as member function template
718 // declarations with the same name, the same parameter-type-list, and
719 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000720 // them, but not all, have a ref-qualifier (8.3.5).
721 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
722 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
723 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
John McCall1f82f242009-11-18 22:49:29 +0000726 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
John McCall1f82f242009-11-18 22:49:29 +0000729 // The signatures match; this is not an overload.
730 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000731}
732
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000733/// TryImplicitConversion - Attempt to perform an implicit conversion
734/// from the given expression (Expr) to the given type (ToType). This
735/// function returns an implicit conversion sequence that can be used
736/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737///
738/// void f(float f);
739/// void g(int i) { f(i); }
740///
741/// this routine would produce an implicit conversion sequence to
742/// describe the initialization of f from i, which will be a standard
743/// conversion sequence containing an lvalue-to-rvalue conversion (C++
744/// 4.1) followed by a floating-integral conversion (C++ 4.9).
745//
746/// Note that this routine only determines how the conversion can be
747/// performed; it does not actually perform the conversion. As such,
748/// it will not produce any diagnostics if no conversion is available,
749/// but will instead return an implicit conversion sequence of kind
750/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000751///
752/// If @p SuppressUserConversions, then user-defined conversions are
753/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000754/// If @p AllowExplicit, then explicit user-defined conversions are
755/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000756static ImplicitConversionSequence
757TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
758 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000760 bool InOverloadResolution,
761 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000762 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000763 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +0000764 ICS.Standard, CStyle)) {
John McCall0d1da222010-01-12 00:44:57 +0000765 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000766 return ICS;
767 }
768
John McCall5c32be02010-08-24 20:38:10 +0000769 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000770 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000771 return ICS;
772 }
773
Douglas Gregor836a7e82010-08-11 02:15:33 +0000774 // C++ [over.ics.user]p4:
775 // A conversion of an expression of class type to the same class
776 // type is given Exact Match rank, and a conversion of an
777 // expression of class type to a base class of that type is
778 // given Conversion rank, in spite of the fact that a copy/move
779 // constructor (i.e., a user-defined conversion function) is
780 // called for those cases.
781 QualType FromType = From->getType();
782 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000783 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
784 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000785 ICS.setStandard();
786 ICS.Standard.setAsIdentityConversion();
787 ICS.Standard.setFromType(FromType);
788 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789
Douglas Gregor5ab11652010-04-17 22:01:05 +0000790 // We don't actually check at this point whether there is a valid
791 // copy/move constructor, since overloading just assumes that it
792 // exists. When we actually perform initialization, we'll find the
793 // appropriate constructor to copy the returned object, if needed.
794 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor5ab11652010-04-17 22:01:05 +0000796 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000797 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000798 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799
Douglas Gregor836a7e82010-08-11 02:15:33 +0000800 return ICS;
801 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802
Douglas Gregor836a7e82010-08-11 02:15:33 +0000803 if (SuppressUserConversions) {
804 // We're not in the case above, so there is no conversion that
805 // we can perform.
806 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000807 return ICS;
808 }
809
810 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000811 OverloadCandidateSet Conversions(From->getExprLoc());
812 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000813 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000814 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000815
816 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000817 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000818 // C++ [over.ics.user]p4:
819 // A conversion of an expression of class type to the same class
820 // type is given Exact Match rank, and a conversion of an
821 // expression of class type to a base class of that type is
822 // given Conversion rank, in spite of the fact that a copy
823 // constructor (i.e., a user-defined conversion function) is
824 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000825 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000826 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000827 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000828 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
829 QualType ToCanon
830 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000831 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000832 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000833 // Turn this into a "standard" conversion sequence, so that it
834 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000835 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000836 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000837 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000838 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000839 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000840 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000841 ICS.Standard.Second = ICK_Derived_To_Base;
842 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000843 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000844
845 // C++ [over.best.ics]p4:
846 // However, when considering the argument of a user-defined
847 // conversion function that is a candidate by 13.3.1.3 when
848 // invoked for the copying of the temporary in the second step
849 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
850 // 13.3.1.6 in all cases, only standard conversion sequences and
851 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000852 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000853 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000854 }
John McCalle8c8cd22010-01-13 22:30:33 +0000855 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000856 ICS.setAmbiguous();
857 ICS.Ambiguous.setFromType(From->getType());
858 ICS.Ambiguous.setToType(ToType);
859 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
860 Cand != Conversions.end(); ++Cand)
861 if (Cand->Viable)
862 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000863 } else {
John McCall65eb8792010-02-25 01:37:24 +0000864 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000865 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000866
867 return ICS;
868}
869
John McCall5c32be02010-08-24 20:38:10 +0000870bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
871 const InitializedEntity &Entity,
872 Expr *Initializer,
873 bool SuppressUserConversions,
874 bool AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000875 bool InOverloadResolution,
876 bool CStyle) {
John McCall5c32be02010-08-24 20:38:10 +0000877 ImplicitConversionSequence ICS
878 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
879 SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000880 AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000881 InOverloadResolution,
882 CStyle);
John McCall5c32be02010-08-24 20:38:10 +0000883 if (ICS.isBad()) return true;
884
885 // Perform the actual conversion.
886 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
887 return false;
888}
889
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000890/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000891/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000892/// converted expression. Flavor is the kind of conversion we're
893/// performing, used in the error message. If @p AllowExplicit,
894/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000895ExprResult
896Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000897 AssignmentAction Action, bool AllowExplicit) {
898 ImplicitConversionSequence ICS;
899 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
900}
901
John Wiegley01296292011-04-08 18:41:53 +0000902ExprResult
903Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000904 AssignmentAction Action, bool AllowExplicit,
905 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000906 ICS = clang::TryImplicitConversion(*this, From, ToType,
907 /*SuppressUserConversions=*/false,
908 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000909 /*InOverloadResolution=*/false,
910 /*CStyle=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000911 return PerformImplicitConversion(From, ToType, ICS, Action);
912}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
914/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000915/// conversion that strips "noreturn" off the nested function type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000917 QualType ToType, QualType &ResultTy) {
918 if (Context.hasSameUnqualifiedType(FromType, ToType))
919 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920
John McCall991eb4b2010-12-21 00:44:39 +0000921 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
922 // where F adds one of the following at most once:
923 // - a pointer
924 // - a member pointer
925 // - a block pointer
926 CanQualType CanTo = Context.getCanonicalType(ToType);
927 CanQualType CanFrom = Context.getCanonicalType(FromType);
928 Type::TypeClass TyClass = CanTo->getTypeClass();
929 if (TyClass != CanFrom->getTypeClass()) return false;
930 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
931 if (TyClass == Type::Pointer) {
932 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
933 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
934 } else if (TyClass == Type::BlockPointer) {
935 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
936 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
937 } else if (TyClass == Type::MemberPointer) {
938 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
939 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
940 } else {
941 return false;
942 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000943
John McCall991eb4b2010-12-21 00:44:39 +0000944 TyClass = CanTo->getTypeClass();
945 if (TyClass != CanFrom->getTypeClass()) return false;
946 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
947 return false;
948 }
949
950 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
951 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
952 if (!EInfo.getNoReturn()) return false;
953
954 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
955 assert(QualType(FromFn, 0).isCanonical());
956 if (QualType(FromFn, 0) != CanTo) return false;
957
958 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000959 return true;
960}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
Douglas Gregor46188682010-05-18 22:42:18 +0000962/// \brief Determine whether the conversion from FromType to ToType is a valid
963/// vector conversion.
964///
965/// \param ICK Will be set to the vector conversion kind, if this is a vector
966/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967static bool IsVectorConversion(ASTContext &Context, QualType FromType,
968 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000969 // We need at least one of these types to be a vector type to have a vector
970 // conversion.
971 if (!ToType->isVectorType() && !FromType->isVectorType())
972 return false;
973
974 // Identical types require no conversions.
975 if (Context.hasSameUnqualifiedType(FromType, ToType))
976 return false;
977
978 // There are no conversions between extended vector types, only identity.
979 if (ToType->isExtVectorType()) {
980 // There are no conversions between extended vector types other than the
981 // identity conversion.
982 if (FromType->isExtVectorType())
983 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000984
Douglas Gregor46188682010-05-18 22:42:18 +0000985 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000986 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000987 ICK = ICK_Vector_Splat;
988 return true;
989 }
990 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000991
992 // We can perform the conversion between vector types in the following cases:
993 // 1)vector types are equivalent AltiVec and GCC vector types
994 // 2)lax vector conversions are permitted and the vector types are of the
995 // same size
996 if (ToType->isVectorType() && FromType->isVectorType()) {
997 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000998 (Context.getLangOptions().LaxVectorConversions &&
999 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001000 ICK = ICK_Vector_Conversion;
1001 return true;
1002 }
Douglas Gregor46188682010-05-18 22:42:18 +00001003 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001004
Douglas Gregor46188682010-05-18 22:42:18 +00001005 return false;
1006}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001008/// IsStandardConversion - Determines whether there is a standard
1009/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1010/// expression From to the type ToType. Standard conversion sequences
1011/// only consider non-class types; for conversions that involve class
1012/// types, use TryImplicitConversion. If a conversion exists, SCS will
1013/// contain the standard conversion sequence required to perform this
1014/// conversion and this routine will return true. Otherwise, this
1015/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001016static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1017 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001018 StandardConversionSequence &SCS,
1019 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001020 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001022 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001023 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001024 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001025 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001026 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001027 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001029 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001030 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001031 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001032 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001033 return false;
1034
Mike Stump11289f42009-09-09 15:08:12 +00001035 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001036 }
1037
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038 // The first conversion can be an lvalue-to-rvalue conversion,
1039 // array-to-pointer conversion, or function-to-pointer conversion
1040 // (C++ 4p1).
1041
John McCall5c32be02010-08-24 20:38:10 +00001042 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001043 DeclAccessPair AccessPair;
1044 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001046 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001047 // We were able to resolve the address of the overloaded function,
1048 // so we can convert to the type of that function.
1049 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001050
1051 // we can sometimes resolve &foo<int> regardless of ToType, so check
1052 // if the type matches (identity) or we are converting to bool
1053 if (!S.Context.hasSameUnqualifiedType(
1054 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1055 QualType resultTy;
1056 // if the function type matches except for [[noreturn]], it's ok
1057 if (!IsNoReturnConversion(S.Context, FromType,
1058 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1059 // otherwise, only a boolean conversion is standard
1060 if (!ToType->isBooleanType())
1061 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001063
Chandler Carruthffce2452011-03-29 08:08:18 +00001064 // Check if the "from" expression is taking the address of an overloaded
1065 // function and recompute the FromType accordingly. Take advantage of the
1066 // fact that non-static member functions *must* have such an address-of
1067 // expression.
1068 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1069 if (Method && !Method->isStatic()) {
1070 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1071 "Non-unary operator on non-static member address");
1072 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1073 == UO_AddrOf &&
1074 "Non-address-of operator on non-static member address");
1075 const Type *ClassType
1076 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1077 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001078 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1079 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1080 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001081 "Non-address-of operator for overloaded function expression");
1082 FromType = S.Context.getPointerType(FromType);
1083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
Douglas Gregor980fb162010-04-29 18:24:40 +00001085 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001086 assert(S.Context.hasSameType(
1087 FromType,
1088 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001089 } else {
1090 return false;
1091 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001092 }
Mike Stump11289f42009-09-09 15:08:12 +00001093 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001094 // An lvalue (3.10) of a non-function, non-array type T can be
1095 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001096 bool argIsLValue = From->isLValue();
1097 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001098 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001099 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001100 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001101
1102 // If T is a non-class type, the type of the rvalue is the
1103 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001104 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1105 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001106 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001107 } else if (FromType->isArrayType()) {
1108 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001109 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110
1111 // An lvalue or rvalue of type "array of N T" or "array of unknown
1112 // bound of T" can be converted to an rvalue of type "pointer to
1113 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001114 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115
John McCall5c32be02010-08-24 20:38:10 +00001116 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001117 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001118 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119
1120 // For the purpose of ranking in overload resolution
1121 // (13.3.3.1.1), this conversion is considered an
1122 // array-to-pointer conversion followed by a qualification
1123 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001124 SCS.Second = ICK_Identity;
1125 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001126 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001127 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128 }
John McCall086a4642010-11-24 05:12:34 +00001129 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001130 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001131 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132
1133 // An lvalue of function type T can be converted to an rvalue of
1134 // type "pointer to T." The result is a pointer to the
1135 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001136 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001137 } else {
1138 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001139 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001141 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142
1143 // The second conversion can be an integral promotion, floating
1144 // point promotion, integral conversion, floating point conversion,
1145 // floating-integral conversion, pointer conversion,
1146 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001147 // For overloading in C, this can also be a "compatible-type"
1148 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001149 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001150 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001151 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 // The unqualified versions of the types are the same: there's no
1153 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001154 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001155 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001156 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001157 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001159 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001160 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001161 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001163 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001164 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001165 SCS.Second = ICK_Complex_Promotion;
1166 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001167 } else if (ToType->isBooleanType() &&
1168 (FromType->isArithmeticType() ||
1169 FromType->isAnyPointerType() ||
1170 FromType->isBlockPointerType() ||
1171 FromType->isMemberPointerType() ||
1172 FromType->isNullPtrType())) {
1173 // Boolean conversions (C++ 4.12).
1174 SCS.Second = ICK_Boolean_Conversion;
1175 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001176 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001177 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001178 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001179 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001181 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001182 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001183 SCS.Second = ICK_Complex_Conversion;
1184 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001185 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1186 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001187 // Complex-real conversions (C99 6.3.1.7)
1188 SCS.Second = ICK_Complex_Real;
1189 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001190 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001191 // Floating point conversions (C++ 4.8).
1192 SCS.Second = ICK_Floating_Conversion;
1193 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001195 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001196 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001197 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001198 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001199 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001201 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1202 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001203 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1204 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001205 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001206 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001207 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001208 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001210 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001211 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001212 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001213 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001214 SCS.Second = SecondICK;
1215 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001216 } else if (!S.getLangOptions().CPlusPlus &&
1217 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001218 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001219 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001220 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001221 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001222 // Treat a conversion that strips "noreturn" as an identity conversion.
1223 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001224 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1225 InOverloadResolution,
1226 SCS, CStyle)) {
1227 SCS.Second = ICK_TransparentUnionConversion;
1228 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229 } else {
1230 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001231 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001232 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001233 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001234
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001235 QualType CanonFrom;
1236 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001237 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001238 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001239 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001241 CanonFrom = S.Context.getCanonicalType(FromType);
1242 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001243 } else {
1244 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001245 SCS.Third = ICK_Identity;
1246
Mike Stump11289f42009-09-09 15:08:12 +00001247 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001248 // [...] Any difference in top-level cv-qualification is
1249 // subsumed by the initialization itself and does not constitute
1250 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001251 CanonFrom = S.Context.getCanonicalType(FromType);
1252 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001254 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001255 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1256 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001257 FromType = ToType;
1258 CanonFrom = CanonTo;
1259 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001260 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001261 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001262
1263 // If we have not converted the argument type to the parameter type,
1264 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001265 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001266 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001267
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001268 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001269}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001270
1271static bool
1272IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1273 QualType &ToType,
1274 bool InOverloadResolution,
1275 StandardConversionSequence &SCS,
1276 bool CStyle) {
1277
1278 const RecordType *UT = ToType->getAsUnionType();
1279 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1280 return false;
1281 // The field to initialize within the transparent union.
1282 RecordDecl *UD = UT->getDecl();
1283 // It's compatible if the expression matches any of the fields.
1284 for (RecordDecl::field_iterator it = UD->field_begin(),
1285 itend = UD->field_end();
1286 it != itend; ++it) {
1287 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, CStyle)) {
1288 ToType = it->getType();
1289 return true;
1290 }
1291 }
1292 return false;
1293}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001294
1295/// IsIntegralPromotion - Determines whether the conversion from the
1296/// expression From (whose potentially-adjusted type is FromType) to
1297/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1298/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001299bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001300 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001301 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001302 if (!To) {
1303 return false;
1304 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001305
1306 // An rvalue of type char, signed char, unsigned char, short int, or
1307 // unsigned short int can be converted to an rvalue of type int if
1308 // int can represent all the values of the source type; otherwise,
1309 // the source rvalue can be converted to an rvalue of type unsigned
1310 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001311 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1312 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001313 if (// We can promote any signed, promotable integer type to an int
1314 (FromType->isSignedIntegerType() ||
1315 // We can promote any unsigned integer type whose size is
1316 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001317 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001318 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001319 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001320 }
1321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001322 return To->getKind() == BuiltinType::UInt;
1323 }
1324
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325 // C++0x [conv.prom]p3:
1326 // A prvalue of an unscoped enumeration type whose underlying type is not
1327 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1328 // following types that can represent all the values of the enumeration
1329 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1330 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001331 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001333 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334 // with lowest integer conversion rank (4.13) greater than the rank of long
1335 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001336 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001337 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1338 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1339 // provided for a scoped enumeration.
1340 if (FromEnumType->getDecl()->isScoped())
1341 return false;
1342
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001343 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001345 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001346 return Context.hasSameUnqualifiedType(ToType,
1347 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001348 }
John McCall56774992009-12-09 09:09:27 +00001349
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001350 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1352 // to an rvalue a prvalue of the first of the following types that can
1353 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001354 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001356 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001358 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001360 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001361 // Determine whether the type we're converting from is signed or
1362 // unsigned.
1363 bool FromIsSigned;
1364 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001365
John McCall56774992009-12-09 09:09:27 +00001366 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1367 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001368
1369 // The types we'll try to promote to, in the appropriate
1370 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001371 QualType PromoteTypes[6] = {
1372 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001373 Context.LongTy, Context.UnsignedLongTy ,
1374 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001375 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001376 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001377 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1378 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001379 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001380 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1381 // We found the type that we can promote to. If this is the
1382 // type we wanted, we have a promotion. Otherwise, no
1383 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001384 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001385 }
1386 }
1387 }
1388
1389 // An rvalue for an integral bit-field (9.6) can be converted to an
1390 // rvalue of type int if int can represent all the values of the
1391 // bit-field; otherwise, it can be converted to unsigned int if
1392 // unsigned int can represent all the values of the bit-field. If
1393 // the bit-field is larger yet, no integral promotion applies to
1394 // it. If the bit-field has an enumerated type, it is treated as any
1395 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001396 // FIXME: We should delay checking of bit-fields until we actually perform the
1397 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001398 using llvm::APSInt;
1399 if (From)
1400 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001401 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001402 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001403 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1404 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1405 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001406
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001407 // Are we promoting to an int from a bitfield that fits in an int?
1408 if (BitWidth < ToSize ||
1409 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1410 return To->getKind() == BuiltinType::Int;
1411 }
Mike Stump11289f42009-09-09 15:08:12 +00001412
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001413 // Are we promoting to an unsigned int from an unsigned bitfield
1414 // that fits into an unsigned int?
1415 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1416 return To->getKind() == BuiltinType::UInt;
1417 }
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001419 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001420 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421 }
Mike Stump11289f42009-09-09 15:08:12 +00001422
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001423 // An rvalue of type bool can be converted to an rvalue of type int,
1424 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001425 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001426 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001427 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001428
1429 return false;
1430}
1431
1432/// IsFloatingPointPromotion - Determines whether the conversion from
1433/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1434/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001435bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001436 /// An rvalue of type float can be converted to an rvalue of type
1437 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001438 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1439 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001440 if (FromBuiltin->getKind() == BuiltinType::Float &&
1441 ToBuiltin->getKind() == BuiltinType::Double)
1442 return true;
1443
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001444 // C99 6.3.1.5p1:
1445 // When a float is promoted to double or long double, or a
1446 // double is promoted to long double [...].
1447 if (!getLangOptions().CPlusPlus &&
1448 (FromBuiltin->getKind() == BuiltinType::Float ||
1449 FromBuiltin->getKind() == BuiltinType::Double) &&
1450 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1451 return true;
1452 }
1453
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001454 return false;
1455}
1456
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001457/// \brief Determine if a conversion is a complex promotion.
1458///
1459/// A complex promotion is defined as a complex -> complex conversion
1460/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001461/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001462bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001463 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001464 if (!FromComplex)
1465 return false;
1466
John McCall9dd450b2009-09-21 23:43:11 +00001467 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001468 if (!ToComplex)
1469 return false;
1470
1471 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001472 ToComplex->getElementType()) ||
1473 IsIntegralPromotion(0, FromComplex->getElementType(),
1474 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001475}
1476
Douglas Gregor237f96c2008-11-26 23:31:11 +00001477/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1478/// the pointer type FromPtr to a pointer to type ToPointee, with the
1479/// same type qualifiers as FromPtr has on its pointee type. ToType,
1480/// if non-empty, will be a pointer to ToType that may or may not have
1481/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001482static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001483BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001484 QualType ToPointee, QualType ToType,
1485 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001486 assert((FromPtr->getTypeClass() == Type::Pointer ||
1487 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1488 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001490 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1491 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1492 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001493
1494 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001495 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001496 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001497 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001498
1499 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001500 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001501 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001502 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001503 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001504
1505 // Build a pointer to ToPointee. It has the right qualifiers
1506 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001507 if (isa<ObjCObjectPointerType>(ToType))
1508 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001509 return Context.getPointerType(ToPointee);
1510 }
1511
1512 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001513 QualType QualifiedCanonToPointee
1514 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001515
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001516 if (isa<ObjCObjectPointerType>(ToType))
1517 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1518 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001519}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520
Mike Stump11289f42009-09-09 15:08:12 +00001521static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001522 bool InOverloadResolution,
1523 ASTContext &Context) {
1524 // Handle value-dependent integral null pointer constants correctly.
1525 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1526 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001527 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001528 return !InOverloadResolution;
1529
Douglas Gregor56751b52009-09-25 04:25:58 +00001530 return Expr->isNullPointerConstant(Context,
1531 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1532 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001533}
Mike Stump11289f42009-09-09 15:08:12 +00001534
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001535/// IsPointerConversion - Determines whether the conversion of the
1536/// expression From, which has the (possibly adjusted) type FromType,
1537/// can be converted to the type ToType via a pointer conversion (C++
1538/// 4.10). If so, returns true and places the converted type (that
1539/// might differ from ToType in its cv-qualifiers at some level) into
1540/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001541///
Douglas Gregora29dc052008-11-27 01:19:21 +00001542/// This routine also supports conversions to and from block pointers
1543/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1544/// pointers to interfaces. FIXME: Once we've determined the
1545/// appropriate overloading rules for Objective-C, we may want to
1546/// split the Objective-C checks into a different routine; however,
1547/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001548/// conversions, so for now they live here. IncompatibleObjC will be
1549/// set if the conversion is an allowed Objective-C conversion that
1550/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001552 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001553 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001554 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001555 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001556 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1557 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001558 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001559
Mike Stump11289f42009-09-09 15:08:12 +00001560 // Conversion from a null pointer constant to any Objective-C pointer type.
1561 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001562 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001563 ConvertedType = ToType;
1564 return true;
1565 }
1566
Douglas Gregor231d1c62008-11-27 00:15:41 +00001567 // Blocks: Block pointers can be converted to void*.
1568 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001569 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001570 ConvertedType = ToType;
1571 return true;
1572 }
1573 // Blocks: A null pointer constant can be converted to a block
1574 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001575 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001576 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001577 ConvertedType = ToType;
1578 return true;
1579 }
1580
Sebastian Redl576fd422009-05-10 18:38:11 +00001581 // If the left-hand-side is nullptr_t, the right side can be a null
1582 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001583 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001584 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001585 ConvertedType = ToType;
1586 return true;
1587 }
1588
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001589 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 if (!ToTypePtr)
1591 return false;
1592
1593 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001594 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595 ConvertedType = ToType;
1596 return true;
1597 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001598
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001600 // , including objective-c pointers.
1601 QualType ToPointeeType = ToTypePtr->getPointeeType();
1602 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001603 ConvertedType = BuildSimilarlyQualifiedPointerType(
1604 FromType->getAs<ObjCObjectPointerType>(),
1605 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001606 ToType, Context);
1607 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001608 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001609 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001610 if (!FromTypePtr)
1611 return false;
1612
1613 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001614
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001616 // pointer conversion, so don't do all of the work below.
1617 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1618 return false;
1619
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001620 // An rvalue of type "pointer to cv T," where T is an object type,
1621 // can be converted to an rvalue of type "pointer to cv void" (C++
1622 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001623 if (FromPointeeType->isIncompleteOrObjectType() &&
1624 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001625 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001626 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001627 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 return true;
1629 }
1630
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001631 // When we're overloading in C, we allow a special kind of pointer
1632 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001633 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001634 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001635 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001636 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001637 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001638 return true;
1639 }
1640
Douglas Gregor5c407d92008-10-23 00:40:37 +00001641 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001642 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001643 // An rvalue of type "pointer to cv D," where D is a class type,
1644 // can be converted to an rvalue of type "pointer to cv B," where
1645 // B is a base class (clause 10) of D. If B is an inaccessible
1646 // (clause 11) or ambiguous (10.2) base class of D, a program that
1647 // necessitates this conversion is ill-formed. The result of the
1648 // conversion is a pointer to the base class sub-object of the
1649 // derived class object. The null pointer value is converted to
1650 // the null pointer value of the destination type.
1651 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001652 // Note that we do not check for ambiguity or inaccessibility
1653 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001654 if (getLangOptions().CPlusPlus &&
1655 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001656 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001657 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001658 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001659 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001660 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001661 ToType, Context);
1662 return true;
1663 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001664
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001665 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1666 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1667 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1668 ToPointeeType,
1669 ToType, Context);
1670 return true;
1671 }
1672
Douglas Gregora119f102008-12-19 19:13:09 +00001673 return false;
1674}
Douglas Gregoraec25842011-04-26 23:16:46 +00001675
1676/// \brief Adopt the given qualifiers for the given type.
1677static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1678 Qualifiers TQs = T.getQualifiers();
1679
1680 // Check whether qualifiers already match.
1681 if (TQs == Qs)
1682 return T;
1683
1684 if (Qs.compatiblyIncludes(TQs))
1685 return Context.getQualifiedType(T, Qs);
1686
1687 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1688}
Douglas Gregora119f102008-12-19 19:13:09 +00001689
1690/// isObjCPointerConversion - Determines whether this is an
1691/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1692/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001693bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001694 QualType& ConvertedType,
1695 bool &IncompatibleObjC) {
1696 if (!getLangOptions().ObjC1)
1697 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001698
Douglas Gregoraec25842011-04-26 23:16:46 +00001699 // The set of qualifiers on the type we're converting from.
1700 Qualifiers FromQualifiers = FromType.getQualifiers();
1701
Steve Naroff7cae42b2009-07-10 23:34:53 +00001702 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001703 const ObjCObjectPointerType* ToObjCPtr =
1704 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001705 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001706 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001707
Steve Naroff7cae42b2009-07-10 23:34:53 +00001708 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001709 // If the pointee types are the same (ignoring qualifications),
1710 // then this is not a pointer conversion.
1711 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1712 FromObjCPtr->getPointeeType()))
1713 return false;
1714
Douglas Gregoraec25842011-04-26 23:16:46 +00001715 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001716 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001717 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001718 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001719 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001720 return true;
1721 }
1722 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001723 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001724 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001725 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001726 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001727 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001728 return true;
1729 }
1730 // Objective C++: We're able to convert from a pointer to an
1731 // interface to a pointer to a different interface.
1732 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001733 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1734 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1735 if (getLangOptions().CPlusPlus && LHS && RHS &&
1736 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1737 FromObjCPtr->getPointeeType()))
1738 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001740 ToObjCPtr->getPointeeType(),
1741 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001742 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001743 return true;
1744 }
1745
1746 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1747 // Okay: this is some kind of implicit downcast of Objective-C
1748 // interfaces, which is permitted. However, we're going to
1749 // complain about it.
1750 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001752 ToObjCPtr->getPointeeType(),
1753 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001754 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001755 return true;
1756 }
Mike Stump11289f42009-09-09 15:08:12 +00001757 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001758 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001759 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001760 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001761 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001762 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001763 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001764 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001765 // to a block pointer type.
1766 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001767 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001768 return true;
1769 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001770 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001773 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001775 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001776 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001777 return true;
1778 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001779 else
Douglas Gregora119f102008-12-19 19:13:09 +00001780 return false;
1781
Douglas Gregor033f56d2008-12-23 00:53:59 +00001782 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001783 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001784 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001785 else if (const BlockPointerType *FromBlockPtr =
1786 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001787 FromPointeeType = FromBlockPtr->getPointeeType();
1788 else
Douglas Gregora119f102008-12-19 19:13:09 +00001789 return false;
1790
Douglas Gregora119f102008-12-19 19:13:09 +00001791 // If we have pointers to pointers, recursively check whether this
1792 // is an Objective-C conversion.
1793 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1794 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1795 IncompatibleObjC)) {
1796 // We always complain about this conversion.
1797 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001798 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001799 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001800 return true;
1801 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001802 // Allow conversion of pointee being objective-c pointer to another one;
1803 // as in I* to id.
1804 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1805 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1806 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1807 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001808 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001809 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001810 return true;
1811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001812
Douglas Gregor033f56d2008-12-23 00:53:59 +00001813 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001814 // differences in the argument and result types are in Objective-C
1815 // pointer conversions. If so, we permit the conversion (but
1816 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001817 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001818 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001819 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001820 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001821 if (FromFunctionType && ToFunctionType) {
1822 // If the function types are exactly the same, this isn't an
1823 // Objective-C pointer conversion.
1824 if (Context.getCanonicalType(FromPointeeType)
1825 == Context.getCanonicalType(ToPointeeType))
1826 return false;
1827
1828 // Perform the quick checks that will tell us whether these
1829 // function types are obviously different.
1830 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1831 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1832 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1833 return false;
1834
1835 bool HasObjCConversion = false;
1836 if (Context.getCanonicalType(FromFunctionType->getResultType())
1837 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1838 // Okay, the types match exactly. Nothing to do.
1839 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1840 ToFunctionType->getResultType(),
1841 ConvertedType, IncompatibleObjC)) {
1842 // Okay, we have an Objective-C pointer conversion.
1843 HasObjCConversion = true;
1844 } else {
1845 // Function types are too different. Abort.
1846 return false;
1847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848
Douglas Gregora119f102008-12-19 19:13:09 +00001849 // Check argument types.
1850 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1851 ArgIdx != NumArgs; ++ArgIdx) {
1852 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1853 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1854 if (Context.getCanonicalType(FromArgType)
1855 == Context.getCanonicalType(ToArgType)) {
1856 // Okay, the types match exactly. Nothing to do.
1857 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1858 ConvertedType, IncompatibleObjC)) {
1859 // Okay, we have an Objective-C pointer conversion.
1860 HasObjCConversion = true;
1861 } else {
1862 // Argument types are too different. Abort.
1863 return false;
1864 }
1865 }
1866
1867 if (HasObjCConversion) {
1868 // We had an Objective-C conversion. Allow this pointer
1869 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001870 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001871 IncompatibleObjC = true;
1872 return true;
1873 }
1874 }
1875
Sebastian Redl72b597d2009-01-25 19:43:20 +00001876 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001877}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001878
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001879bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1880 QualType& ConvertedType) {
1881 QualType ToPointeeType;
1882 if (const BlockPointerType *ToBlockPtr =
1883 ToType->getAs<BlockPointerType>())
1884 ToPointeeType = ToBlockPtr->getPointeeType();
1885 else
1886 return false;
1887
1888 QualType FromPointeeType;
1889 if (const BlockPointerType *FromBlockPtr =
1890 FromType->getAs<BlockPointerType>())
1891 FromPointeeType = FromBlockPtr->getPointeeType();
1892 else
1893 return false;
1894 // We have pointer to blocks, check whether the only
1895 // differences in the argument and result types are in Objective-C
1896 // pointer conversions. If so, we permit the conversion.
1897
1898 const FunctionProtoType *FromFunctionType
1899 = FromPointeeType->getAs<FunctionProtoType>();
1900 const FunctionProtoType *ToFunctionType
1901 = ToPointeeType->getAs<FunctionProtoType>();
1902
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001903 if (!FromFunctionType || !ToFunctionType)
1904 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001905
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001906 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001907 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001908
1909 // Perform the quick checks that will tell us whether these
1910 // function types are obviously different.
1911 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1912 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1913 return false;
1914
1915 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1916 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1917 if (FromEInfo != ToEInfo)
1918 return false;
1919
1920 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00001921 if (Context.hasSameType(FromFunctionType->getResultType(),
1922 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001923 // Okay, the types match exactly. Nothing to do.
1924 } else {
1925 QualType RHS = FromFunctionType->getResultType();
1926 QualType LHS = ToFunctionType->getResultType();
1927 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1928 !RHS.hasQualifiers() && LHS.hasQualifiers())
1929 LHS = LHS.getUnqualifiedType();
1930
1931 if (Context.hasSameType(RHS,LHS)) {
1932 // OK exact match.
1933 } else if (isObjCPointerConversion(RHS, LHS,
1934 ConvertedType, IncompatibleObjC)) {
1935 if (IncompatibleObjC)
1936 return false;
1937 // Okay, we have an Objective-C pointer conversion.
1938 }
1939 else
1940 return false;
1941 }
1942
1943 // Check argument types.
1944 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1945 ArgIdx != NumArgs; ++ArgIdx) {
1946 IncompatibleObjC = false;
1947 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1948 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1949 if (Context.hasSameType(FromArgType, ToArgType)) {
1950 // Okay, the types match exactly. Nothing to do.
1951 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1952 ConvertedType, IncompatibleObjC)) {
1953 if (IncompatibleObjC)
1954 return false;
1955 // Okay, we have an Objective-C pointer conversion.
1956 } else
1957 // Argument types are too different. Abort.
1958 return false;
1959 }
1960 ConvertedType = ToType;
1961 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001962}
1963
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001964/// FunctionArgTypesAreEqual - This routine checks two function proto types
1965/// for equlity of their argument types. Caller has already checked that
1966/// they have same number of arguments. This routine assumes that Objective-C
1967/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00001969 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001970 if (!getLangOptions().ObjC1)
1971 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1972 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001974 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1975 N = NewType->arg_type_begin(),
1976 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1977 QualType ToType = (*O);
1978 QualType FromType = (*N);
1979 if (ToType != FromType) {
1980 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1981 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001982 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1983 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1984 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1985 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001986 continue;
1987 }
John McCall8b07ec22010-05-15 11:32:37 +00001988 else if (const ObjCObjectPointerType *PTTo =
1989 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00001991 FromType->getAs<ObjCObjectPointerType>())
1992 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1993 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001996 }
1997 }
1998 return true;
1999}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002000
Douglas Gregor39c16d42008-10-24 04:54:22 +00002001/// CheckPointerConversion - Check the pointer conversion from the
2002/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002003/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002004/// conversions for which IsPointerConversion has already returned
2005/// true. It returns true and produces a diagnostic if there was an
2006/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002007bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002008 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002009 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002010 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002011 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002012 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002013
John McCall8cb679e2010-11-15 09:13:47 +00002014 Kind = CK_BitCast;
2015
Chandler Carruthffab8732011-04-09 07:32:05 +00002016 if (!IsCStyleOrFunctionalCast &&
2017 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2018 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2019 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002020 PDiag(diag::warn_impcast_bool_to_null_pointer)
2021 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002022
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002023 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2024 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002025 QualType FromPointeeType = FromPtrType->getPointeeType(),
2026 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002027
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002028 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2029 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002030 // We must have a derived-to-base conversion. Check an
2031 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002032 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2033 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002034 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002035 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002036 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002038 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002039 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002040 }
2041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00002043 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002044 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00002045 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002046 // Objective-C++ conversions are always okay.
2047 // FIXME: We should have a different class of conversions for the
2048 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002049 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002050 return false;
John McCall8cb679e2010-11-15 09:13:47 +00002051 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002052 }
John McCall8cb679e2010-11-15 09:13:47 +00002053
2054 // We shouldn't fall into this case unless it's valid for other
2055 // reasons.
2056 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2057 Kind = CK_NullToPointer;
2058
Douglas Gregor39c16d42008-10-24 04:54:22 +00002059 return false;
2060}
2061
Sebastian Redl72b597d2009-01-25 19:43:20 +00002062/// IsMemberPointerConversion - Determines whether the conversion of the
2063/// expression From, which has the (possibly adjusted) type FromType, can be
2064/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2065/// If so, returns true and places the converted type (that might differ from
2066/// ToType in its cv-qualifiers at some level) into ConvertedType.
2067bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002069 bool InOverloadResolution,
2070 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002071 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002072 if (!ToTypePtr)
2073 return false;
2074
2075 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002076 if (From->isNullPointerConstant(Context,
2077 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2078 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002079 ConvertedType = ToType;
2080 return true;
2081 }
2082
2083 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002084 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002085 if (!FromTypePtr)
2086 return false;
2087
2088 // A pointer to member of B can be converted to a pointer to member of D,
2089 // where D is derived from B (C++ 4.11p2).
2090 QualType FromClass(FromTypePtr->getClass(), 0);
2091 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002092
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002093 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2094 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2095 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002096 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2097 ToClass.getTypePtr());
2098 return true;
2099 }
2100
2101 return false;
2102}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103
Sebastian Redl72b597d2009-01-25 19:43:20 +00002104/// CheckMemberPointerConversion - Check the member pointer conversion from the
2105/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002106/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002107/// for which IsMemberPointerConversion has already returned true. It returns
2108/// true and produces a diagnostic if there was an error, or returns false
2109/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002110bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002111 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002112 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002113 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002114 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002115 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002116 if (!FromPtrType) {
2117 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002118 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002119 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002120 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002121 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002122 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002123 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002124
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002125 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002126 assert(ToPtrType && "No member pointer cast has a target type "
2127 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002128
Sebastian Redled8f2002009-01-28 18:33:18 +00002129 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2130 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002131
Sebastian Redled8f2002009-01-28 18:33:18 +00002132 // FIXME: What about dependent types?
2133 assert(FromClass->isRecordType() && "Pointer into non-class.");
2134 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002135
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002136 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002137 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002138 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2139 assert(DerivationOkay &&
2140 "Should not have been called if derivation isn't OK.");
2141 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002142
Sebastian Redled8f2002009-01-28 18:33:18 +00002143 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2144 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002145 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2146 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2147 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2148 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002149 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002150
Douglas Gregor89ee6822009-02-28 01:32:25 +00002151 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002152 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2153 << FromClass << ToClass << QualType(VBase, 0)
2154 << From->getSourceRange();
2155 return true;
2156 }
2157
John McCall5b0829a2010-02-10 09:31:12 +00002158 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002159 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2160 Paths.front(),
2161 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002162
Anders Carlssond7923c62009-08-22 23:33:40 +00002163 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002164 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002165 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002166 return false;
2167}
2168
Douglas Gregor9a657932008-10-21 23:43:52 +00002169/// IsQualificationConversion - Determines whether the conversion from
2170/// an rvalue of type FromType to ToType is a qualification conversion
2171/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00002172bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor58281352011-01-27 00:58:17 +00002174 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002175 FromType = Context.getCanonicalType(FromType);
2176 ToType = Context.getCanonicalType(ToType);
2177
2178 // If FromType and ToType are the same type, this is not a
2179 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002180 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002181 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002182
Douglas Gregor9a657932008-10-21 23:43:52 +00002183 // (C++ 4.4p4):
2184 // A conversion can add cv-qualifiers at levels other than the first
2185 // in multi-level pointers, subject to the following rules: [...]
2186 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002187 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002188 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002189 // Within each iteration of the loop, we check the qualifiers to
2190 // determine if this still looks like a qualification
2191 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002192 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002193 // until there are no more pointers or pointers-to-members left to
2194 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002195 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002196
Douglas Gregor90609aa2011-04-25 18:40:17 +00002197 Qualifiers FromQuals = FromType.getQualifiers();
2198 Qualifiers ToQuals = ToType.getQualifiers();
2199
Douglas Gregorf30053d2011-05-08 06:09:53 +00002200 // Allow addition/removal of GC attributes but not changing GC attributes.
2201 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2202 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2203 FromQuals.removeObjCGCAttr();
2204 ToQuals.removeObjCGCAttr();
2205 }
2206
Douglas Gregor9a657932008-10-21 23:43:52 +00002207 // -- for every j > 0, if const is in cv 1,j then const is in cv
2208 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002209 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002210 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002211
Douglas Gregor9a657932008-10-21 23:43:52 +00002212 // -- if the cv 1,j and cv 2,j are different, then const is in
2213 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002214 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002215 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002216 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002217
Douglas Gregor9a657932008-10-21 23:43:52 +00002218 // Keep track of whether all prior cv-qualifiers in the "to" type
2219 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002220 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002221 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002222 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002223
2224 // We are left with FromType and ToType being the pointee types
2225 // after unwrapping the original FromType and ToType the same number
2226 // of types. If we unwrapped any pointers, and if FromType and
2227 // ToType have the same unqualified type (since we checked
2228 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002229 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002230}
2231
Douglas Gregor576e98c2009-01-30 23:27:23 +00002232/// Determines whether there is a user-defined conversion sequence
2233/// (C++ [over.ics.user]) that converts expression From to the type
2234/// ToType. If such a conversion exists, User will contain the
2235/// user-defined conversion sequence that performs such a conversion
2236/// and this routine will return true. Otherwise, this routine returns
2237/// false and User is unspecified.
2238///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002239/// \param AllowExplicit true if the conversion should consider C++0x
2240/// "explicit" conversion functions as well as non-explicit conversion
2241/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002242static OverloadingResult
2243IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2244 UserDefinedConversionSequence& User,
2245 OverloadCandidateSet& CandidateSet,
2246 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002247 // Whether we will only visit constructors.
2248 bool ConstructorsOnly = false;
2249
2250 // If the type we are conversion to is a class type, enumerate its
2251 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002252 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002253 // C++ [over.match.ctor]p1:
2254 // When objects of class type are direct-initialized (8.5), or
2255 // copy-initialized from an expression of the same or a
2256 // derived class type (8.5), overload resolution selects the
2257 // constructor. [...] For copy-initialization, the candidate
2258 // functions are all the converting constructors (12.3.1) of
2259 // that class. The argument list is the expression-list within
2260 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002261 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002262 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002263 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002264 ConstructorsOnly = true;
2265
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002266 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2267 // RequireCompleteType may have returned true due to some invalid decl
2268 // during template instantiation, but ToType may be complete enough now
2269 // to try to recover.
2270 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002271 // We're not going to find any constructors.
2272 } else if (CXXRecordDecl *ToRecordDecl
2273 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002274 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002275 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002276 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002277 NamedDecl *D = *Con;
2278 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2279
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002280 // Find the constructor (which may be a template).
2281 CXXConstructorDecl *Constructor = 0;
2282 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002283 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002284 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002285 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002286 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2287 else
John McCalla0296f72010-03-19 07:35:19 +00002288 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002289
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002290 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002291 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002292 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002293 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2294 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002295 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002296 /*SuppressUserConversions=*/
2297 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002298 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002299 // Allow one user-defined conversion when user specifies a
2300 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002301 S.AddOverloadCandidate(Constructor, FoundDecl,
2302 &From, 1, CandidateSet,
2303 /*SuppressUserConversions=*/
2304 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002305 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002306 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002307 }
2308 }
2309
Douglas Gregor5ab11652010-04-17 22:01:05 +00002310 // Enumerate conversion functions, if we're allowed to.
2311 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002312 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2313 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002314 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002315 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002316 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002317 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002318 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2319 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002320 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002321 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002322 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002323 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002324 DeclAccessPair FoundDecl = I.getPair();
2325 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002326 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2327 if (isa<UsingShadowDecl>(D))
2328 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2329
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002330 CXXConversionDecl *Conv;
2331 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002332 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2333 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002334 else
John McCallda4458e2010-03-31 01:36:47 +00002335 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002336
2337 if (AllowExplicit || !Conv->isExplicit()) {
2338 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002339 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2340 ActingContext, From, ToType,
2341 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002342 else
John McCall5c32be02010-08-24 20:38:10 +00002343 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2344 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002345 }
2346 }
2347 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002348 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002349
2350 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002351 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002352 case OR_Success:
2353 // Record the standard conversion we used and the conversion function.
2354 if (CXXConstructorDecl *Constructor
2355 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002356 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2357
John McCall5c32be02010-08-24 20:38:10 +00002358 // C++ [over.ics.user]p1:
2359 // If the user-defined conversion is specified by a
2360 // constructor (12.3.1), the initial standard conversion
2361 // sequence converts the source type to the type required by
2362 // the argument of the constructor.
2363 //
2364 QualType ThisType = Constructor->getThisType(S.Context);
2365 if (Best->Conversions[0].isEllipsis())
2366 User.EllipsisConversion = true;
2367 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002368 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002369 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002370 }
John McCall5c32be02010-08-24 20:38:10 +00002371 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002372 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002373 User.After.setAsIdentityConversion();
2374 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2375 User.After.setAllToTypes(ToType);
2376 return OR_Success;
2377 } else if (CXXConversionDecl *Conversion
2378 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002379 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2380
John McCall5c32be02010-08-24 20:38:10 +00002381 // C++ [over.ics.user]p1:
2382 //
2383 // [...] If the user-defined conversion is specified by a
2384 // conversion function (12.3.2), the initial standard
2385 // conversion sequence converts the source type to the
2386 // implicit object parameter of the conversion function.
2387 User.Before = Best->Conversions[0].Standard;
2388 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002389 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002390 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002391
John McCall5c32be02010-08-24 20:38:10 +00002392 // C++ [over.ics.user]p2:
2393 // The second standard conversion sequence converts the
2394 // result of the user-defined conversion to the target type
2395 // for the sequence. Since an implicit conversion sequence
2396 // is an initialization, the special rules for
2397 // initialization by user-defined conversion apply when
2398 // selecting the best user-defined conversion for a
2399 // user-defined conversion sequence (see 13.3.3 and
2400 // 13.3.3.1).
2401 User.After = Best->FinalConversion;
2402 return OR_Success;
2403 } else {
2404 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002405 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002406 }
2407
John McCall5c32be02010-08-24 20:38:10 +00002408 case OR_No_Viable_Function:
2409 return OR_No_Viable_Function;
2410 case OR_Deleted:
2411 // No conversion here! We're done.
2412 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002413
John McCall5c32be02010-08-24 20:38:10 +00002414 case OR_Ambiguous:
2415 return OR_Ambiguous;
2416 }
2417
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002418 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002419}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002420
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002421bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002422Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002423 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002424 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002425 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002426 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002427 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002428 if (OvResult == OR_Ambiguous)
2429 Diag(From->getSourceRange().getBegin(),
2430 diag::err_typecheck_ambiguous_condition)
2431 << From->getType() << ToType << From->getSourceRange();
2432 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2433 Diag(From->getSourceRange().getBegin(),
2434 diag::err_typecheck_nonviable_condition)
2435 << From->getType() << ToType << From->getSourceRange();
2436 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002437 return false;
John McCall5c32be02010-08-24 20:38:10 +00002438 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002439 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002440}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002441
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002442/// CompareImplicitConversionSequences - Compare two implicit
2443/// conversion sequences to determine whether one is better than the
2444/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002445static ImplicitConversionSequence::CompareKind
2446CompareImplicitConversionSequences(Sema &S,
2447 const ImplicitConversionSequence& ICS1,
2448 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002449{
2450 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2451 // conversion sequences (as defined in 13.3.3.1)
2452 // -- a standard conversion sequence (13.3.3.1.1) is a better
2453 // conversion sequence than a user-defined conversion sequence or
2454 // an ellipsis conversion sequence, and
2455 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2456 // conversion sequence than an ellipsis conversion sequence
2457 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002458 //
John McCall0d1da222010-01-12 00:44:57 +00002459 // C++0x [over.best.ics]p10:
2460 // For the purpose of ranking implicit conversion sequences as
2461 // described in 13.3.3.2, the ambiguous conversion sequence is
2462 // treated as a user-defined sequence that is indistinguishable
2463 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002464 if (ICS1.getKindRank() < ICS2.getKindRank())
2465 return ImplicitConversionSequence::Better;
2466 else if (ICS2.getKindRank() < ICS1.getKindRank())
2467 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002468
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002469 // The following checks require both conversion sequences to be of
2470 // the same kind.
2471 if (ICS1.getKind() != ICS2.getKind())
2472 return ImplicitConversionSequence::Indistinguishable;
2473
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002474 // Two implicit conversion sequences of the same form are
2475 // indistinguishable conversion sequences unless one of the
2476 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002477 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002478 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002479 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002480 // User-defined conversion sequence U1 is a better conversion
2481 // sequence than another user-defined conversion sequence U2 if
2482 // they contain the same user-defined conversion function or
2483 // constructor and if the second standard conversion sequence of
2484 // U1 is better than the second standard conversion sequence of
2485 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002486 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002487 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002488 return CompareStandardConversionSequences(S,
2489 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002490 ICS2.UserDefined.After);
2491 }
2492
2493 return ImplicitConversionSequence::Indistinguishable;
2494}
2495
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002496static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2497 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2498 Qualifiers Quals;
2499 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002500 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002502
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002503 return Context.hasSameUnqualifiedType(T1, T2);
2504}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002505
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002506// Per 13.3.3.2p3, compare the given standard conversion sequences to
2507// determine if one is a proper subset of the other.
2508static ImplicitConversionSequence::CompareKind
2509compareStandardConversionSubsets(ASTContext &Context,
2510 const StandardConversionSequence& SCS1,
2511 const StandardConversionSequence& SCS2) {
2512 ImplicitConversionSequence::CompareKind Result
2513 = ImplicitConversionSequence::Indistinguishable;
2514
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002516 // any non-identity conversion sequence
2517 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2518 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2519 return ImplicitConversionSequence::Better;
2520 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2521 return ImplicitConversionSequence::Worse;
2522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002523
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002524 if (SCS1.Second != SCS2.Second) {
2525 if (SCS1.Second == ICK_Identity)
2526 Result = ImplicitConversionSequence::Better;
2527 else if (SCS2.Second == ICK_Identity)
2528 Result = ImplicitConversionSequence::Worse;
2529 else
2530 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002531 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002532 return ImplicitConversionSequence::Indistinguishable;
2533
2534 if (SCS1.Third == SCS2.Third) {
2535 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2536 : ImplicitConversionSequence::Indistinguishable;
2537 }
2538
2539 if (SCS1.Third == ICK_Identity)
2540 return Result == ImplicitConversionSequence::Worse
2541 ? ImplicitConversionSequence::Indistinguishable
2542 : ImplicitConversionSequence::Better;
2543
2544 if (SCS2.Third == ICK_Identity)
2545 return Result == ImplicitConversionSequence::Better
2546 ? ImplicitConversionSequence::Indistinguishable
2547 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002548
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002549 return ImplicitConversionSequence::Indistinguishable;
2550}
2551
Douglas Gregore696ebb2011-01-26 14:52:12 +00002552/// \brief Determine whether one of the given reference bindings is better
2553/// than the other based on what kind of bindings they are.
2554static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2555 const StandardConversionSequence &SCS2) {
2556 // C++0x [over.ics.rank]p3b4:
2557 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2558 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002559 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002560 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002561 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002562 // reference*.
2563 //
2564 // FIXME: Rvalue references. We're going rogue with the above edits,
2565 // because the semantics in the current C++0x working paper (N3225 at the
2566 // time of this writing) break the standard definition of std::forward
2567 // and std::reference_wrapper when dealing with references to functions.
2568 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002569 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2570 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2571 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002572
Douglas Gregore696ebb2011-01-26 14:52:12 +00002573 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2574 SCS2.IsLvalueReference) ||
2575 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2576 !SCS2.IsLvalueReference);
2577}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002578
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002579/// CompareStandardConversionSequences - Compare two standard
2580/// conversion sequences to determine whether one is better than the
2581/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002582static ImplicitConversionSequence::CompareKind
2583CompareStandardConversionSequences(Sema &S,
2584 const StandardConversionSequence& SCS1,
2585 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002586{
2587 // Standard conversion sequence S1 is a better conversion sequence
2588 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2589
2590 // -- S1 is a proper subsequence of S2 (comparing the conversion
2591 // sequences in the canonical form defined by 13.3.3.1.1,
2592 // excluding any Lvalue Transformation; the identity conversion
2593 // sequence is considered to be a subsequence of any
2594 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002595 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002596 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002597 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002598
2599 // -- the rank of S1 is better than the rank of S2 (by the rules
2600 // defined below), or, if not that,
2601 ImplicitConversionRank Rank1 = SCS1.getRank();
2602 ImplicitConversionRank Rank2 = SCS2.getRank();
2603 if (Rank1 < Rank2)
2604 return ImplicitConversionSequence::Better;
2605 else if (Rank2 < Rank1)
2606 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002607
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002608 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2609 // are indistinguishable unless one of the following rules
2610 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002611
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002612 // A conversion that is not a conversion of a pointer, or
2613 // pointer to member, to bool is better than another conversion
2614 // that is such a conversion.
2615 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2616 return SCS2.isPointerConversionToBool()
2617 ? ImplicitConversionSequence::Better
2618 : ImplicitConversionSequence::Worse;
2619
Douglas Gregor5c407d92008-10-23 00:40:37 +00002620 // C++ [over.ics.rank]p4b2:
2621 //
2622 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002623 // conversion of B* to A* is better than conversion of B* to
2624 // void*, and conversion of A* to void* is better than conversion
2625 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002626 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002627 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002628 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002629 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002630 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2631 // Exactly one of the conversion sequences is a conversion to
2632 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002633 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2634 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002635 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2636 // Neither conversion sequence converts to a void pointer; compare
2637 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002638 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002639 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002640 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002641 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2642 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002643 // Both conversion sequences are conversions to void
2644 // pointers. Compare the source types to determine if there's an
2645 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002646 QualType FromType1 = SCS1.getFromType();
2647 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002648
2649 // Adjust the types we're converting from via the array-to-pointer
2650 // conversion, if we need to.
2651 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002652 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002653 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002654 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002655
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002656 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2657 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002658
John McCall5c32be02010-08-24 20:38:10 +00002659 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002660 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002661 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002662 return ImplicitConversionSequence::Worse;
2663
2664 // Objective-C++: If one interface is more specific than the
2665 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002666 const ObjCObjectPointerType* FromObjCPtr1
2667 = FromType1->getAs<ObjCObjectPointerType>();
2668 const ObjCObjectPointerType* FromObjCPtr2
2669 = FromType2->getAs<ObjCObjectPointerType>();
2670 if (FromObjCPtr1 && FromObjCPtr2) {
2671 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2672 FromObjCPtr2);
2673 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2674 FromObjCPtr1);
2675 if (AssignLeft != AssignRight) {
2676 return AssignLeft? ImplicitConversionSequence::Better
2677 : ImplicitConversionSequence::Worse;
2678 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002679 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002680 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002681
2682 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2683 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002684 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002685 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002686 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002687
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002688 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002689 // Check for a better reference binding based on the kind of bindings.
2690 if (isBetterReferenceBindingKind(SCS1, SCS2))
2691 return ImplicitConversionSequence::Better;
2692 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2693 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002694
Sebastian Redlb28b4072009-03-22 23:49:27 +00002695 // C++ [over.ics.rank]p3b4:
2696 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2697 // which the references refer are the same type except for
2698 // top-level cv-qualifiers, and the type to which the reference
2699 // initialized by S2 refers is more cv-qualified than the type
2700 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002701 QualType T1 = SCS1.getToType(2);
2702 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002703 T1 = S.Context.getCanonicalType(T1);
2704 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002705 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002706 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2707 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002708 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002709 // If the type is an array type, promote the element qualifiers to the
2710 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002711 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002712 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002713 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002714 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002715 if (T2.isMoreQualifiedThan(T1))
2716 return ImplicitConversionSequence::Better;
2717 else if (T1.isMoreQualifiedThan(T2))
2718 return ImplicitConversionSequence::Worse;
2719 }
2720 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002721
2722 return ImplicitConversionSequence::Indistinguishable;
2723}
2724
2725/// CompareQualificationConversions - Compares two standard conversion
2726/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002727/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2728ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002729CompareQualificationConversions(Sema &S,
2730 const StandardConversionSequence& SCS1,
2731 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002732 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002733 // -- S1 and S2 differ only in their qualification conversion and
2734 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2735 // cv-qualification signature of type T1 is a proper subset of
2736 // the cv-qualification signature of type T2, and S1 is not the
2737 // deprecated string literal array-to-pointer conversion (4.2).
2738 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2739 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2740 return ImplicitConversionSequence::Indistinguishable;
2741
2742 // FIXME: the example in the standard doesn't use a qualification
2743 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002744 QualType T1 = SCS1.getToType(2);
2745 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002746 T1 = S.Context.getCanonicalType(T1);
2747 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002748 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002749 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2750 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002751
2752 // If the types are the same, we won't learn anything by unwrapped
2753 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002754 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002755 return ImplicitConversionSequence::Indistinguishable;
2756
Chandler Carruth607f38e2009-12-29 07:16:59 +00002757 // If the type is an array type, promote the element qualifiers to the type
2758 // for comparison.
2759 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002760 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002761 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002762 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002763
Mike Stump11289f42009-09-09 15:08:12 +00002764 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002765 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002766 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002767 // Within each iteration of the loop, we check the qualifiers to
2768 // determine if this still looks like a qualification
2769 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002770 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002771 // until there are no more pointers or pointers-to-members left
2772 // to unwrap. This essentially mimics what
2773 // IsQualificationConversion does, but here we're checking for a
2774 // strict subset of qualifiers.
2775 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2776 // The qualifiers are the same, so this doesn't tell us anything
2777 // about how the sequences rank.
2778 ;
2779 else if (T2.isMoreQualifiedThan(T1)) {
2780 // T1 has fewer qualifiers, so it could be the better sequence.
2781 if (Result == ImplicitConversionSequence::Worse)
2782 // Neither has qualifiers that are a subset of the other's
2783 // qualifiers.
2784 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002785
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002786 Result = ImplicitConversionSequence::Better;
2787 } else if (T1.isMoreQualifiedThan(T2)) {
2788 // T2 has fewer qualifiers, so it could be the better sequence.
2789 if (Result == ImplicitConversionSequence::Better)
2790 // Neither has qualifiers that are a subset of the other's
2791 // qualifiers.
2792 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002793
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002794 Result = ImplicitConversionSequence::Worse;
2795 } else {
2796 // Qualifiers are disjoint.
2797 return ImplicitConversionSequence::Indistinguishable;
2798 }
2799
2800 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002801 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002802 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002803 }
2804
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002805 // Check that the winning standard conversion sequence isn't using
2806 // the deprecated string literal array to pointer conversion.
2807 switch (Result) {
2808 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002809 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002810 Result = ImplicitConversionSequence::Indistinguishable;
2811 break;
2812
2813 case ImplicitConversionSequence::Indistinguishable:
2814 break;
2815
2816 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002817 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002818 Result = ImplicitConversionSequence::Indistinguishable;
2819 break;
2820 }
2821
2822 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002823}
2824
Douglas Gregor5c407d92008-10-23 00:40:37 +00002825/// CompareDerivedToBaseConversions - Compares two standard conversion
2826/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002827/// various kinds of derived-to-base conversions (C++
2828/// [over.ics.rank]p4b3). As part of these checks, we also look at
2829/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002830ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002831CompareDerivedToBaseConversions(Sema &S,
2832 const StandardConversionSequence& SCS1,
2833 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002834 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002835 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002836 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002837 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002838
2839 // Adjust the types we're converting from via the array-to-pointer
2840 // conversion, if we need to.
2841 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002842 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002843 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002844 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002845
2846 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002847 FromType1 = S.Context.getCanonicalType(FromType1);
2848 ToType1 = S.Context.getCanonicalType(ToType1);
2849 FromType2 = S.Context.getCanonicalType(FromType2);
2850 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002851
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002852 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002853 //
2854 // If class B is derived directly or indirectly from class A and
2855 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002856 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002857 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002858 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002859 SCS2.Second == ICK_Pointer_Conversion &&
2860 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2861 FromType1->isPointerType() && FromType2->isPointerType() &&
2862 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002863 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002864 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002865 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002866 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002867 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002868 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002869 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002870 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002871
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002872 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002873 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002874 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002875 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002876 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002877 return ImplicitConversionSequence::Worse;
2878 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002879
2880 // -- conversion of B* to A* is better than conversion of C* to A*,
2881 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002882 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002883 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002884 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002885 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00002886 }
2887 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2888 SCS2.Second == ICK_Pointer_Conversion) {
2889 const ObjCObjectPointerType *FromPtr1
2890 = FromType1->getAs<ObjCObjectPointerType>();
2891 const ObjCObjectPointerType *FromPtr2
2892 = FromType2->getAs<ObjCObjectPointerType>();
2893 const ObjCObjectPointerType *ToPtr1
2894 = ToType1->getAs<ObjCObjectPointerType>();
2895 const ObjCObjectPointerType *ToPtr2
2896 = ToType2->getAs<ObjCObjectPointerType>();
2897
2898 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2899 // Apply the same conversion ranking rules for Objective-C pointer types
2900 // that we do for C++ pointers to class types. However, we employ the
2901 // Objective-C pseudo-subtyping relationship used for assignment of
2902 // Objective-C pointer types.
2903 bool FromAssignLeft
2904 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2905 bool FromAssignRight
2906 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2907 bool ToAssignLeft
2908 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2909 bool ToAssignRight
2910 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2911
2912 // A conversion to an a non-id object pointer type or qualified 'id'
2913 // type is better than a conversion to 'id'.
2914 if (ToPtr1->isObjCIdType() &&
2915 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2916 return ImplicitConversionSequence::Worse;
2917 if (ToPtr2->isObjCIdType() &&
2918 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2919 return ImplicitConversionSequence::Better;
2920
2921 // A conversion to a non-id object pointer type is better than a
2922 // conversion to a qualified 'id' type
2923 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2924 return ImplicitConversionSequence::Worse;
2925 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2926 return ImplicitConversionSequence::Better;
2927
2928 // A conversion to an a non-Class object pointer type or qualified 'Class'
2929 // type is better than a conversion to 'Class'.
2930 if (ToPtr1->isObjCClassType() &&
2931 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2932 return ImplicitConversionSequence::Worse;
2933 if (ToPtr2->isObjCClassType() &&
2934 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2935 return ImplicitConversionSequence::Better;
2936
2937 // A conversion to a non-Class object pointer type is better than a
2938 // conversion to a qualified 'Class' type.
2939 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2940 return ImplicitConversionSequence::Worse;
2941 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2942 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00002943
Douglas Gregor058d3de2011-01-31 18:51:41 +00002944 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2945 if (S.Context.hasSameType(FromType1, FromType2) &&
2946 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2947 (ToAssignLeft != ToAssignRight))
2948 return ToAssignLeft? ImplicitConversionSequence::Worse
2949 : ImplicitConversionSequence::Better;
2950
2951 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2952 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2953 (FromAssignLeft != FromAssignRight))
2954 return FromAssignLeft? ImplicitConversionSequence::Better
2955 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002956 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002957 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00002958
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002959 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002960 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2961 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2962 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002964 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002966 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002967 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002968 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002969 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002970 ToType2->getAs<MemberPointerType>();
2971 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2972 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2973 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2974 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2975 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2976 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2977 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2978 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002979 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002980 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002981 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002982 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002983 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002984 return ImplicitConversionSequence::Better;
2985 }
2986 // conversion of B::* to C::* is better than conversion of A::* to C::*
2987 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002988 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002989 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002990 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002991 return ImplicitConversionSequence::Worse;
2992 }
2993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994
Douglas Gregor5ab11652010-04-17 22:01:05 +00002995 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002996 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002997 // -- binding of an expression of type C to a reference of type
2998 // B& is better than binding an expression of type C to a
2999 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003000 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3001 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3002 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003003 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003004 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003005 return ImplicitConversionSequence::Worse;
3006 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003007
Douglas Gregor2fe98832008-11-03 19:09:14 +00003008 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003009 // -- binding of an expression of type B to a reference of type
3010 // A& is better than binding an expression of type C to a
3011 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003012 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3013 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3014 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003015 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003016 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003017 return ImplicitConversionSequence::Worse;
3018 }
3019 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003020
Douglas Gregor5c407d92008-10-23 00:40:37 +00003021 return ImplicitConversionSequence::Indistinguishable;
3022}
3023
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003024/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3025/// determine whether they are reference-related,
3026/// reference-compatible, reference-compatible with added
3027/// qualification, or incompatible, for use in C++ initialization by
3028/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3029/// type, and the first type (T1) is the pointee type of the reference
3030/// type being initialized.
3031Sema::ReferenceCompareResult
3032Sema::CompareReferenceRelationship(SourceLocation Loc,
3033 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003034 bool &DerivedToBase,
3035 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003036 assert(!OrigT1->isReferenceType() &&
3037 "T1 must be the pointee type of the reference type");
3038 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3039
3040 QualType T1 = Context.getCanonicalType(OrigT1);
3041 QualType T2 = Context.getCanonicalType(OrigT2);
3042 Qualifiers T1Quals, T2Quals;
3043 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3044 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3045
3046 // C++ [dcl.init.ref]p4:
3047 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3048 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3049 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003050 DerivedToBase = false;
3051 ObjCConversion = false;
3052 if (UnqualT1 == UnqualT2) {
3053 // Nothing to do.
3054 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003055 IsDerivedFrom(UnqualT2, UnqualT1))
3056 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003057 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3058 UnqualT2->isObjCObjectOrInterfaceType() &&
3059 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3060 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003061 else
3062 return Ref_Incompatible;
3063
3064 // At this point, we know that T1 and T2 are reference-related (at
3065 // least).
3066
3067 // If the type is an array type, promote the element qualifiers to the type
3068 // for comparison.
3069 if (isa<ArrayType>(T1) && T1Quals)
3070 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3071 if (isa<ArrayType>(T2) && T2Quals)
3072 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3073
3074 // C++ [dcl.init.ref]p4:
3075 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3076 // reference-related to T2 and cv1 is the same cv-qualification
3077 // as, or greater cv-qualification than, cv2. For purposes of
3078 // overload resolution, cases for which cv1 is greater
3079 // cv-qualification than cv2 are identified as
3080 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003081 //
3082 // Note that we also require equivalence of Objective-C GC and address-space
3083 // qualifiers when performing these computations, so that e.g., an int in
3084 // address space 1 is not reference-compatible with an int in address
3085 // space 2.
3086 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003087 return Ref_Compatible;
3088 else if (T1.isMoreQualifiedThan(T2))
3089 return Ref_Compatible_With_Added_Qualification;
3090 else
3091 return Ref_Related;
3092}
3093
Douglas Gregor836a7e82010-08-11 02:15:33 +00003094/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003095/// with DeclType. Return true if something definite is found.
3096static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003097FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3098 QualType DeclType, SourceLocation DeclLoc,
3099 Expr *Init, QualType T2, bool AllowRvalues,
3100 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003101 assert(T2->isRecordType() && "Can only find conversions of record types.");
3102 CXXRecordDecl *T2RecordDecl
3103 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3104
3105 OverloadCandidateSet CandidateSet(DeclLoc);
3106 const UnresolvedSetImpl *Conversions
3107 = T2RecordDecl->getVisibleConversionFunctions();
3108 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3109 E = Conversions->end(); I != E; ++I) {
3110 NamedDecl *D = *I;
3111 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3112 if (isa<UsingShadowDecl>(D))
3113 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3114
3115 FunctionTemplateDecl *ConvTemplate
3116 = dyn_cast<FunctionTemplateDecl>(D);
3117 CXXConversionDecl *Conv;
3118 if (ConvTemplate)
3119 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3120 else
3121 Conv = cast<CXXConversionDecl>(D);
3122
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003124 // explicit conversions, skip it.
3125 if (!AllowExplicit && Conv->isExplicit())
3126 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003127
Douglas Gregor836a7e82010-08-11 02:15:33 +00003128 if (AllowRvalues) {
3129 bool DerivedToBase = false;
3130 bool ObjCConversion = false;
3131 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003132 S.CompareReferenceRelationship(
3133 DeclLoc,
3134 Conv->getConversionType().getNonReferenceType()
3135 .getUnqualifiedType(),
3136 DeclType.getNonReferenceType().getUnqualifiedType(),
3137 DerivedToBase, ObjCConversion) ==
3138 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003139 continue;
3140 } else {
3141 // If the conversion function doesn't return a reference type,
3142 // it can't be considered for this conversion. An rvalue reference
3143 // is only acceptable if its referencee is a function type.
3144
3145 const ReferenceType *RefType =
3146 Conv->getConversionType()->getAs<ReferenceType>();
3147 if (!RefType ||
3148 (!RefType->isLValueReferenceType() &&
3149 !RefType->getPointeeType()->isFunctionType()))
3150 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152
Douglas Gregor836a7e82010-08-11 02:15:33 +00003153 if (ConvTemplate)
3154 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003155 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003156 else
3157 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003158 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003159 }
3160
3161 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003162 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003163 case OR_Success:
3164 // C++ [over.ics.ref]p1:
3165 //
3166 // [...] If the parameter binds directly to the result of
3167 // applying a conversion function to the argument
3168 // expression, the implicit conversion sequence is a
3169 // user-defined conversion sequence (13.3.3.1.2), with the
3170 // second standard conversion sequence either an identity
3171 // conversion or, if the conversion function returns an
3172 // entity of a type that is a derived class of the parameter
3173 // type, a derived-to-base Conversion.
3174 if (!Best->FinalConversion.DirectBinding)
3175 return false;
3176
Chandler Carruth30141632011-02-25 19:41:05 +00003177 if (Best->Function)
3178 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003179 ICS.setUserDefined();
3180 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3181 ICS.UserDefined.After = Best->FinalConversion;
3182 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003183 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003184 ICS.UserDefined.EllipsisConversion = false;
3185 assert(ICS.UserDefined.After.ReferenceBinding &&
3186 ICS.UserDefined.After.DirectBinding &&
3187 "Expected a direct reference binding!");
3188 return true;
3189
3190 case OR_Ambiguous:
3191 ICS.setAmbiguous();
3192 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3193 Cand != CandidateSet.end(); ++Cand)
3194 if (Cand->Viable)
3195 ICS.Ambiguous.addConversion(Cand->Function);
3196 return true;
3197
3198 case OR_No_Viable_Function:
3199 case OR_Deleted:
3200 // There was no suitable conversion, or we found a deleted
3201 // conversion; continue with other checks.
3202 return false;
3203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204
Eric Christopheraba9fb22010-06-30 18:36:32 +00003205 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003206}
3207
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003208/// \brief Compute an implicit conversion sequence for reference
3209/// initialization.
3210static ImplicitConversionSequence
3211TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3212 SourceLocation DeclLoc,
3213 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003214 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003215 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3216
3217 // Most paths end in a failed conversion.
3218 ImplicitConversionSequence ICS;
3219 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3220
3221 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3222 QualType T2 = Init->getType();
3223
3224 // If the initializer is the address of an overloaded function, try
3225 // to resolve the overloaded function. If all goes well, T2 is the
3226 // type of the resulting function.
3227 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3228 DeclAccessPair Found;
3229 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3230 false, Found))
3231 T2 = Fn->getType();
3232 }
3233
3234 // Compute some basic properties of the types and the initializer.
3235 bool isRValRef = DeclType->isRValueReferenceType();
3236 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003237 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003238 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003239 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003240 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3241 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003242
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003243
Sebastian Redld92badf2010-06-30 18:13:39 +00003244 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003245 // A reference to type "cv1 T1" is initialized by an expression
3246 // of type "cv2 T2" as follows:
3247
Sebastian Redld92badf2010-06-30 18:13:39 +00003248 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003249 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003250 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3251 // reference-compatible with "cv2 T2," or
3252 //
3253 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3254 if (InitCategory.isLValue() &&
3255 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003256 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003257 // When a parameter of reference type binds directly (8.5.3)
3258 // to an argument expression, the implicit conversion sequence
3259 // is the identity conversion, unless the argument expression
3260 // has a type that is a derived class of the parameter type,
3261 // in which case the implicit conversion sequence is a
3262 // derived-to-base Conversion (13.3.3.1).
3263 ICS.setStandard();
3264 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003265 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3266 : ObjCConversion? ICK_Compatible_Conversion
3267 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003268 ICS.Standard.Third = ICK_Identity;
3269 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3270 ICS.Standard.setToType(0, T2);
3271 ICS.Standard.setToType(1, T1);
3272 ICS.Standard.setToType(2, T1);
3273 ICS.Standard.ReferenceBinding = true;
3274 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003275 ICS.Standard.IsLvalueReference = !isRValRef;
3276 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3277 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003278 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003279 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003280
Sebastian Redld92badf2010-06-30 18:13:39 +00003281 // Nothing more to do: the inaccessibility/ambiguity check for
3282 // derived-to-base conversions is suppressed when we're
3283 // computing the implicit conversion sequence (C++
3284 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003285 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003286 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003287
Sebastian Redld92badf2010-06-30 18:13:39 +00003288 // -- has a class type (i.e., T2 is a class type), where T1 is
3289 // not reference-related to T2, and can be implicitly
3290 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3291 // is reference-compatible with "cv3 T3" 92) (this
3292 // conversion is selected by enumerating the applicable
3293 // conversion functions (13.3.1.6) and choosing the best
3294 // one through overload resolution (13.3)),
3295 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003296 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003297 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003298 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3299 Init, T2, /*AllowRvalues=*/false,
3300 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003301 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003302 }
3303 }
3304
Sebastian Redld92badf2010-06-30 18:13:39 +00003305 // -- Otherwise, the reference shall be an lvalue reference to a
3306 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003307 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003309 // We actually handle one oddity of C++ [over.ics.ref] at this
3310 // point, which is that, due to p2 (which short-circuits reference
3311 // binding by only attempting a simple conversion for non-direct
3312 // bindings) and p3's strange wording, we allow a const volatile
3313 // reference to bind to an rvalue. Hence the check for the presence
3314 // of "const" rather than checking for "const" being the only
3315 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003316 // This is also the point where rvalue references and lvalue inits no longer
3317 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003318 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003319 return ICS;
3320
Douglas Gregorf143cd52011-01-24 16:14:37 +00003321 // -- If the initializer expression
3322 //
3323 // -- is an xvalue, class prvalue, array prvalue or function
3324 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3325 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3326 (InitCategory.isXValue() ||
3327 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3328 (InitCategory.isLValue() && T2->isFunctionType()))) {
3329 ICS.setStandard();
3330 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003332 : ObjCConversion? ICK_Compatible_Conversion
3333 : ICK_Identity;
3334 ICS.Standard.Third = ICK_Identity;
3335 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3336 ICS.Standard.setToType(0, T2);
3337 ICS.Standard.setToType(1, T1);
3338 ICS.Standard.setToType(2, T1);
3339 ICS.Standard.ReferenceBinding = true;
3340 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3341 // binding unless we're binding to a class prvalue.
3342 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3343 // allow the use of rvalue references in C++98/03 for the benefit of
3344 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345 ICS.Standard.DirectBinding =
3346 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003347 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003348 ICS.Standard.IsLvalueReference = !isRValRef;
3349 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003351 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003352 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355
Douglas Gregorf143cd52011-01-24 16:14:37 +00003356 // -- has a class type (i.e., T2 is a class type), where T1 is not
3357 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358 // an xvalue, class prvalue, or function lvalue of type
3359 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003360 // "cv3 T3",
3361 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003363 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003365 // class subobject).
3366 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003368 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3369 Init, T2, /*AllowRvalues=*/true,
3370 AllowExplicit)) {
3371 // In the second case, if the reference is an rvalue reference
3372 // and the second standard conversion sequence of the
3373 // user-defined conversion sequence includes an lvalue-to-rvalue
3374 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003376 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3377 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3378
Douglas Gregor95273c32011-01-21 16:36:05 +00003379 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003382 // -- Otherwise, a temporary of type "cv1 T1" is created and
3383 // initialized from the initializer expression using the
3384 // rules for a non-reference copy initialization (8.5). The
3385 // reference is then bound to the temporary. If T1 is
3386 // reference-related to T2, cv1 must be the same
3387 // cv-qualification as, or greater cv-qualification than,
3388 // cv2; otherwise, the program is ill-formed.
3389 if (RefRelationship == Sema::Ref_Related) {
3390 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3391 // we would be reference-compatible or reference-compatible with
3392 // added qualification. But that wasn't the case, so the reference
3393 // initialization fails.
3394 return ICS;
3395 }
3396
3397 // If at least one of the types is a class type, the types are not
3398 // related, and we aren't allowed any user conversions, the
3399 // reference binding fails. This case is important for breaking
3400 // recursion, since TryImplicitConversion below will attempt to
3401 // create a temporary through the use of a copy constructor.
3402 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3403 (T1->isRecordType() || T2->isRecordType()))
3404 return ICS;
3405
Douglas Gregorcba72b12011-01-21 05:18:22 +00003406 // If T1 is reference-related to T2 and the reference is an rvalue
3407 // reference, the initializer expression shall not be an lvalue.
3408 if (RefRelationship >= Sema::Ref_Related &&
3409 isRValRef && Init->Classify(S.Context).isLValue())
3410 return ICS;
3411
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003412 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003413 // When a parameter of reference type is not bound directly to
3414 // an argument expression, the conversion sequence is the one
3415 // required to convert the argument expression to the
3416 // underlying type of the reference according to
3417 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3418 // to copy-initializing a temporary of the underlying type with
3419 // the argument expression. Any difference in top-level
3420 // cv-qualification is subsumed by the initialization itself
3421 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003422 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3423 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003424 /*InOverloadResolution=*/false,
3425 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003426
3427 // Of course, that's still a reference binding.
3428 if (ICS.isStandard()) {
3429 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003430 ICS.Standard.IsLvalueReference = !isRValRef;
3431 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3432 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003433 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003434 } else if (ICS.isUserDefined()) {
3435 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003436 ICS.Standard.IsLvalueReference = !isRValRef;
3437 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3438 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003439 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003440 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003441
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003442 return ICS;
3443}
3444
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003445/// TryCopyInitialization - Try to copy-initialize a value of type
3446/// ToType from the expression From. Return the implicit conversion
3447/// sequence required to pass this argument, which may be a bad
3448/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003449/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003450/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003451static ImplicitConversionSequence
3452TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003453 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003454 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003455 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003456 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003457 /*FIXME:*/From->getLocStart(),
3458 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003459 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003460
John McCall5c32be02010-08-24 20:38:10 +00003461 return TryImplicitConversion(S, From, ToType,
3462 SuppressUserConversions,
3463 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003464 InOverloadResolution,
3465 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003466}
3467
Douglas Gregor436424c2008-11-18 23:14:02 +00003468/// TryObjectArgumentInitialization - Try to initialize the object
3469/// parameter of the given member function (@c Method) from the
3470/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003471static ImplicitConversionSequence
3472TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003473 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003474 CXXMethodDecl *Method,
3475 CXXRecordDecl *ActingContext) {
3476 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003477 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3478 // const volatile object.
3479 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3480 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003481 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003482
3483 // Set up the conversion sequence as a "bad" conversion, to allow us
3484 // to exit early.
3485 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003486
3487 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003488 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003489 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003490 FromType = PT->getPointeeType();
3491
Douglas Gregor02824322011-01-26 19:30:28 +00003492 // When we had a pointer, it's implicitly dereferenced, so we
3493 // better have an lvalue.
3494 assert(FromClassification.isLValue());
3495 }
3496
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003497 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003498
Douglas Gregor02824322011-01-26 19:30:28 +00003499 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003501 // parameter is
3502 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003503 // - "lvalue reference to cv X" for functions declared without a
3504 // ref-qualifier or with the & ref-qualifier
3505 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003506 // ref-qualifier
3507 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003509 // cv-qualification on the member function declaration.
3510 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003512 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003513 // (C++ [over.match.funcs]p5). We perform a simplified version of
3514 // reference binding here, that allows class rvalues to bind to
3515 // non-constant references.
3516
Douglas Gregor02824322011-01-26 19:30:28 +00003517 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003518 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003520 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003521 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003522 ICS.setBad(BadConversionSequence::bad_qualifiers,
3523 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003524 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003525 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003526
3527 // Check that we have either the same type or a derived type. It
3528 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003529 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003530 ImplicitConversionKind SecondKind;
3531 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3532 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003533 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003534 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003535 else {
John McCall65eb8792010-02-25 01:37:24 +00003536 ICS.setBad(BadConversionSequence::unrelated_class,
3537 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003538 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003539 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003540
Douglas Gregor02824322011-01-26 19:30:28 +00003541 // Check the ref-qualifier.
3542 switch (Method->getRefQualifier()) {
3543 case RQ_None:
3544 // Do nothing; we don't care about lvalueness or rvalueness.
3545 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546
Douglas Gregor02824322011-01-26 19:30:28 +00003547 case RQ_LValue:
3548 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3549 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003551 ImplicitParamType);
3552 return ICS;
3553 }
3554 break;
3555
3556 case RQ_RValue:
3557 if (!FromClassification.isRValue()) {
3558 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003560 ImplicitParamType);
3561 return ICS;
3562 }
3563 break;
3564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003565
Douglas Gregor436424c2008-11-18 23:14:02 +00003566 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003567 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003568 ICS.Standard.setAsIdentityConversion();
3569 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003570 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003571 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003572 ICS.Standard.ReferenceBinding = true;
3573 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003575 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003576 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3577 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3578 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003579 return ICS;
3580}
3581
3582/// PerformObjectArgumentInitialization - Perform initialization of
3583/// the implicit object parameter for the given Method with the given
3584/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003585ExprResult
3586Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003587 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003588 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003589 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003590 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003591 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003592 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003593
Douglas Gregor02824322011-01-26 19:30:28 +00003594 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003595 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003596 FromRecordType = PT->getPointeeType();
3597 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003598 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003599 } else {
3600 FromRecordType = From->getType();
3601 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003602 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003603 }
3604
John McCall6e9f8f62009-12-03 04:06:58 +00003605 // Note that we always use the true parent context when performing
3606 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003607 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003608 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3609 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003610 if (ICS.isBad()) {
3611 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3612 Qualifiers FromQs = FromRecordType.getQualifiers();
3613 Qualifiers ToQs = DestType.getQualifiers();
3614 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3615 if (CVR) {
3616 Diag(From->getSourceRange().getBegin(),
3617 diag::err_member_function_call_bad_cvr)
3618 << Method->getDeclName() << FromRecordType << (CVR - 1)
3619 << From->getSourceRange();
3620 Diag(Method->getLocation(), diag::note_previous_decl)
3621 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003622 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003623 }
3624 }
3625
Douglas Gregor436424c2008-11-18 23:14:02 +00003626 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003627 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003628 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003629 }
Mike Stump11289f42009-09-09 15:08:12 +00003630
John Wiegley01296292011-04-08 18:41:53 +00003631 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3632 ExprResult FromRes =
3633 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3634 if (FromRes.isInvalid())
3635 return ExprError();
3636 From = FromRes.take();
3637 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003638
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003639 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003640 From = ImpCastExprToType(From, DestType, CK_NoOp,
3641 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3642 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003643}
3644
Douglas Gregor5fb53972009-01-14 15:45:31 +00003645/// TryContextuallyConvertToBool - Attempt to contextually convert the
3646/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003647static ImplicitConversionSequence
3648TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003649 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003650 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003651 // FIXME: Are these flags correct?
3652 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003653 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003654 /*InOverloadResolution=*/false,
3655 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003656}
3657
3658/// PerformContextuallyConvertToBool - Perform a contextual conversion
3659/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003660ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003661 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003662 if (!ICS.isBad())
3663 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Fariborz Jahanian76197412009-11-18 18:26:29 +00003665 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003666 return Diag(From->getSourceRange().getBegin(),
3667 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003668 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003669 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003670}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003672/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3673/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003674static ImplicitConversionSequence
3675TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3676 QualType Ty = S.Context.getObjCIdType();
3677 return TryImplicitConversion(S, From, Ty,
3678 // FIXME: Are these flags correct?
3679 /*SuppressUserConversions=*/false,
3680 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003681 /*InOverloadResolution=*/false,
3682 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003683}
John McCall5c32be02010-08-24 20:38:10 +00003684
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003685/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3686/// of the expression From to 'id'.
John Wiegley01296292011-04-08 18:41:53 +00003687ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003688 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003689 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003690 if (!ICS.isBad())
3691 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003692 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003693}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003694
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003695/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003696/// enumeration type.
3697///
3698/// This routine will attempt to convert an expression of class type to an
3699/// integral or enumeration type, if that class type only has a single
3700/// conversion to an integral or enumeration type.
3701///
Douglas Gregor4799d032010-06-30 00:20:43 +00003702/// \param Loc The source location of the construct that requires the
3703/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003704///
Douglas Gregor4799d032010-06-30 00:20:43 +00003705/// \param FromE The expression we're converting from.
3706///
3707/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3708/// have integral or enumeration type.
3709///
3710/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3711/// incomplete class type.
3712///
3713/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3714/// explicit conversion function (because no implicit conversion functions
3715/// were available). This is a recovery mode.
3716///
3717/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3718/// showing which conversion was picked.
3719///
3720/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3721/// conversion function that could convert to integral or enumeration type.
3722///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003724/// usable conversion function.
3725///
3726/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3727/// function, which may be an extension in this case.
3728///
3729/// \returns The expression, converted to an integral or enumeration type if
3730/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003731ExprResult
John McCallb268a282010-08-23 23:25:46 +00003732Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003733 const PartialDiagnostic &NotIntDiag,
3734 const PartialDiagnostic &IncompleteDiag,
3735 const PartialDiagnostic &ExplicitConvDiag,
3736 const PartialDiagnostic &ExplicitConvNote,
3737 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003738 const PartialDiagnostic &AmbigNote,
3739 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003740 // We can't perform any more checking for type-dependent expressions.
3741 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003742 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003743
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003744 // If the expression already has integral or enumeration type, we're golden.
3745 QualType T = From->getType();
3746 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003747 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003748
3749 // FIXME: Check for missing '()' if T is a function type?
3750
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003752 // expression of integral or enumeration type.
3753 const RecordType *RecordTy = T->getAs<RecordType>();
3754 if (!RecordTy || !getLangOptions().CPlusPlus) {
3755 Diag(Loc, NotIntDiag)
3756 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003757 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003759
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003760 // We must have a complete class type.
3761 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003762 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003764 // Look for a conversion to an integral or enumeration type.
3765 UnresolvedSet<4> ViableConversions;
3766 UnresolvedSet<4> ExplicitConversions;
3767 const UnresolvedSetImpl *Conversions
3768 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003770 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771 E = Conversions->end();
3772 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003773 ++I) {
3774 if (CXXConversionDecl *Conversion
3775 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3776 if (Conversion->getConversionType().getNonReferenceType()
3777 ->isIntegralOrEnumerationType()) {
3778 if (Conversion->isExplicit())
3779 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3780 else
3781 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3782 }
3783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003785 switch (ViableConversions.size()) {
3786 case 0:
3787 if (ExplicitConversions.size() == 1) {
3788 DeclAccessPair Found = ExplicitConversions[0];
3789 CXXConversionDecl *Conversion
3790 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003792 // The user probably meant to invoke the given explicit
3793 // conversion; use it.
3794 QualType ConvTy
3795 = Conversion->getConversionType().getNonReferenceType();
3796 std::string TypeStr;
3797 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003798
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003799 Diag(Loc, ExplicitConvDiag)
3800 << T << ConvTy
3801 << FixItHint::CreateInsertion(From->getLocStart(),
3802 "static_cast<" + TypeStr + ">(")
3803 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3804 ")");
3805 Diag(Conversion->getLocation(), ExplicitConvNote)
3806 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003807
3808 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003809 // explicit conversion function.
3810 if (isSFINAEContext())
3811 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003813 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003814 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3815 if (Result.isInvalid())
3816 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817
Douglas Gregor668443e2011-01-20 00:18:04 +00003818 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003821 // We'll complain below about a non-integral condition type.
3822 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003824 case 1: {
3825 // Apply this conversion.
3826 DeclAccessPair Found = ViableConversions[0];
3827 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828
Douglas Gregor4799d032010-06-30 00:20:43 +00003829 CXXConversionDecl *Conversion
3830 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3831 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00003833 if (ConvDiag.getDiagID()) {
3834 if (isSFINAEContext())
3835 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836
Douglas Gregor4799d032010-06-30 00:20:43 +00003837 Diag(Loc, ConvDiag)
3838 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840
Douglas Gregor668443e2011-01-20 00:18:04 +00003841 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003842 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003843 if (Result.isInvalid())
3844 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845
Douglas Gregor668443e2011-01-20 00:18:04 +00003846 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003847 break;
3848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003850 default:
3851 Diag(Loc, AmbigDiag)
3852 << T << From->getSourceRange();
3853 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3854 CXXConversionDecl *Conv
3855 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3856 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3857 Diag(Conv->getLocation(), AmbigNote)
3858 << ConvTy->isEnumeralType() << ConvTy;
3859 }
John McCallb268a282010-08-23 23:25:46 +00003860 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003862
Douglas Gregor5823da32010-06-29 23:25:20 +00003863 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003864 Diag(Loc, NotIntDiag)
3865 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003866
John McCallb268a282010-08-23 23:25:46 +00003867 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003868}
3869
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003870/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003871/// candidate functions, using the given function call arguments. If
3872/// @p SuppressUserConversions, then don't allow user-defined
3873/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003874///
3875/// \para PartialOverloading true if we are performing "partial" overloading
3876/// based on an incomplete set of function arguments. This feature is used by
3877/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003878void
3879Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003880 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003881 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003882 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003883 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003884 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003885 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003886 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003887 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003888 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003889 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003890
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003892 if (!isa<CXXConstructorDecl>(Method)) {
3893 // If we get here, it's because we're calling a member function
3894 // that is named without a member access expression (e.g.,
3895 // "this->f") that was either written explicitly or created
3896 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003897 // function, e.g., X::f(). We use an empty type for the implied
3898 // object argument (C++ [over.call.func]p3), and the acting context
3899 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003900 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003901 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00003902 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003903 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003904 return;
3905 }
3906 // We treat a constructor like a non-member function, since its object
3907 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003908 }
3909
Douglas Gregorff7028a2009-11-13 23:59:09 +00003910 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003911 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003912
Douglas Gregor27381f32009-11-23 12:27:39 +00003913 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003914 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003915
Douglas Gregorffe14e32009-11-14 01:20:54 +00003916 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3917 // C++ [class.copy]p3:
3918 // A member function template is never instantiated to perform the copy
3919 // of a class object to an object of its class type.
3920 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003922 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003923 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3924 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003925 return;
3926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003928 // Add this candidate
3929 CandidateSet.push_back(OverloadCandidate());
3930 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003931 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003932 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003933 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003934 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003935 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003936 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003938 unsigned NumArgsInProto = Proto->getNumArgs();
3939
3940 // (C++ 13.3.2p2): A candidate function having fewer than m
3941 // parameters is viable only if it has an ellipsis in its parameter
3942 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00003944 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003945 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003946 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003947 return;
3948 }
3949
3950 // (C++ 13.3.2p2): A candidate function having more than m parameters
3951 // is viable only if the (m+1)st parameter has a default argument
3952 // (8.3.6). For the purposes of overload resolution, the
3953 // parameter list is truncated on the right, so that there are
3954 // exactly m parameters.
3955 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003956 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003957 // Not enough arguments.
3958 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003959 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003960 return;
3961 }
3962
3963 // Determine the implicit conversion sequences for each of the
3964 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003965 Candidate.Conversions.resize(NumArgs);
3966 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3967 if (ArgIdx < NumArgsInProto) {
3968 // (C++ 13.3.2p3): for F to be a viable function, there shall
3969 // exist for each argument an implicit conversion sequence
3970 // (13.3.3.1) that converts that argument to the corresponding
3971 // parameter of F.
3972 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003973 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003974 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003975 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003976 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003977 if (Candidate.Conversions[ArgIdx].isBad()) {
3978 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003979 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003980 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003981 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003982 } else {
3983 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3984 // argument for which there is no corresponding parameter is
3985 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003986 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003987 }
3988 }
3989}
3990
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003991/// \brief Add all of the function declarations in the given function set to
3992/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003993void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003994 Expr **Args, unsigned NumArgs,
3995 OverloadCandidateSet& CandidateSet,
3996 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003997 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003998 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3999 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004000 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004001 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004002 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004003 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004005 CandidateSet, SuppressUserConversions);
4006 else
John McCalla0296f72010-03-19 07:35:19 +00004007 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004008 SuppressUserConversions);
4009 } else {
John McCalla0296f72010-03-19 07:35:19 +00004010 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004011 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4012 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004013 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004014 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004015 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004017 Args[0]->Classify(Context),
4018 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004019 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004020 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004021 else
John McCalla0296f72010-03-19 07:35:19 +00004022 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004023 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004024 Args, NumArgs, CandidateSet,
4025 SuppressUserConversions);
4026 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004027 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004028}
4029
John McCallf0f1cf02009-11-17 07:50:12 +00004030/// AddMethodCandidate - Adds a named decl (which is some kind of
4031/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004032void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004033 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004034 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004035 Expr **Args, unsigned NumArgs,
4036 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004037 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004038 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004039 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004040
4041 if (isa<UsingShadowDecl>(Decl))
4042 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043
John McCallf0f1cf02009-11-17 07:50:12 +00004044 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4045 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4046 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004047 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4048 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004049 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004050 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004051 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004052 } else {
John McCalla0296f72010-03-19 07:35:19 +00004053 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004054 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004055 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004056 }
4057}
4058
Douglas Gregor436424c2008-11-18 23:14:02 +00004059/// AddMethodCandidate - Adds the given C++ member function to the set
4060/// of candidate functions, using the given function call arguments
4061/// and the object argument (@c Object). For example, in a call
4062/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4063/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4064/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004065/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004066void
John McCalla0296f72010-03-19 07:35:19 +00004067Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004068 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004069 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004070 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004071 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004072 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004073 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004074 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004075 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004076 assert(!isa<CXXConstructorDecl>(Method) &&
4077 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004078
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004079 if (!CandidateSet.isNewCandidate(Method))
4080 return;
4081
Douglas Gregor27381f32009-11-23 12:27:39 +00004082 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004083 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004084
Douglas Gregor436424c2008-11-18 23:14:02 +00004085 // Add this candidate
4086 CandidateSet.push_back(OverloadCandidate());
4087 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004088 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004089 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004090 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004091 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004092 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004093
4094 unsigned NumArgsInProto = Proto->getNumArgs();
4095
4096 // (C++ 13.3.2p2): A candidate function having fewer than m
4097 // parameters is viable only if it has an ellipsis in its parameter
4098 // list (8.3.5).
4099 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4100 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004101 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004102 return;
4103 }
4104
4105 // (C++ 13.3.2p2): A candidate function having more than m parameters
4106 // is viable only if the (m+1)st parameter has a default argument
4107 // (8.3.6). For the purposes of overload resolution, the
4108 // parameter list is truncated on the right, so that there are
4109 // exactly m parameters.
4110 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4111 if (NumArgs < MinRequiredArgs) {
4112 // Not enough arguments.
4113 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004114 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004115 return;
4116 }
4117
4118 Candidate.Viable = true;
4119 Candidate.Conversions.resize(NumArgs + 1);
4120
John McCall6e9f8f62009-12-03 04:06:58 +00004121 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004122 // The implicit object argument is ignored.
4123 Candidate.IgnoreObjectArgument = true;
4124 else {
4125 // Determine the implicit conversion sequence for the object
4126 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004127 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004128 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4129 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004130 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004131 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004132 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004133 return;
4134 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004135 }
4136
4137 // Determine the implicit conversion sequences for each of the
4138 // arguments.
4139 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4140 if (ArgIdx < NumArgsInProto) {
4141 // (C++ 13.3.2p3): for F to be a viable function, there shall
4142 // exist for each argument an implicit conversion sequence
4143 // (13.3.3.1) that converts that argument to the corresponding
4144 // parameter of F.
4145 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004146 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004147 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00004149 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00004150 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004151 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004152 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004153 break;
4154 }
4155 } else {
4156 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4157 // argument for which there is no corresponding parameter is
4158 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004159 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004160 }
4161 }
4162}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004163
Douglas Gregor97628d62009-08-21 00:16:32 +00004164/// \brief Add a C++ member function template as a candidate to the candidate
4165/// set, using template argument deduction to produce an appropriate member
4166/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004167void
Douglas Gregor97628d62009-08-21 00:16:32 +00004168Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004169 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004170 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004171 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004172 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004173 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004174 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004175 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004176 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004177 if (!CandidateSet.isNewCandidate(MethodTmpl))
4178 return;
4179
Douglas Gregor97628d62009-08-21 00:16:32 +00004180 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004181 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004182 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004183 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004184 // candidate functions in the usual way.113) A given name can refer to one
4185 // or more function templates and also to a set of overloaded non-template
4186 // functions. In such a case, the candidate functions generated from each
4187 // function template are combined with the set of non-template candidate
4188 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004189 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004190 FunctionDecl *Specialization = 0;
4191 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004192 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004193 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004194 CandidateSet.push_back(OverloadCandidate());
4195 OverloadCandidate &Candidate = CandidateSet.back();
4196 Candidate.FoundDecl = FoundDecl;
4197 Candidate.Function = MethodTmpl->getTemplatedDecl();
4198 Candidate.Viable = false;
4199 Candidate.FailureKind = ovl_fail_bad_deduction;
4200 Candidate.IsSurrogate = false;
4201 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004202 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004204 Info);
4205 return;
4206 }
Mike Stump11289f42009-09-09 15:08:12 +00004207
Douglas Gregor97628d62009-08-21 00:16:32 +00004208 // Add the function template specialization produced by template argument
4209 // deduction as a candidate.
4210 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004211 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004212 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004213 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004214 ActingContext, ObjectType, ObjectClassification,
4215 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004216}
4217
Douglas Gregor05155d82009-08-21 23:19:43 +00004218/// \brief Add a C++ function template specialization as a candidate
4219/// in the candidate set, using template argument deduction to produce
4220/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004221void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004222Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004223 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004224 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004225 Expr **Args, unsigned NumArgs,
4226 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004227 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004228 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4229 return;
4230
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004231 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004232 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004233 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004234 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004235 // candidate functions in the usual way.113) A given name can refer to one
4236 // or more function templates and also to a set of overloaded non-template
4237 // functions. In such a case, the candidate functions generated from each
4238 // function template are combined with the set of non-template candidate
4239 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004240 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004241 FunctionDecl *Specialization = 0;
4242 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004243 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004244 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004245 CandidateSet.push_back(OverloadCandidate());
4246 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004247 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004248 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4249 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004250 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004251 Candidate.IsSurrogate = false;
4252 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004253 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004254 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004255 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004256 return;
4257 }
Mike Stump11289f42009-09-09 15:08:12 +00004258
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004259 // Add the function template specialization produced by template argument
4260 // deduction as a candidate.
4261 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004262 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004263 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004264}
Mike Stump11289f42009-09-09 15:08:12 +00004265
Douglas Gregora1f013e2008-11-07 22:36:19 +00004266/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004267/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004268/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004269/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004270/// (which may or may not be the same type as the type that the
4271/// conversion function produces).
4272void
4273Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004274 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004275 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004276 Expr *From, QualType ToType,
4277 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004278 assert(!Conversion->getDescribedFunctionTemplate() &&
4279 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004280 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004281 if (!CandidateSet.isNewCandidate(Conversion))
4282 return;
4283
Douglas Gregor27381f32009-11-23 12:27:39 +00004284 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004285 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004286
Douglas Gregora1f013e2008-11-07 22:36:19 +00004287 // Add this candidate
4288 CandidateSet.push_back(OverloadCandidate());
4289 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004290 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004291 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004292 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004293 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004294 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004295 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004296 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004297 Candidate.Viable = true;
4298 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004299 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004300
Douglas Gregor6affc782010-08-19 15:37:02 +00004301 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302 // For conversion functions, the function is considered to be a member of
4303 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004304 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004305 //
4306 // Determine the implicit conversion sequence for the implicit
4307 // object parameter.
4308 QualType ImplicitParamType = From->getType();
4309 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4310 ImplicitParamType = FromPtrType->getPointeeType();
4311 CXXRecordDecl *ConversionContext
4312 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004314 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315 = TryObjectArgumentInitialization(*this, From->getType(),
4316 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004317 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318
John McCall0d1da222010-01-12 00:44:57 +00004319 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004320 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004321 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004322 return;
4323 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004324
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004325 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004326 // derived to base as such conversions are given Conversion Rank. They only
4327 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4328 QualType FromCanon
4329 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4330 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4331 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4332 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004333 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004334 return;
4335 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336
Douglas Gregora1f013e2008-11-07 22:36:19 +00004337 // To determine what the conversion from the result of calling the
4338 // conversion function to the type we're eventually trying to
4339 // convert to (ToType), we need to synthesize a call to the
4340 // conversion function and attempt copy initialization from it. This
4341 // makes sure that we get the right semantics with respect to
4342 // lvalues/rvalues and the type. Fortunately, we can allocate this
4343 // call on the stack and we don't need its arguments to be
4344 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004345 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004346 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004347 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4348 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004349 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004350 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004351
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004352 QualType CallResultType
4353 = Conversion->getConversionType().getNonLValueExprType(Context);
4354 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4355 Candidate.Viable = false;
4356 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4357 return;
4358 }
4359
John McCall7decc9e2010-11-18 06:31:45 +00004360 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4361
Mike Stump11289f42009-09-09 15:08:12 +00004362 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004363 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4364 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004365 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004366 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004367 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004368 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004369 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004370 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004371
John McCall0d1da222010-01-12 00:44:57 +00004372 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004373 case ImplicitConversionSequence::StandardConversion:
4374 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004376 // C++ [over.ics.user]p3:
4377 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004379 // shall have exact match rank.
4380 if (Conversion->getPrimaryTemplate() &&
4381 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4382 Candidate.Viable = false;
4383 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004385
Douglas Gregorcba72b12011-01-21 05:18:22 +00004386 // C++0x [dcl.init.ref]p5:
4387 // In the second case, if the reference is an rvalue reference and
4388 // the second standard conversion sequence of the user-defined
4389 // conversion sequence includes an lvalue-to-rvalue conversion, the
4390 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004392 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4393 Candidate.Viable = false;
4394 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4395 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004396 break;
4397
4398 case ImplicitConversionSequence::BadConversion:
4399 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004400 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004401 break;
4402
4403 default:
Mike Stump11289f42009-09-09 15:08:12 +00004404 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004405 "Can only end up with a standard conversion sequence or failure");
4406 }
4407}
4408
Douglas Gregor05155d82009-08-21 23:19:43 +00004409/// \brief Adds a conversion function template specialization
4410/// candidate to the overload set, using template argument deduction
4411/// to deduce the template arguments of the conversion function
4412/// template from the type that we are converting to (C++
4413/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004414void
Douglas Gregor05155d82009-08-21 23:19:43 +00004415Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004416 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004417 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004418 Expr *From, QualType ToType,
4419 OverloadCandidateSet &CandidateSet) {
4420 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4421 "Only conversion function templates permitted here");
4422
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004423 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4424 return;
4425
John McCallbc077cf2010-02-08 23:07:23 +00004426 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004427 CXXConversionDecl *Specialization = 0;
4428 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004429 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004430 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004431 CandidateSet.push_back(OverloadCandidate());
4432 OverloadCandidate &Candidate = CandidateSet.back();
4433 Candidate.FoundDecl = FoundDecl;
4434 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4435 Candidate.Viable = false;
4436 Candidate.FailureKind = ovl_fail_bad_deduction;
4437 Candidate.IsSurrogate = false;
4438 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004439 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004440 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004441 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004442 return;
4443 }
Mike Stump11289f42009-09-09 15:08:12 +00004444
Douglas Gregor05155d82009-08-21 23:19:43 +00004445 // Add the conversion function template specialization produced by
4446 // template argument deduction as a candidate.
4447 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004448 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004449 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004450}
4451
Douglas Gregorab7897a2008-11-19 22:57:39 +00004452/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4453/// converts the given @c Object to a function pointer via the
4454/// conversion function @c Conversion, and then attempts to call it
4455/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4456/// the type of function that we'll eventually be calling.
4457void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004458 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004459 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004460 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004461 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004462 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004463 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004464 if (!CandidateSet.isNewCandidate(Conversion))
4465 return;
4466
Douglas Gregor27381f32009-11-23 12:27:39 +00004467 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004468 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004469
Douglas Gregorab7897a2008-11-19 22:57:39 +00004470 CandidateSet.push_back(OverloadCandidate());
4471 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004472 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004473 Candidate.Function = 0;
4474 Candidate.Surrogate = Conversion;
4475 Candidate.Viable = true;
4476 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004477 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004478 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004479 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004480
4481 // Determine the implicit conversion sequence for the implicit
4482 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004483 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004484 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004485 Object->Classify(Context),
4486 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004487 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004488 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004489 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004490 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004491 return;
4492 }
4493
4494 // The first conversion is actually a user-defined conversion whose
4495 // first conversion is ObjectInit's standard conversion (which is
4496 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004497 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004498 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004499 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004500 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004502 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004503 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004504 = Candidate.Conversions[0].UserDefined.Before;
4505 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4506
Mike Stump11289f42009-09-09 15:08:12 +00004507 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004508 unsigned NumArgsInProto = Proto->getNumArgs();
4509
4510 // (C++ 13.3.2p2): A candidate function having fewer than m
4511 // parameters is viable only if it has an ellipsis in its parameter
4512 // list (8.3.5).
4513 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4514 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004515 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004516 return;
4517 }
4518
4519 // Function types don't have any default arguments, so just check if
4520 // we have enough arguments.
4521 if (NumArgs < NumArgsInProto) {
4522 // Not enough arguments.
4523 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004524 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004525 return;
4526 }
4527
4528 // Determine the implicit conversion sequences for each of the
4529 // arguments.
4530 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4531 if (ArgIdx < NumArgsInProto) {
4532 // (C++ 13.3.2p3): for F to be a viable function, there shall
4533 // exist for each argument an implicit conversion sequence
4534 // (13.3.3.1) that converts that argument to the corresponding
4535 // parameter of F.
4536 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004537 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004538 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004539 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004540 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004541 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004542 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004543 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004544 break;
4545 }
4546 } else {
4547 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4548 // argument for which there is no corresponding parameter is
4549 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004550 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004551 }
4552 }
4553}
4554
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004555/// \brief Add overload candidates for overloaded operators that are
4556/// member functions.
4557///
4558/// Add the overloaded operator candidates that are member functions
4559/// for the operator Op that was used in an operator expression such
4560/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4561/// CandidateSet will store the added overload candidates. (C++
4562/// [over.match.oper]).
4563void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4564 SourceLocation OpLoc,
4565 Expr **Args, unsigned NumArgs,
4566 OverloadCandidateSet& CandidateSet,
4567 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004568 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4569
4570 // C++ [over.match.oper]p3:
4571 // For a unary operator @ with an operand of a type whose
4572 // cv-unqualified version is T1, and for a binary operator @ with
4573 // a left operand of a type whose cv-unqualified version is T1 and
4574 // a right operand of a type whose cv-unqualified version is T2,
4575 // three sets of candidate functions, designated member
4576 // candidates, non-member candidates and built-in candidates, are
4577 // constructed as follows:
4578 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004579
4580 // -- If T1 is a class type, the set of member candidates is the
4581 // result of the qualified lookup of T1::operator@
4582 // (13.3.1.1.1); otherwise, the set of member candidates is
4583 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004584 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004585 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004586 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004587 return;
Mike Stump11289f42009-09-09 15:08:12 +00004588
John McCall27b18f82009-11-17 02:14:36 +00004589 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4590 LookupQualifiedName(Operators, T1Rec->getDecl());
4591 Operators.suppressDiagnostics();
4592
Mike Stump11289f42009-09-09 15:08:12 +00004593 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004594 OperEnd = Operators.end();
4595 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004596 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004597 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004598 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004599 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004600 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004601 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004602}
4603
Douglas Gregora11693b2008-11-12 17:17:38 +00004604/// AddBuiltinCandidate - Add a candidate for a built-in
4605/// operator. ResultTy and ParamTys are the result and parameter types
4606/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004607/// arguments being passed to the candidate. IsAssignmentOperator
4608/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004609/// operator. NumContextualBoolArguments is the number of arguments
4610/// (at the beginning of the argument list) that will be contextually
4611/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004612void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004613 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004614 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004615 bool IsAssignmentOperator,
4616 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004617 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004618 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004619
Douglas Gregora11693b2008-11-12 17:17:38 +00004620 // Add this candidate
4621 CandidateSet.push_back(OverloadCandidate());
4622 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004623 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004624 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004625 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004626 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004627 Candidate.BuiltinTypes.ResultTy = ResultTy;
4628 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4629 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4630
4631 // Determine the implicit conversion sequences for each of the
4632 // arguments.
4633 Candidate.Viable = true;
4634 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004635 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004636 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004637 // C++ [over.match.oper]p4:
4638 // For the built-in assignment operators, conversions of the
4639 // left operand are restricted as follows:
4640 // -- no temporaries are introduced to hold the left operand, and
4641 // -- no user-defined conversions are applied to the left
4642 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004643 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004644 //
4645 // We block these conversions by turning off user-defined
4646 // conversions, since that is the only way that initialization of
4647 // a reference to a non-class type can occur from something that
4648 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004649 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004650 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004651 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004652 Candidate.Conversions[ArgIdx]
4653 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004654 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004655 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004656 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004657 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004658 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004659 }
John McCall0d1da222010-01-12 00:44:57 +00004660 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004661 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004662 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004663 break;
4664 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004665 }
4666}
4667
4668/// BuiltinCandidateTypeSet - A set of types that will be used for the
4669/// candidate operator functions for built-in operators (C++
4670/// [over.built]). The types are separated into pointer types and
4671/// enumeration types.
4672class BuiltinCandidateTypeSet {
4673 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004674 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004675
4676 /// PointerTypes - The set of pointer types that will be used in the
4677 /// built-in candidates.
4678 TypeSet PointerTypes;
4679
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004680 /// MemberPointerTypes - The set of member pointer types that will be
4681 /// used in the built-in candidates.
4682 TypeSet MemberPointerTypes;
4683
Douglas Gregora11693b2008-11-12 17:17:38 +00004684 /// EnumerationTypes - The set of enumeration types that will be
4685 /// used in the built-in candidates.
4686 TypeSet EnumerationTypes;
4687
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004689 /// candidates.
4690 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004691
4692 /// \brief A flag indicating non-record types are viable candidates
4693 bool HasNonRecordTypes;
4694
4695 /// \brief A flag indicating whether either arithmetic or enumeration types
4696 /// were present in the candidate set.
4697 bool HasArithmeticOrEnumeralTypes;
4698
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004699 /// Sema - The semantic analysis instance where we are building the
4700 /// candidate type set.
4701 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004702
Douglas Gregora11693b2008-11-12 17:17:38 +00004703 /// Context - The AST context in which we will build the type sets.
4704 ASTContext &Context;
4705
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004706 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4707 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004708 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004709
4710public:
4711 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004712 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004713
Mike Stump11289f42009-09-09 15:08:12 +00004714 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004715 : HasNonRecordTypes(false),
4716 HasArithmeticOrEnumeralTypes(false),
4717 SemaRef(SemaRef),
4718 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004719
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004721 SourceLocation Loc,
4722 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004723 bool AllowExplicitConversions,
4724 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004725
4726 /// pointer_begin - First pointer type found;
4727 iterator pointer_begin() { return PointerTypes.begin(); }
4728
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004729 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004730 iterator pointer_end() { return PointerTypes.end(); }
4731
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004732 /// member_pointer_begin - First member pointer type found;
4733 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4734
4735 /// member_pointer_end - Past the last member pointer type found;
4736 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4737
Douglas Gregora11693b2008-11-12 17:17:38 +00004738 /// enumeration_begin - First enumeration type found;
4739 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4740
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004741 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004742 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004744 iterator vector_begin() { return VectorTypes.begin(); }
4745 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004746
4747 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4748 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004749};
4750
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004751/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004752/// the set of pointer types along with any more-qualified variants of
4753/// that type. For example, if @p Ty is "int const *", this routine
4754/// will add "int const *", "int const volatile *", "int const
4755/// restrict *", and "int const volatile restrict *" to the set of
4756/// pointer types. Returns true if the add of @p Ty itself succeeded,
4757/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004758///
4759/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004760bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004761BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4762 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004763
Douglas Gregora11693b2008-11-12 17:17:38 +00004764 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004765 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004766 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004768 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004769 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004770 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004771 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004772 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004773 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004774 buildObjCPtr = true;
4775 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004776 else
4777 assert(false && "type was not a pointer type!");
4778 }
4779 else
4780 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781
Sebastian Redl4990a632009-11-18 20:39:26 +00004782 // Don't add qualified variants of arrays. For one, they're not allowed
4783 // (the qualifier would sink to the element type), and for another, the
4784 // only overload situation where it matters is subscript or pointer +- int,
4785 // and those shouldn't have qualifier variants anyway.
4786 if (PointeeTy->isArrayType())
4787 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004788 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004789 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004790 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004791 bool hasVolatile = VisibleQuals.hasVolatile();
4792 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004793
John McCall8ccfcb52009-09-24 19:53:00 +00004794 // Iterate through all strict supersets of BaseCVR.
4795 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4796 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004797 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4798 // in the types.
4799 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4800 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004801 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004802 if (!buildObjCPtr)
4803 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4804 else
4805 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004806 }
4807
4808 return true;
4809}
4810
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004811/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4812/// to the set of pointer types along with any more-qualified variants of
4813/// that type. For example, if @p Ty is "int const *", this routine
4814/// will add "int const *", "int const volatile *", "int const
4815/// restrict *", and "int const volatile restrict *" to the set of
4816/// pointer types. Returns true if the add of @p Ty itself succeeded,
4817/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004818///
4819/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004820bool
4821BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4822 QualType Ty) {
4823 // Insert this type.
4824 if (!MemberPointerTypes.insert(Ty))
4825 return false;
4826
John McCall8ccfcb52009-09-24 19:53:00 +00004827 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4828 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004829
John McCall8ccfcb52009-09-24 19:53:00 +00004830 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004831 // Don't add qualified variants of arrays. For one, they're not allowed
4832 // (the qualifier would sink to the element type), and for another, the
4833 // only overload situation where it matters is subscript or pointer +- int,
4834 // and those shouldn't have qualifier variants anyway.
4835 if (PointeeTy->isArrayType())
4836 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004837 const Type *ClassTy = PointerTy->getClass();
4838
4839 // Iterate through all strict supersets of the pointee type's CVR
4840 // qualifiers.
4841 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4842 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4843 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844
John McCall8ccfcb52009-09-24 19:53:00 +00004845 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004846 MemberPointerTypes.insert(
4847 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004848 }
4849
4850 return true;
4851}
4852
Douglas Gregora11693b2008-11-12 17:17:38 +00004853/// AddTypesConvertedFrom - Add each of the types to which the type @p
4854/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004855/// primarily interested in pointer types and enumeration types. We also
4856/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004857/// AllowUserConversions is true if we should look at the conversion
4858/// functions of a class type, and AllowExplicitConversions if we
4859/// should also include the explicit conversion functions of a class
4860/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004861void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004862BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004863 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004864 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004865 bool AllowExplicitConversions,
4866 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004867 // Only deal with canonical types.
4868 Ty = Context.getCanonicalType(Ty);
4869
4870 // Look through reference types; they aren't part of the type of an
4871 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004872 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004873 Ty = RefTy->getPointeeType();
4874
John McCall33ddac02011-01-19 10:06:00 +00004875 // If we're dealing with an array type, decay to the pointer.
4876 if (Ty->isArrayType())
4877 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4878
4879 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004880 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004881
Chandler Carruth00a38332010-12-13 01:44:01 +00004882 // Flag if we ever add a non-record type.
4883 const RecordType *TyRec = Ty->getAs<RecordType>();
4884 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4885
Chandler Carruth00a38332010-12-13 01:44:01 +00004886 // Flag if we encounter an arithmetic type.
4887 HasArithmeticOrEnumeralTypes =
4888 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4889
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004890 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4891 PointerTypes.insert(Ty);
4892 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004893 // Insert our type, and its more-qualified variants, into the set
4894 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004895 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004896 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004897 } else if (Ty->isMemberPointerType()) {
4898 // Member pointers are far easier, since the pointee can't be converted.
4899 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4900 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004901 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004902 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004903 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004904 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004905 // We treat vector types as arithmetic types in many contexts as an
4906 // extension.
4907 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004908 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004909 } else if (AllowUserConversions && TyRec) {
4910 // No conversion functions in incomplete types.
4911 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4912 return;
Mike Stump11289f42009-09-09 15:08:12 +00004913
Chandler Carruth00a38332010-12-13 01:44:01 +00004914 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4915 const UnresolvedSetImpl *Conversions
4916 = ClassDecl->getVisibleConversionFunctions();
4917 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4918 E = Conversions->end(); I != E; ++I) {
4919 NamedDecl *D = I.getDecl();
4920 if (isa<UsingShadowDecl>(D))
4921 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004922
Chandler Carruth00a38332010-12-13 01:44:01 +00004923 // Skip conversion function templates; they don't tell us anything
4924 // about which builtin types we can convert to.
4925 if (isa<FunctionTemplateDecl>(D))
4926 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004927
Chandler Carruth00a38332010-12-13 01:44:01 +00004928 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4929 if (AllowExplicitConversions || !Conv->isExplicit()) {
4930 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4931 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004932 }
4933 }
4934 }
4935}
4936
Douglas Gregor84605ae2009-08-24 13:43:27 +00004937/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4938/// the volatile- and non-volatile-qualified assignment operators for the
4939/// given type to the candidate set.
4940static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4941 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004942 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004943 unsigned NumArgs,
4944 OverloadCandidateSet &CandidateSet) {
4945 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004946
Douglas Gregor84605ae2009-08-24 13:43:27 +00004947 // T& operator=(T&, T)
4948 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4949 ParamTypes[1] = T;
4950 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4951 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004952
Douglas Gregor84605ae2009-08-24 13:43:27 +00004953 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4954 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004955 ParamTypes[0]
4956 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004957 ParamTypes[1] = T;
4958 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004959 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004960 }
4961}
Mike Stump11289f42009-09-09 15:08:12 +00004962
Sebastian Redl1054fae2009-10-25 17:03:50 +00004963/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4964/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004965static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4966 Qualifiers VRQuals;
4967 const RecordType *TyRec;
4968 if (const MemberPointerType *RHSMPType =
4969 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004970 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004971 else
4972 TyRec = ArgExpr->getType()->getAs<RecordType>();
4973 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004974 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004975 VRQuals.addVolatile();
4976 VRQuals.addRestrict();
4977 return VRQuals;
4978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004980 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004981 if (!ClassDecl->hasDefinition())
4982 return VRQuals;
4983
John McCallad371252010-01-20 00:46:10 +00004984 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004985 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004986
John McCallad371252010-01-20 00:46:10 +00004987 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004988 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004989 NamedDecl *D = I.getDecl();
4990 if (isa<UsingShadowDecl>(D))
4991 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4992 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004993 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4994 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4995 CanTy = ResTypeRef->getPointeeType();
4996 // Need to go down the pointer/mempointer chain and add qualifiers
4997 // as see them.
4998 bool done = false;
4999 while (!done) {
5000 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5001 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005002 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005003 CanTy->getAs<MemberPointerType>())
5004 CanTy = ResTypeMPtr->getPointeeType();
5005 else
5006 done = true;
5007 if (CanTy.isVolatileQualified())
5008 VRQuals.addVolatile();
5009 if (CanTy.isRestrictQualified())
5010 VRQuals.addRestrict();
5011 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5012 return VRQuals;
5013 }
5014 }
5015 }
5016 return VRQuals;
5017}
John McCall52872982010-11-13 05:51:15 +00005018
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005019namespace {
John McCall52872982010-11-13 05:51:15 +00005020
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005021/// \brief Helper class to manage the addition of builtin operator overload
5022/// candidates. It provides shared state and utility methods used throughout
5023/// the process, as well as a helper method to add each group of builtin
5024/// operator overloads from the standard to a candidate set.
5025class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005026 // Common instance state available to all overload candidate addition methods.
5027 Sema &S;
5028 Expr **Args;
5029 unsigned NumArgs;
5030 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005031 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005032 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
5033 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005034
Chandler Carruthc6586e52010-12-12 10:35:00 +00005035 // Define some constants used to index and iterate over the arithemetic types
5036 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005037 // The "promoted arithmetic types" are the arithmetic
5038 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005039 static const unsigned FirstIntegralType = 3;
5040 static const unsigned LastIntegralType = 18;
5041 static const unsigned FirstPromotedIntegralType = 3,
5042 LastPromotedIntegralType = 9;
5043 static const unsigned FirstPromotedArithmeticType = 0,
5044 LastPromotedArithmeticType = 9;
5045 static const unsigned NumArithmeticTypes = 18;
5046
Chandler Carruthc6586e52010-12-12 10:35:00 +00005047 /// \brief Get the canonical type for a given arithmetic type index.
5048 CanQualType getArithmeticType(unsigned index) {
5049 assert(index < NumArithmeticTypes);
5050 static CanQualType ASTContext::* const
5051 ArithmeticTypes[NumArithmeticTypes] = {
5052 // Start of promoted types.
5053 &ASTContext::FloatTy,
5054 &ASTContext::DoubleTy,
5055 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005056
Chandler Carruthc6586e52010-12-12 10:35:00 +00005057 // Start of integral types.
5058 &ASTContext::IntTy,
5059 &ASTContext::LongTy,
5060 &ASTContext::LongLongTy,
5061 &ASTContext::UnsignedIntTy,
5062 &ASTContext::UnsignedLongTy,
5063 &ASTContext::UnsignedLongLongTy,
5064 // End of promoted types.
5065
5066 &ASTContext::BoolTy,
5067 &ASTContext::CharTy,
5068 &ASTContext::WCharTy,
5069 &ASTContext::Char16Ty,
5070 &ASTContext::Char32Ty,
5071 &ASTContext::SignedCharTy,
5072 &ASTContext::ShortTy,
5073 &ASTContext::UnsignedCharTy,
5074 &ASTContext::UnsignedShortTy,
5075 // End of integral types.
5076 // FIXME: What about complex?
5077 };
5078 return S.Context.*ArithmeticTypes[index];
5079 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005080
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005081 /// \brief Gets the canonical type resulting from the usual arithemetic
5082 /// converions for the given arithmetic types.
5083 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5084 // Accelerator table for performing the usual arithmetic conversions.
5085 // The rules are basically:
5086 // - if either is floating-point, use the wider floating-point
5087 // - if same signedness, use the higher rank
5088 // - if same size, use unsigned of the higher rank
5089 // - use the larger type
5090 // These rules, together with the axiom that higher ranks are
5091 // never smaller, are sufficient to precompute all of these results
5092 // *except* when dealing with signed types of higher rank.
5093 // (we could precompute SLL x UI for all known platforms, but it's
5094 // better not to make any assumptions).
5095 enum PromotedType {
5096 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5097 };
5098 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5099 [LastPromotedArithmeticType] = {
5100 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5101 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5102 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5103 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5104 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5105 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5106 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5107 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5108 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5109 };
5110
5111 assert(L < LastPromotedArithmeticType);
5112 assert(R < LastPromotedArithmeticType);
5113 int Idx = ConversionsTable[L][R];
5114
5115 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005116 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005117
5118 // Slow path: we need to compare widths.
5119 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005120 CanQualType LT = getArithmeticType(L),
5121 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005122 unsigned LW = S.Context.getIntWidth(LT),
5123 RW = S.Context.getIntWidth(RT);
5124
5125 // If they're different widths, use the signed type.
5126 if (LW > RW) return LT;
5127 else if (LW < RW) return RT;
5128
5129 // Otherwise, use the unsigned type of the signed type's rank.
5130 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5131 assert(L == SLL || R == SLL);
5132 return S.Context.UnsignedLongLongTy;
5133 }
5134
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005135 /// \brief Helper method to factor out the common pattern of adding overloads
5136 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005137 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5138 bool HasVolatile) {
5139 QualType ParamTypes[2] = {
5140 S.Context.getLValueReferenceType(CandidateTy),
5141 S.Context.IntTy
5142 };
5143
5144 // Non-volatile version.
5145 if (NumArgs == 1)
5146 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5147 else
5148 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5149
5150 // Use a heuristic to reduce number of builtin candidates in the set:
5151 // add volatile version only if there are conversions to a volatile type.
5152 if (HasVolatile) {
5153 ParamTypes[0] =
5154 S.Context.getLValueReferenceType(
5155 S.Context.getVolatileType(CandidateTy));
5156 if (NumArgs == 1)
5157 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5158 else
5159 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5160 }
5161 }
5162
5163public:
5164 BuiltinOperatorOverloadBuilder(
5165 Sema &S, Expr **Args, unsigned NumArgs,
5166 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005167 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005168 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5169 OverloadCandidateSet &CandidateSet)
5170 : S(S), Args(Args), NumArgs(NumArgs),
5171 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005172 HasArithmeticOrEnumeralCandidateType(
5173 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005174 CandidateTypes(CandidateTypes),
5175 CandidateSet(CandidateSet) {
5176 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005177 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005178 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005179 assert(getArithmeticType(LastPromotedIntegralType - 1)
5180 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005181 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005182 assert(getArithmeticType(FirstPromotedArithmeticType)
5183 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005184 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005185 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5186 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005187 "Invalid last promoted arithmetic type");
5188 }
5189
5190 // C++ [over.built]p3:
5191 //
5192 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5193 // is either volatile or empty, there exist candidate operator
5194 // functions of the form
5195 //
5196 // VQ T& operator++(VQ T&);
5197 // T operator++(VQ T&, int);
5198 //
5199 // C++ [over.built]p4:
5200 //
5201 // For every pair (T, VQ), where T is an arithmetic type other
5202 // than bool, and VQ is either volatile or empty, there exist
5203 // candidate operator functions of the form
5204 //
5205 // VQ T& operator--(VQ T&);
5206 // T operator--(VQ T&, int);
5207 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005208 if (!HasArithmeticOrEnumeralCandidateType)
5209 return;
5210
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005211 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5212 Arith < NumArithmeticTypes; ++Arith) {
5213 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005214 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005215 VisibleTypeConversionsQuals.hasVolatile());
5216 }
5217 }
5218
5219 // C++ [over.built]p5:
5220 //
5221 // For every pair (T, VQ), where T is a cv-qualified or
5222 // cv-unqualified object type, and VQ is either volatile or
5223 // empty, there exist candidate operator functions of the form
5224 //
5225 // T*VQ& operator++(T*VQ&);
5226 // T*VQ& operator--(T*VQ&);
5227 // T* operator++(T*VQ&, int);
5228 // T* operator--(T*VQ&, int);
5229 void addPlusPlusMinusMinusPointerOverloads() {
5230 for (BuiltinCandidateTypeSet::iterator
5231 Ptr = CandidateTypes[0].pointer_begin(),
5232 PtrEnd = CandidateTypes[0].pointer_end();
5233 Ptr != PtrEnd; ++Ptr) {
5234 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005235 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005236 continue;
5237
5238 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5239 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5240 VisibleTypeConversionsQuals.hasVolatile()));
5241 }
5242 }
5243
5244 // C++ [over.built]p6:
5245 // For every cv-qualified or cv-unqualified object type T, there
5246 // exist candidate operator functions of the form
5247 //
5248 // T& operator*(T*);
5249 //
5250 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005251 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005252 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005253 // T& operator*(T*);
5254 void addUnaryStarPointerOverloads() {
5255 for (BuiltinCandidateTypeSet::iterator
5256 Ptr = CandidateTypes[0].pointer_begin(),
5257 PtrEnd = CandidateTypes[0].pointer_end();
5258 Ptr != PtrEnd; ++Ptr) {
5259 QualType ParamTy = *Ptr;
5260 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005261 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5262 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005263
Douglas Gregor02824322011-01-26 19:30:28 +00005264 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5265 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5266 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005268 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5269 &ParamTy, Args, 1, CandidateSet);
5270 }
5271 }
5272
5273 // C++ [over.built]p9:
5274 // For every promoted arithmetic type T, there exist candidate
5275 // operator functions of the form
5276 //
5277 // T operator+(T);
5278 // T operator-(T);
5279 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005280 if (!HasArithmeticOrEnumeralCandidateType)
5281 return;
5282
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005283 for (unsigned Arith = FirstPromotedArithmeticType;
5284 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005285 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005286 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5287 }
5288
5289 // Extension: We also add these operators for vector types.
5290 for (BuiltinCandidateTypeSet::iterator
5291 Vec = CandidateTypes[0].vector_begin(),
5292 VecEnd = CandidateTypes[0].vector_end();
5293 Vec != VecEnd; ++Vec) {
5294 QualType VecTy = *Vec;
5295 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5296 }
5297 }
5298
5299 // C++ [over.built]p8:
5300 // For every type T, there exist candidate operator functions of
5301 // the form
5302 //
5303 // T* operator+(T*);
5304 void addUnaryPlusPointerOverloads() {
5305 for (BuiltinCandidateTypeSet::iterator
5306 Ptr = CandidateTypes[0].pointer_begin(),
5307 PtrEnd = CandidateTypes[0].pointer_end();
5308 Ptr != PtrEnd; ++Ptr) {
5309 QualType ParamTy = *Ptr;
5310 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5311 }
5312 }
5313
5314 // C++ [over.built]p10:
5315 // For every promoted integral type T, there exist candidate
5316 // operator functions of the form
5317 //
5318 // T operator~(T);
5319 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005320 if (!HasArithmeticOrEnumeralCandidateType)
5321 return;
5322
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005323 for (unsigned Int = FirstPromotedIntegralType;
5324 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005325 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005326 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5327 }
5328
5329 // Extension: We also add this operator for vector types.
5330 for (BuiltinCandidateTypeSet::iterator
5331 Vec = CandidateTypes[0].vector_begin(),
5332 VecEnd = CandidateTypes[0].vector_end();
5333 Vec != VecEnd; ++Vec) {
5334 QualType VecTy = *Vec;
5335 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5336 }
5337 }
5338
5339 // C++ [over.match.oper]p16:
5340 // For every pointer to member type T, there exist candidate operator
5341 // functions of the form
5342 //
5343 // bool operator==(T,T);
5344 // bool operator!=(T,T);
5345 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5346 /// Set of (canonical) types that we've already handled.
5347 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5348
5349 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5350 for (BuiltinCandidateTypeSet::iterator
5351 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5352 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5353 MemPtr != MemPtrEnd;
5354 ++MemPtr) {
5355 // Don't add the same builtin candidate twice.
5356 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5357 continue;
5358
5359 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5360 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5361 CandidateSet);
5362 }
5363 }
5364 }
5365
5366 // C++ [over.built]p15:
5367 //
5368 // For every pointer or enumeration type T, there exist
5369 // candidate operator functions of the form
5370 //
5371 // bool operator<(T, T);
5372 // bool operator>(T, T);
5373 // bool operator<=(T, T);
5374 // bool operator>=(T, T);
5375 // bool operator==(T, T);
5376 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005377 void addRelationalPointerOrEnumeralOverloads() {
5378 // C++ [over.built]p1:
5379 // If there is a user-written candidate with the same name and parameter
5380 // types as a built-in candidate operator function, the built-in operator
5381 // function is hidden and is not included in the set of candidate
5382 // functions.
5383 //
5384 // The text is actually in a note, but if we don't implement it then we end
5385 // up with ambiguities when the user provides an overloaded operator for
5386 // an enumeration type. Note that only enumeration types have this problem,
5387 // so we track which enumeration types we've seen operators for. Also, the
5388 // only other overloaded operator with enumeration argumenst, operator=,
5389 // cannot be overloaded for enumeration types, so this is the only place
5390 // where we must suppress candidates like this.
5391 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5392 UserDefinedBinaryOperators;
5393
5394 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5395 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5396 CandidateTypes[ArgIdx].enumeration_end()) {
5397 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5398 CEnd = CandidateSet.end();
5399 C != CEnd; ++C) {
5400 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5401 continue;
5402
5403 QualType FirstParamType =
5404 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5405 QualType SecondParamType =
5406 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5407
5408 // Skip if either parameter isn't of enumeral type.
5409 if (!FirstParamType->isEnumeralType() ||
5410 !SecondParamType->isEnumeralType())
5411 continue;
5412
5413 // Add this operator to the set of known user-defined operators.
5414 UserDefinedBinaryOperators.insert(
5415 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5416 S.Context.getCanonicalType(SecondParamType)));
5417 }
5418 }
5419 }
5420
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005421 /// Set of (canonical) types that we've already handled.
5422 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5423
5424 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5425 for (BuiltinCandidateTypeSet::iterator
5426 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5427 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5428 Ptr != PtrEnd; ++Ptr) {
5429 // Don't add the same builtin candidate twice.
5430 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5431 continue;
5432
5433 QualType ParamTypes[2] = { *Ptr, *Ptr };
5434 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5435 CandidateSet);
5436 }
5437 for (BuiltinCandidateTypeSet::iterator
5438 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5439 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5440 Enum != EnumEnd; ++Enum) {
5441 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5442
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005443 // Don't add the same builtin candidate twice, or if a user defined
5444 // candidate exists.
5445 if (!AddedTypes.insert(CanonType) ||
5446 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5447 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005448 continue;
5449
5450 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005451 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5452 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005453 }
5454 }
5455 }
5456
5457 // C++ [over.built]p13:
5458 //
5459 // For every cv-qualified or cv-unqualified object type T
5460 // there exist candidate operator functions of the form
5461 //
5462 // T* operator+(T*, ptrdiff_t);
5463 // T& operator[](T*, ptrdiff_t); [BELOW]
5464 // T* operator-(T*, ptrdiff_t);
5465 // T* operator+(ptrdiff_t, T*);
5466 // T& operator[](ptrdiff_t, T*); [BELOW]
5467 //
5468 // C++ [over.built]p14:
5469 //
5470 // For every T, where T is a pointer to object type, there
5471 // exist candidate operator functions of the form
5472 //
5473 // ptrdiff_t operator-(T, T);
5474 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5475 /// Set of (canonical) types that we've already handled.
5476 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5477
5478 for (int Arg = 0; Arg < 2; ++Arg) {
5479 QualType AsymetricParamTypes[2] = {
5480 S.Context.getPointerDiffType(),
5481 S.Context.getPointerDiffType(),
5482 };
5483 for (BuiltinCandidateTypeSet::iterator
5484 Ptr = CandidateTypes[Arg].pointer_begin(),
5485 PtrEnd = CandidateTypes[Arg].pointer_end();
5486 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005487 QualType PointeeTy = (*Ptr)->getPointeeType();
5488 if (!PointeeTy->isObjectType())
5489 continue;
5490
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005491 AsymetricParamTypes[Arg] = *Ptr;
5492 if (Arg == 0 || Op == OO_Plus) {
5493 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5494 // T* operator+(ptrdiff_t, T*);
5495 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5496 CandidateSet);
5497 }
5498 if (Op == OO_Minus) {
5499 // ptrdiff_t operator-(T, T);
5500 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5501 continue;
5502
5503 QualType ParamTypes[2] = { *Ptr, *Ptr };
5504 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5505 Args, 2, CandidateSet);
5506 }
5507 }
5508 }
5509 }
5510
5511 // C++ [over.built]p12:
5512 //
5513 // For every pair of promoted arithmetic types L and R, there
5514 // exist candidate operator functions of the form
5515 //
5516 // LR operator*(L, R);
5517 // LR operator/(L, R);
5518 // LR operator+(L, R);
5519 // LR operator-(L, R);
5520 // bool operator<(L, R);
5521 // bool operator>(L, R);
5522 // bool operator<=(L, R);
5523 // bool operator>=(L, R);
5524 // bool operator==(L, R);
5525 // bool operator!=(L, R);
5526 //
5527 // where LR is the result of the usual arithmetic conversions
5528 // between types L and R.
5529 //
5530 // C++ [over.built]p24:
5531 //
5532 // For every pair of promoted arithmetic types L and R, there exist
5533 // candidate operator functions of the form
5534 //
5535 // LR operator?(bool, L, R);
5536 //
5537 // where LR is the result of the usual arithmetic conversions
5538 // between types L and R.
5539 // Our candidates ignore the first parameter.
5540 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005541 if (!HasArithmeticOrEnumeralCandidateType)
5542 return;
5543
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005544 for (unsigned Left = FirstPromotedArithmeticType;
5545 Left < LastPromotedArithmeticType; ++Left) {
5546 for (unsigned Right = FirstPromotedArithmeticType;
5547 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005548 QualType LandR[2] = { getArithmeticType(Left),
5549 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005550 QualType Result =
5551 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005552 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005553 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5554 }
5555 }
5556
5557 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5558 // conditional operator for vector types.
5559 for (BuiltinCandidateTypeSet::iterator
5560 Vec1 = CandidateTypes[0].vector_begin(),
5561 Vec1End = CandidateTypes[0].vector_end();
5562 Vec1 != Vec1End; ++Vec1) {
5563 for (BuiltinCandidateTypeSet::iterator
5564 Vec2 = CandidateTypes[1].vector_begin(),
5565 Vec2End = CandidateTypes[1].vector_end();
5566 Vec2 != Vec2End; ++Vec2) {
5567 QualType LandR[2] = { *Vec1, *Vec2 };
5568 QualType Result = S.Context.BoolTy;
5569 if (!isComparison) {
5570 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5571 Result = *Vec1;
5572 else
5573 Result = *Vec2;
5574 }
5575
5576 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5577 }
5578 }
5579 }
5580
5581 // C++ [over.built]p17:
5582 //
5583 // For every pair of promoted integral types L and R, there
5584 // exist candidate operator functions of the form
5585 //
5586 // LR operator%(L, R);
5587 // LR operator&(L, R);
5588 // LR operator^(L, R);
5589 // LR operator|(L, R);
5590 // L operator<<(L, R);
5591 // L operator>>(L, R);
5592 //
5593 // where LR is the result of the usual arithmetic conversions
5594 // between types L and R.
5595 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005596 if (!HasArithmeticOrEnumeralCandidateType)
5597 return;
5598
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005599 for (unsigned Left = FirstPromotedIntegralType;
5600 Left < LastPromotedIntegralType; ++Left) {
5601 for (unsigned Right = FirstPromotedIntegralType;
5602 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005603 QualType LandR[2] = { getArithmeticType(Left),
5604 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005605 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5606 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005607 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005608 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5609 }
5610 }
5611 }
5612
5613 // C++ [over.built]p20:
5614 //
5615 // For every pair (T, VQ), where T is an enumeration or
5616 // pointer to member type and VQ is either volatile or
5617 // empty, there exist candidate operator functions of the form
5618 //
5619 // VQ T& operator=(VQ T&, T);
5620 void addAssignmentMemberPointerOrEnumeralOverloads() {
5621 /// Set of (canonical) types that we've already handled.
5622 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5623
5624 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5625 for (BuiltinCandidateTypeSet::iterator
5626 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5627 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5628 Enum != EnumEnd; ++Enum) {
5629 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5630 continue;
5631
5632 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5633 CandidateSet);
5634 }
5635
5636 for (BuiltinCandidateTypeSet::iterator
5637 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5638 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5639 MemPtr != MemPtrEnd; ++MemPtr) {
5640 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5641 continue;
5642
5643 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5644 CandidateSet);
5645 }
5646 }
5647 }
5648
5649 // C++ [over.built]p19:
5650 //
5651 // For every pair (T, VQ), where T is any type and VQ is either
5652 // volatile or empty, there exist candidate operator functions
5653 // of the form
5654 //
5655 // T*VQ& operator=(T*VQ&, T*);
5656 //
5657 // C++ [over.built]p21:
5658 //
5659 // For every pair (T, VQ), where T is a cv-qualified or
5660 // cv-unqualified object type and VQ is either volatile or
5661 // empty, there exist candidate operator functions of the form
5662 //
5663 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5664 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5665 void addAssignmentPointerOverloads(bool isEqualOp) {
5666 /// Set of (canonical) types that we've already handled.
5667 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5668
5669 for (BuiltinCandidateTypeSet::iterator
5670 Ptr = CandidateTypes[0].pointer_begin(),
5671 PtrEnd = CandidateTypes[0].pointer_end();
5672 Ptr != PtrEnd; ++Ptr) {
5673 // If this is operator=, keep track of the builtin candidates we added.
5674 if (isEqualOp)
5675 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005676 else if (!(*Ptr)->getPointeeType()->isObjectType())
5677 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005678
5679 // non-volatile version
5680 QualType ParamTypes[2] = {
5681 S.Context.getLValueReferenceType(*Ptr),
5682 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5683 };
5684 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5685 /*IsAssigmentOperator=*/ isEqualOp);
5686
5687 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5688 VisibleTypeConversionsQuals.hasVolatile()) {
5689 // volatile version
5690 ParamTypes[0] =
5691 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5692 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5693 /*IsAssigmentOperator=*/isEqualOp);
5694 }
5695 }
5696
5697 if (isEqualOp) {
5698 for (BuiltinCandidateTypeSet::iterator
5699 Ptr = CandidateTypes[1].pointer_begin(),
5700 PtrEnd = CandidateTypes[1].pointer_end();
5701 Ptr != PtrEnd; ++Ptr) {
5702 // Make sure we don't add the same candidate twice.
5703 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5704 continue;
5705
Chandler Carruth8e543b32010-12-12 08:17:55 +00005706 QualType ParamTypes[2] = {
5707 S.Context.getLValueReferenceType(*Ptr),
5708 *Ptr,
5709 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005710
5711 // non-volatile version
5712 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5713 /*IsAssigmentOperator=*/true);
5714
5715 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5716 VisibleTypeConversionsQuals.hasVolatile()) {
5717 // volatile version
5718 ParamTypes[0] =
5719 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005720 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5721 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005722 }
5723 }
5724 }
5725 }
5726
5727 // C++ [over.built]p18:
5728 //
5729 // For every triple (L, VQ, R), where L is an arithmetic type,
5730 // VQ is either volatile or empty, and R is a promoted
5731 // arithmetic type, there exist candidate operator functions of
5732 // the form
5733 //
5734 // VQ L& operator=(VQ L&, R);
5735 // VQ L& operator*=(VQ L&, R);
5736 // VQ L& operator/=(VQ L&, R);
5737 // VQ L& operator+=(VQ L&, R);
5738 // VQ L& operator-=(VQ L&, R);
5739 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005740 if (!HasArithmeticOrEnumeralCandidateType)
5741 return;
5742
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005743 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5744 for (unsigned Right = FirstPromotedArithmeticType;
5745 Right < LastPromotedArithmeticType; ++Right) {
5746 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005747 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005748
5749 // Add this built-in operator as a candidate (VQ is empty).
5750 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005751 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005752 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5753 /*IsAssigmentOperator=*/isEqualOp);
5754
5755 // Add this built-in operator as a candidate (VQ is 'volatile').
5756 if (VisibleTypeConversionsQuals.hasVolatile()) {
5757 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005758 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005759 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005760 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5761 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005762 /*IsAssigmentOperator=*/isEqualOp);
5763 }
5764 }
5765 }
5766
5767 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5768 for (BuiltinCandidateTypeSet::iterator
5769 Vec1 = CandidateTypes[0].vector_begin(),
5770 Vec1End = CandidateTypes[0].vector_end();
5771 Vec1 != Vec1End; ++Vec1) {
5772 for (BuiltinCandidateTypeSet::iterator
5773 Vec2 = CandidateTypes[1].vector_begin(),
5774 Vec2End = CandidateTypes[1].vector_end();
5775 Vec2 != Vec2End; ++Vec2) {
5776 QualType ParamTypes[2];
5777 ParamTypes[1] = *Vec2;
5778 // Add this built-in operator as a candidate (VQ is empty).
5779 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5780 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5781 /*IsAssigmentOperator=*/isEqualOp);
5782
5783 // Add this built-in operator as a candidate (VQ is 'volatile').
5784 if (VisibleTypeConversionsQuals.hasVolatile()) {
5785 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5786 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005787 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5788 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005789 /*IsAssigmentOperator=*/isEqualOp);
5790 }
5791 }
5792 }
5793 }
5794
5795 // C++ [over.built]p22:
5796 //
5797 // For every triple (L, VQ, R), where L is an integral type, VQ
5798 // is either volatile or empty, and R is a promoted integral
5799 // type, there exist candidate operator functions of the form
5800 //
5801 // VQ L& operator%=(VQ L&, R);
5802 // VQ L& operator<<=(VQ L&, R);
5803 // VQ L& operator>>=(VQ L&, R);
5804 // VQ L& operator&=(VQ L&, R);
5805 // VQ L& operator^=(VQ L&, R);
5806 // VQ L& operator|=(VQ L&, R);
5807 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005808 if (!HasArithmeticOrEnumeralCandidateType)
5809 return;
5810
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005811 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5812 for (unsigned Right = FirstPromotedIntegralType;
5813 Right < LastPromotedIntegralType; ++Right) {
5814 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005815 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005816
5817 // Add this built-in operator as a candidate (VQ is empty).
5818 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005819 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005820 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5821 if (VisibleTypeConversionsQuals.hasVolatile()) {
5822 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005823 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005824 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5825 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5826 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5827 CandidateSet);
5828 }
5829 }
5830 }
5831 }
5832
5833 // C++ [over.operator]p23:
5834 //
5835 // There also exist candidate operator functions of the form
5836 //
5837 // bool operator!(bool);
5838 // bool operator&&(bool, bool);
5839 // bool operator||(bool, bool);
5840 void addExclaimOverload() {
5841 QualType ParamTy = S.Context.BoolTy;
5842 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5843 /*IsAssignmentOperator=*/false,
5844 /*NumContextualBoolArguments=*/1);
5845 }
5846 void addAmpAmpOrPipePipeOverload() {
5847 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5848 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5849 /*IsAssignmentOperator=*/false,
5850 /*NumContextualBoolArguments=*/2);
5851 }
5852
5853 // C++ [over.built]p13:
5854 //
5855 // For every cv-qualified or cv-unqualified object type T there
5856 // exist candidate operator functions of the form
5857 //
5858 // T* operator+(T*, ptrdiff_t); [ABOVE]
5859 // T& operator[](T*, ptrdiff_t);
5860 // T* operator-(T*, ptrdiff_t); [ABOVE]
5861 // T* operator+(ptrdiff_t, T*); [ABOVE]
5862 // T& operator[](ptrdiff_t, T*);
5863 void addSubscriptOverloads() {
5864 for (BuiltinCandidateTypeSet::iterator
5865 Ptr = CandidateTypes[0].pointer_begin(),
5866 PtrEnd = CandidateTypes[0].pointer_end();
5867 Ptr != PtrEnd; ++Ptr) {
5868 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5869 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005870 if (!PointeeType->isObjectType())
5871 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005872
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005873 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5874
5875 // T& operator[](T*, ptrdiff_t)
5876 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5877 }
5878
5879 for (BuiltinCandidateTypeSet::iterator
5880 Ptr = CandidateTypes[1].pointer_begin(),
5881 PtrEnd = CandidateTypes[1].pointer_end();
5882 Ptr != PtrEnd; ++Ptr) {
5883 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5884 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005885 if (!PointeeType->isObjectType())
5886 continue;
5887
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005888 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5889
5890 // T& operator[](ptrdiff_t, T*)
5891 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5892 }
5893 }
5894
5895 // C++ [over.built]p11:
5896 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5897 // C1 is the same type as C2 or is a derived class of C2, T is an object
5898 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5899 // there exist candidate operator functions of the form
5900 //
5901 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5902 //
5903 // where CV12 is the union of CV1 and CV2.
5904 void addArrowStarOverloads() {
5905 for (BuiltinCandidateTypeSet::iterator
5906 Ptr = CandidateTypes[0].pointer_begin(),
5907 PtrEnd = CandidateTypes[0].pointer_end();
5908 Ptr != PtrEnd; ++Ptr) {
5909 QualType C1Ty = (*Ptr);
5910 QualType C1;
5911 QualifierCollector Q1;
5912 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5913 if (!isa<RecordType>(C1))
5914 continue;
5915 // heuristic to reduce number of builtin candidates in the set.
5916 // Add volatile/restrict version only if there are conversions to a
5917 // volatile/restrict type.
5918 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5919 continue;
5920 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5921 continue;
5922 for (BuiltinCandidateTypeSet::iterator
5923 MemPtr = CandidateTypes[1].member_pointer_begin(),
5924 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5925 MemPtr != MemPtrEnd; ++MemPtr) {
5926 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5927 QualType C2 = QualType(mptr->getClass(), 0);
5928 C2 = C2.getUnqualifiedType();
5929 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5930 break;
5931 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5932 // build CV12 T&
5933 QualType T = mptr->getPointeeType();
5934 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5935 T.isVolatileQualified())
5936 continue;
5937 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5938 T.isRestrictQualified())
5939 continue;
5940 T = Q1.apply(S.Context, T);
5941 QualType ResultTy = S.Context.getLValueReferenceType(T);
5942 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5943 }
5944 }
5945 }
5946
5947 // Note that we don't consider the first argument, since it has been
5948 // contextually converted to bool long ago. The candidates below are
5949 // therefore added as binary.
5950 //
5951 // C++ [over.built]p25:
5952 // For every type T, where T is a pointer, pointer-to-member, or scoped
5953 // enumeration type, there exist candidate operator functions of the form
5954 //
5955 // T operator?(bool, T, T);
5956 //
5957 void addConditionalOperatorOverloads() {
5958 /// Set of (canonical) types that we've already handled.
5959 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5960
5961 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5962 for (BuiltinCandidateTypeSet::iterator
5963 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5964 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5965 Ptr != PtrEnd; ++Ptr) {
5966 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5967 continue;
5968
5969 QualType ParamTypes[2] = { *Ptr, *Ptr };
5970 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5971 }
5972
5973 for (BuiltinCandidateTypeSet::iterator
5974 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5975 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5976 MemPtr != MemPtrEnd; ++MemPtr) {
5977 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5978 continue;
5979
5980 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5981 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5982 }
5983
5984 if (S.getLangOptions().CPlusPlus0x) {
5985 for (BuiltinCandidateTypeSet::iterator
5986 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5987 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5988 Enum != EnumEnd; ++Enum) {
5989 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5990 continue;
5991
5992 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5993 continue;
5994
5995 QualType ParamTypes[2] = { *Enum, *Enum };
5996 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5997 }
5998 }
5999 }
6000 }
6001};
6002
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006003} // end anonymous namespace
6004
6005/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6006/// operator overloads to the candidate set (C++ [over.built]), based
6007/// on the operator @p Op and the arguments given. For example, if the
6008/// operator is a binary '+', this routine might add "int
6009/// operator+(int, int)" to cover integer addition.
6010void
6011Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6012 SourceLocation OpLoc,
6013 Expr **Args, unsigned NumArgs,
6014 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006015 // Find all of the types that the arguments can convert to, but only
6016 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006017 // that make use of these types. Also record whether we encounter non-record
6018 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006019 Qualifiers VisibleTypeConversionsQuals;
6020 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006021 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6022 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006023
6024 bool HasNonRecordCandidateType = false;
6025 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006026 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
6027 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6028 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6029 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6030 OpLoc,
6031 true,
6032 (Op == OO_Exclaim ||
6033 Op == OO_AmpAmp ||
6034 Op == OO_PipePipe),
6035 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006036 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6037 CandidateTypes[ArgIdx].hasNonRecordTypes();
6038 HasArithmeticOrEnumeralCandidateType =
6039 HasArithmeticOrEnumeralCandidateType ||
6040 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006041 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006042
Chandler Carruth00a38332010-12-13 01:44:01 +00006043 // Exit early when no non-record types have been added to the candidate set
6044 // for any of the arguments to the operator.
6045 if (!HasNonRecordCandidateType)
6046 return;
6047
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006048 // Setup an object to manage the common state for building overloads.
6049 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6050 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006051 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006052 CandidateTypes, CandidateSet);
6053
6054 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006055 switch (Op) {
6056 case OO_None:
6057 case NUM_OVERLOADED_OPERATORS:
6058 assert(false && "Expected an overloaded operator");
6059 break;
6060
Chandler Carruth5184de02010-12-12 08:51:33 +00006061 case OO_New:
6062 case OO_Delete:
6063 case OO_Array_New:
6064 case OO_Array_Delete:
6065 case OO_Call:
6066 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6067 break;
6068
6069 case OO_Comma:
6070 case OO_Arrow:
6071 // C++ [over.match.oper]p3:
6072 // -- For the operator ',', the unary operator '&', or the
6073 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006074 break;
6075
6076 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006077 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006078 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006079 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006080
6081 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006082 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006083 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006084 } else {
6085 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6086 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6087 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006088 break;
6089
Chandler Carruth5184de02010-12-12 08:51:33 +00006090 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006091 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006092 OpBuilder.addUnaryStarPointerOverloads();
6093 else
6094 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6095 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006096
Chandler Carruth5184de02010-12-12 08:51:33 +00006097 case OO_Slash:
6098 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006099 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006100
6101 case OO_PlusPlus:
6102 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006103 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6104 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006105 break;
6106
Douglas Gregor84605ae2009-08-24 13:43:27 +00006107 case OO_EqualEqual:
6108 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006109 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006110 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006111
Douglas Gregora11693b2008-11-12 17:17:38 +00006112 case OO_Less:
6113 case OO_Greater:
6114 case OO_LessEqual:
6115 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006116 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006117 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6118 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006119
Douglas Gregora11693b2008-11-12 17:17:38 +00006120 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006121 case OO_Caret:
6122 case OO_Pipe:
6123 case OO_LessLess:
6124 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006125 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006126 break;
6127
Chandler Carruth5184de02010-12-12 08:51:33 +00006128 case OO_Amp: // '&' is either unary or binary
6129 if (NumArgs == 1)
6130 // C++ [over.match.oper]p3:
6131 // -- For the operator ',', the unary operator '&', or the
6132 // operator '->', the built-in candidates set is empty.
6133 break;
6134
6135 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6136 break;
6137
6138 case OO_Tilde:
6139 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6140 break;
6141
Douglas Gregora11693b2008-11-12 17:17:38 +00006142 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006143 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006144 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006145
6146 case OO_PlusEqual:
6147 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006148 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006149 // Fall through.
6150
6151 case OO_StarEqual:
6152 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006153 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006154 break;
6155
6156 case OO_PercentEqual:
6157 case OO_LessLessEqual:
6158 case OO_GreaterGreaterEqual:
6159 case OO_AmpEqual:
6160 case OO_CaretEqual:
6161 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006162 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006163 break;
6164
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006165 case OO_Exclaim:
6166 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006167 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006168
Douglas Gregora11693b2008-11-12 17:17:38 +00006169 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006170 case OO_PipePipe:
6171 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006172 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006173
6174 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006175 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006176 break;
6177
6178 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006179 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006180 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006181
6182 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006183 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006184 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6185 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006186 }
6187}
6188
Douglas Gregore254f902009-02-04 00:32:51 +00006189/// \brief Add function candidates found via argument-dependent lookup
6190/// to the set of overloading candidates.
6191///
6192/// This routine performs argument-dependent name lookup based on the
6193/// given function name (which may also be an operator name) and adds
6194/// all of the overload candidates found by ADL to the overload
6195/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006196void
Douglas Gregore254f902009-02-04 00:32:51 +00006197Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006198 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006199 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006200 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006201 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006202 bool PartialOverloading,
6203 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006204 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006205
John McCall91f61fc2010-01-26 06:04:06 +00006206 // FIXME: This approach for uniquing ADL results (and removing
6207 // redundant candidates from the set) relies on pointer-equality,
6208 // which means we need to key off the canonical decl. However,
6209 // always going back to the canonical decl might not get us the
6210 // right set of default arguments. What default arguments are
6211 // we supposed to consider on ADL candidates, anyway?
6212
Douglas Gregorcabea402009-09-22 15:41:20 +00006213 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006214 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6215 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006216
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006217 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006218 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6219 CandEnd = CandidateSet.end();
6220 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006221 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006222 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006223 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006224 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006225 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006226
6227 // For each of the ADL candidates we found, add it to the overload
6228 // set.
John McCall8fe68082010-01-26 07:16:45 +00006229 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006230 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006231 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006232 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006233 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006234
John McCalla0296f72010-03-19 07:35:19 +00006235 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006236 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006237 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006238 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006239 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006240 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006241 }
Douglas Gregore254f902009-02-04 00:32:51 +00006242}
6243
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006244/// isBetterOverloadCandidate - Determines whether the first overload
6245/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006246bool
John McCall5c32be02010-08-24 20:38:10 +00006247isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006248 const OverloadCandidate &Cand1,
6249 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006250 SourceLocation Loc,
6251 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006252 // Define viable functions to be better candidates than non-viable
6253 // functions.
6254 if (!Cand2.Viable)
6255 return Cand1.Viable;
6256 else if (!Cand1.Viable)
6257 return false;
6258
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006259 // C++ [over.match.best]p1:
6260 //
6261 // -- if F is a static member function, ICS1(F) is defined such
6262 // that ICS1(F) is neither better nor worse than ICS1(G) for
6263 // any function G, and, symmetrically, ICS1(G) is neither
6264 // better nor worse than ICS1(F).
6265 unsigned StartArg = 0;
6266 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6267 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006268
Douglas Gregord3cb3562009-07-07 23:38:56 +00006269 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006270 // A viable function F1 is defined to be a better function than another
6271 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006272 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006273 unsigned NumArgs = Cand1.Conversions.size();
6274 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6275 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006276 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006277 switch (CompareImplicitConversionSequences(S,
6278 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006279 Cand2.Conversions[ArgIdx])) {
6280 case ImplicitConversionSequence::Better:
6281 // Cand1 has a better conversion sequence.
6282 HasBetterConversion = true;
6283 break;
6284
6285 case ImplicitConversionSequence::Worse:
6286 // Cand1 can't be better than Cand2.
6287 return false;
6288
6289 case ImplicitConversionSequence::Indistinguishable:
6290 // Do nothing.
6291 break;
6292 }
6293 }
6294
Mike Stump11289f42009-09-09 15:08:12 +00006295 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006296 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006297 if (HasBetterConversion)
6298 return true;
6299
Mike Stump11289f42009-09-09 15:08:12 +00006300 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006301 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006302 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006303 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6304 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006305
6306 // -- F1 and F2 are function template specializations, and the function
6307 // template for F1 is more specialized than the template for F2
6308 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006309 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006310 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006311 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006312 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006313 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6314 Cand2.Function->getPrimaryTemplate(),
6315 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006316 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006317 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006318 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006319 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006321
Douglas Gregora1f013e2008-11-07 22:36:19 +00006322 // -- the context is an initialization by user-defined conversion
6323 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6324 // from the return type of F1 to the destination type (i.e.,
6325 // the type of the entity being initialized) is a better
6326 // conversion sequence than the standard conversion sequence
6327 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006328 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006329 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006330 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006331 switch (CompareStandardConversionSequences(S,
6332 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006333 Cand2.FinalConversion)) {
6334 case ImplicitConversionSequence::Better:
6335 // Cand1 has a better conversion sequence.
6336 return true;
6337
6338 case ImplicitConversionSequence::Worse:
6339 // Cand1 can't be better than Cand2.
6340 return false;
6341
6342 case ImplicitConversionSequence::Indistinguishable:
6343 // Do nothing
6344 break;
6345 }
6346 }
6347
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006348 return false;
6349}
6350
Mike Stump11289f42009-09-09 15:08:12 +00006351/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006352/// within an overload candidate set.
6353///
6354/// \param CandidateSet the set of candidate functions.
6355///
6356/// \param Loc the location of the function name (or operator symbol) for
6357/// which overload resolution occurs.
6358///
Mike Stump11289f42009-09-09 15:08:12 +00006359/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006360/// function, Best points to the candidate function found.
6361///
6362/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006363OverloadingResult
6364OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006365 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006366 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006367 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006368 Best = end();
6369 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6370 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006371 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006372 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006373 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006374 }
6375
6376 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006377 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006378 return OR_No_Viable_Function;
6379
6380 // Make sure that this function is better than every other viable
6381 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006382 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006383 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006384 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006385 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006386 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006387 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006388 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006389 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006390 }
Mike Stump11289f42009-09-09 15:08:12 +00006391
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006392 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006393 if (Best->Function &&
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006394 (Best->Function->isDeleted() || Best->Function->isUnavailable()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006395 return OR_Deleted;
6396
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006397 return OR_Success;
6398}
6399
John McCall53262c92010-01-12 02:15:36 +00006400namespace {
6401
6402enum OverloadCandidateKind {
6403 oc_function,
6404 oc_method,
6405 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006406 oc_function_template,
6407 oc_method_template,
6408 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006409 oc_implicit_default_constructor,
6410 oc_implicit_copy_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006411 oc_implicit_copy_assignment,
6412 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006413};
6414
John McCalle1ac8d12010-01-13 00:25:19 +00006415OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6416 FunctionDecl *Fn,
6417 std::string &Description) {
6418 bool isTemplate = false;
6419
6420 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6421 isTemplate = true;
6422 Description = S.getTemplateArgumentBindingsText(
6423 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6424 }
John McCallfd0b2f82010-01-06 09:43:14 +00006425
6426 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006427 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006428 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006429
Sebastian Redl08905022011-02-05 19:23:19 +00006430 if (Ctor->getInheritedConstructor())
6431 return oc_implicit_inherited_constructor;
6432
John McCall53262c92010-01-12 02:15:36 +00006433 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6434 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006435 }
6436
6437 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6438 // This actually gets spelled 'candidate function' for now, but
6439 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006440 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006441 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006442
Douglas Gregorec3bec02010-09-27 22:37:28 +00006443 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006444 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006445 return oc_implicit_copy_assignment;
6446 }
6447
John McCalle1ac8d12010-01-13 00:25:19 +00006448 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006449}
6450
Sebastian Redl08905022011-02-05 19:23:19 +00006451void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6452 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6453 if (!Ctor) return;
6454
6455 Ctor = Ctor->getInheritedConstructor();
6456 if (!Ctor) return;
6457
6458 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6459}
6460
John McCall53262c92010-01-12 02:15:36 +00006461} // end anonymous namespace
6462
6463// Notes the location of an overload candidate.
6464void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006465 std::string FnDesc;
6466 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6467 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6468 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006469 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006470}
6471
Douglas Gregorb491ed32011-02-19 21:32:49 +00006472//Notes the location of all overload candidates designated through
6473// OverloadedExpr
6474void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6475 assert(OverloadedExpr->getType() == Context.OverloadTy);
6476
6477 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6478 OverloadExpr *OvlExpr = Ovl.Expression;
6479
6480 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6481 IEnd = OvlExpr->decls_end();
6482 I != IEnd; ++I) {
6483 if (FunctionTemplateDecl *FunTmpl =
6484 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6485 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6486 } else if (FunctionDecl *Fun
6487 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6488 NoteOverloadCandidate(Fun);
6489 }
6490 }
6491}
6492
John McCall0d1da222010-01-12 00:44:57 +00006493/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6494/// "lead" diagnostic; it will be given two arguments, the source and
6495/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006496void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6497 Sema &S,
6498 SourceLocation CaretLoc,
6499 const PartialDiagnostic &PDiag) const {
6500 S.Diag(CaretLoc, PDiag)
6501 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006502 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006503 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6504 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006505 }
John McCall12f97bc2010-01-08 04:41:39 +00006506}
6507
John McCall0d1da222010-01-12 00:44:57 +00006508namespace {
6509
John McCall6a61b522010-01-13 09:16:55 +00006510void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6511 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6512 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006513 assert(Cand->Function && "for now, candidate must be a function");
6514 FunctionDecl *Fn = Cand->Function;
6515
6516 // There's a conversion slot for the object argument if this is a
6517 // non-constructor method. Note that 'I' corresponds the
6518 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006519 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006520 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006521 if (I == 0)
6522 isObjectArgument = true;
6523 else
6524 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006525 }
6526
John McCalle1ac8d12010-01-13 00:25:19 +00006527 std::string FnDesc;
6528 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6529
John McCall6a61b522010-01-13 09:16:55 +00006530 Expr *FromExpr = Conv.Bad.FromExpr;
6531 QualType FromTy = Conv.Bad.getFromType();
6532 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006533
John McCallfb7ad0f2010-02-02 02:42:52 +00006534 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006535 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006536 Expr *E = FromExpr->IgnoreParens();
6537 if (isa<UnaryOperator>(E))
6538 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006539 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006540
6541 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6542 << (unsigned) FnKind << FnDesc
6543 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6544 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006545 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006546 return;
6547 }
6548
John McCall6d174642010-01-23 08:10:49 +00006549 // Do some hand-waving analysis to see if the non-viability is due
6550 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006551 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6552 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6553 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6554 CToTy = RT->getPointeeType();
6555 else {
6556 // TODO: detect and diagnose the full richness of const mismatches.
6557 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6558 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6559 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6560 }
6561
6562 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6563 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6564 // It is dumb that we have to do this here.
6565 while (isa<ArrayType>(CFromTy))
6566 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6567 while (isa<ArrayType>(CToTy))
6568 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6569
6570 Qualifiers FromQs = CFromTy.getQualifiers();
6571 Qualifiers ToQs = CToTy.getQualifiers();
6572
6573 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6574 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6575 << (unsigned) FnKind << FnDesc
6576 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6577 << FromTy
6578 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6579 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006580 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006581 return;
6582 }
6583
Douglas Gregoraec25842011-04-26 23:16:46 +00006584 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6585 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6586 << (unsigned) FnKind << FnDesc
6587 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6588 << FromTy
6589 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6590 << (unsigned) isObjectArgument << I+1;
6591 MaybeEmitInheritedConstructorNote(S, Fn);
6592 return;
6593 }
6594
John McCall47000992010-01-14 03:28:57 +00006595 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6596 assert(CVR && "unexpected qualifiers mismatch");
6597
6598 if (isObjectArgument) {
6599 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6600 << (unsigned) FnKind << FnDesc
6601 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6602 << FromTy << (CVR - 1);
6603 } else {
6604 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6605 << (unsigned) FnKind << FnDesc
6606 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6607 << FromTy << (CVR - 1) << I+1;
6608 }
Sebastian Redl08905022011-02-05 19:23:19 +00006609 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006610 return;
6611 }
6612
John McCall6d174642010-01-23 08:10:49 +00006613 // Diagnose references or pointers to incomplete types differently,
6614 // since it's far from impossible that the incompleteness triggered
6615 // the failure.
6616 QualType TempFromTy = FromTy.getNonReferenceType();
6617 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6618 TempFromTy = PTy->getPointeeType();
6619 if (TempFromTy->isIncompleteType()) {
6620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6621 << (unsigned) FnKind << FnDesc
6622 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6623 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006624 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006625 return;
6626 }
6627
Douglas Gregor56f2e342010-06-30 23:01:39 +00006628 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006629 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006630 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6631 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6632 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6633 FromPtrTy->getPointeeType()) &&
6634 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6635 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006637 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006638 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006639 }
6640 } else if (const ObjCObjectPointerType *FromPtrTy
6641 = FromTy->getAs<ObjCObjectPointerType>()) {
6642 if (const ObjCObjectPointerType *ToPtrTy
6643 = ToTy->getAs<ObjCObjectPointerType>())
6644 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6645 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6646 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6647 FromPtrTy->getPointeeType()) &&
6648 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006649 BaseToDerivedConversion = 2;
6650 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6651 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6652 !FromTy->isIncompleteType() &&
6653 !ToRefTy->getPointeeType()->isIncompleteType() &&
6654 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6655 BaseToDerivedConversion = 3;
6656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006658 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006660 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006661 << (unsigned) FnKind << FnDesc
6662 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006663 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006665 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006666 return;
6667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006668
John McCall47000992010-01-14 03:28:57 +00006669 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006670 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6671 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006672 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006673 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006674 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006675}
6676
6677void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6678 unsigned NumFormalArgs) {
6679 // TODO: treat calls to a missing default constructor as a special case
6680
6681 FunctionDecl *Fn = Cand->Function;
6682 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6683
6684 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006685
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00006686 // With invalid overloaded operators, it's possible that we think we
6687 // have an arity mismatch when it fact it looks like we have the
6688 // right number of arguments, because only overloaded operators have
6689 // the weird behavior of overloading member and non-member functions.
6690 // Just don't report anything.
6691 if (Fn->isInvalidDecl() &&
6692 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6693 return;
6694
John McCall6a61b522010-01-13 09:16:55 +00006695 // at least / at most / exactly
6696 unsigned mode, modeCount;
6697 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006698 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6699 (Cand->FailureKind == ovl_fail_bad_deduction &&
6700 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006702 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006703 mode = 0; // "at least"
6704 else
6705 mode = 2; // "exactly"
6706 modeCount = MinParams;
6707 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006708 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6709 (Cand->FailureKind == ovl_fail_bad_deduction &&
6710 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006711 if (MinParams != FnTy->getNumArgs())
6712 mode = 1; // "at most"
6713 else
6714 mode = 2; // "exactly"
6715 modeCount = FnTy->getNumArgs();
6716 }
6717
6718 std::string Description;
6719 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6720
6721 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006722 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006723 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006724 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006725}
6726
John McCall8b9ed552010-02-01 18:53:26 +00006727/// Diagnose a failed template-argument deduction.
6728void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6729 Expr **Args, unsigned NumArgs) {
6730 FunctionDecl *Fn = Cand->Function; // pattern
6731
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006732 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006733 NamedDecl *ParamD;
6734 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6735 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6736 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006737 switch (Cand->DeductionFailure.Result) {
6738 case Sema::TDK_Success:
6739 llvm_unreachable("TDK_success while diagnosing bad deduction");
6740
6741 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006742 assert(ParamD && "no parameter found for incomplete deduction result");
6743 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6744 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006745 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006746 return;
6747 }
6748
John McCall42d7d192010-08-05 09:05:08 +00006749 case Sema::TDK_Underqualified: {
6750 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6751 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6752
6753 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6754
6755 // Param will have been canonicalized, but it should just be a
6756 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006757 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006758 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006759 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006760 assert(S.Context.hasSameType(Param, NonCanonParam));
6761
6762 // Arg has also been canonicalized, but there's nothing we can do
6763 // about that. It also doesn't matter as much, because it won't
6764 // have any template parameters in it (because deduction isn't
6765 // done on dependent types).
6766 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6767
6768 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6769 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00006770 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00006771 return;
6772 }
6773
6774 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006775 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006776 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006777 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006778 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006779 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006780 which = 1;
6781 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006782 which = 2;
6783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006784
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006785 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006786 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006787 << *Cand->DeductionFailure.getFirstArg()
6788 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00006789 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006790 return;
6791 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006792
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006793 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006794 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006795 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006796 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006797 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6798 << ParamD->getDeclName();
6799 else {
6800 int index = 0;
6801 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6802 index = TTP->getIndex();
6803 else if (NonTypeTemplateParmDecl *NTTP
6804 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6805 index = NTTP->getIndex();
6806 else
6807 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006808 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006809 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6810 << (index + 1);
6811 }
Sebastian Redl08905022011-02-05 19:23:19 +00006812 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006813 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814
Douglas Gregor02eb4832010-05-08 18:13:28 +00006815 case Sema::TDK_TooManyArguments:
6816 case Sema::TDK_TooFewArguments:
6817 DiagnoseArityMismatch(S, Cand, NumArgs);
6818 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006819
6820 case Sema::TDK_InstantiationDepth:
6821 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00006822 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006823 return;
6824
6825 case Sema::TDK_SubstitutionFailure: {
6826 std::string ArgString;
6827 if (TemplateArgumentList *Args
6828 = Cand->DeductionFailure.getTemplateArgumentList())
6829 ArgString = S.getTemplateArgumentBindingsText(
6830 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6831 *Args);
6832 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6833 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00006834 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006835 return;
6836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006837
John McCall8b9ed552010-02-01 18:53:26 +00006838 // TODO: diagnose these individually, then kill off
6839 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006840 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006841 case Sema::TDK_FailedOverloadResolution:
6842 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00006843 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006844 return;
6845 }
6846}
6847
6848/// Generates a 'note' diagnostic for an overload candidate. We've
6849/// already generated a primary error at the call site.
6850///
6851/// It really does need to be a single diagnostic with its caret
6852/// pointed at the candidate declaration. Yes, this creates some
6853/// major challenges of technical writing. Yes, this makes pointing
6854/// out problems with specific arguments quite awkward. It's still
6855/// better than generating twenty screens of text for every failed
6856/// overload.
6857///
6858/// It would be great to be able to express per-candidate problems
6859/// more richly for those diagnostic clients that cared, but we'd
6860/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006861void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6862 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006863 FunctionDecl *Fn = Cand->Function;
6864
John McCall12f97bc2010-01-08 04:41:39 +00006865 // Note deleted candidates, but only if they're viable.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006866 if (Cand->Viable && (Fn->isDeleted() || Fn->isUnavailable())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006867 std::string FnDesc;
6868 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006869
6870 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006871 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00006872 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00006873 return;
John McCall12f97bc2010-01-08 04:41:39 +00006874 }
6875
John McCalle1ac8d12010-01-13 00:25:19 +00006876 // We don't really have anything else to say about viable candidates.
6877 if (Cand->Viable) {
6878 S.NoteOverloadCandidate(Fn);
6879 return;
6880 }
John McCall0d1da222010-01-12 00:44:57 +00006881
John McCall6a61b522010-01-13 09:16:55 +00006882 switch (Cand->FailureKind) {
6883 case ovl_fail_too_many_arguments:
6884 case ovl_fail_too_few_arguments:
6885 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006886
John McCall6a61b522010-01-13 09:16:55 +00006887 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006888 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6889
John McCallfe796dd2010-01-23 05:17:32 +00006890 case ovl_fail_trivial_conversion:
6891 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006892 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006893 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006894
John McCall65eb8792010-02-25 01:37:24 +00006895 case ovl_fail_bad_conversion: {
6896 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6897 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006898 if (Cand->Conversions[I].isBad())
6899 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900
John McCall6a61b522010-01-13 09:16:55 +00006901 // FIXME: this currently happens when we're called from SemaInit
6902 // when user-conversion overload fails. Figure out how to handle
6903 // those conditions and diagnose them well.
6904 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006905 }
John McCall65eb8792010-02-25 01:37:24 +00006906 }
John McCalld3224162010-01-08 00:58:21 +00006907}
6908
6909void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6910 // Desugar the type of the surrogate down to a function type,
6911 // retaining as many typedefs as possible while still showing
6912 // the function type (and, therefore, its parameter types).
6913 QualType FnType = Cand->Surrogate->getConversionType();
6914 bool isLValueReference = false;
6915 bool isRValueReference = false;
6916 bool isPointer = false;
6917 if (const LValueReferenceType *FnTypeRef =
6918 FnType->getAs<LValueReferenceType>()) {
6919 FnType = FnTypeRef->getPointeeType();
6920 isLValueReference = true;
6921 } else if (const RValueReferenceType *FnTypeRef =
6922 FnType->getAs<RValueReferenceType>()) {
6923 FnType = FnTypeRef->getPointeeType();
6924 isRValueReference = true;
6925 }
6926 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6927 FnType = FnTypePtr->getPointeeType();
6928 isPointer = true;
6929 }
6930 // Desugar down to a function type.
6931 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6932 // Reconstruct the pointer/reference as appropriate.
6933 if (isPointer) FnType = S.Context.getPointerType(FnType);
6934 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6935 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6936
6937 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6938 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00006939 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00006940}
6941
6942void NoteBuiltinOperatorCandidate(Sema &S,
6943 const char *Opc,
6944 SourceLocation OpLoc,
6945 OverloadCandidate *Cand) {
6946 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6947 std::string TypeStr("operator");
6948 TypeStr += Opc;
6949 TypeStr += "(";
6950 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6951 if (Cand->Conversions.size() == 1) {
6952 TypeStr += ")";
6953 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6954 } else {
6955 TypeStr += ", ";
6956 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6957 TypeStr += ")";
6958 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6959 }
6960}
6961
6962void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6963 OverloadCandidate *Cand) {
6964 unsigned NoOperands = Cand->Conversions.size();
6965 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6966 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006967 if (ICS.isBad()) break; // all meaningless after first invalid
6968 if (!ICS.isAmbiguous()) continue;
6969
John McCall5c32be02010-08-24 20:38:10 +00006970 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006971 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006972 }
6973}
6974
John McCall3712d9e2010-01-15 23:32:50 +00006975SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6976 if (Cand->Function)
6977 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006978 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006979 return Cand->Surrogate->getLocation();
6980 return SourceLocation();
6981}
6982
John McCallad2587a2010-01-12 00:48:53 +00006983struct CompareOverloadCandidatesForDisplay {
6984 Sema &S;
6985 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006986
6987 bool operator()(const OverloadCandidate *L,
6988 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006989 // Fast-path this check.
6990 if (L == R) return false;
6991
John McCall12f97bc2010-01-08 04:41:39 +00006992 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006993 if (L->Viable) {
6994 if (!R->Viable) return true;
6995
6996 // TODO: introduce a tri-valued comparison for overload
6997 // candidates. Would be more worthwhile if we had a sort
6998 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006999 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7000 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007001 } else if (R->Viable)
7002 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007003
John McCall3712d9e2010-01-15 23:32:50 +00007004 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007005
John McCall3712d9e2010-01-15 23:32:50 +00007006 // Criteria by which we can sort non-viable candidates:
7007 if (!L->Viable) {
7008 // 1. Arity mismatches come after other candidates.
7009 if (L->FailureKind == ovl_fail_too_many_arguments ||
7010 L->FailureKind == ovl_fail_too_few_arguments)
7011 return false;
7012 if (R->FailureKind == ovl_fail_too_many_arguments ||
7013 R->FailureKind == ovl_fail_too_few_arguments)
7014 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007015
John McCallfe796dd2010-01-23 05:17:32 +00007016 // 2. Bad conversions come first and are ordered by the number
7017 // of bad conversions and quality of good conversions.
7018 if (L->FailureKind == ovl_fail_bad_conversion) {
7019 if (R->FailureKind != ovl_fail_bad_conversion)
7020 return true;
7021
7022 // If there's any ordering between the defined conversions...
7023 // FIXME: this might not be transitive.
7024 assert(L->Conversions.size() == R->Conversions.size());
7025
7026 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007027 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7028 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007029 switch (CompareImplicitConversionSequences(S,
7030 L->Conversions[I],
7031 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007032 case ImplicitConversionSequence::Better:
7033 leftBetter++;
7034 break;
7035
7036 case ImplicitConversionSequence::Worse:
7037 leftBetter--;
7038 break;
7039
7040 case ImplicitConversionSequence::Indistinguishable:
7041 break;
7042 }
7043 }
7044 if (leftBetter > 0) return true;
7045 if (leftBetter < 0) return false;
7046
7047 } else if (R->FailureKind == ovl_fail_bad_conversion)
7048 return false;
7049
John McCall3712d9e2010-01-15 23:32:50 +00007050 // TODO: others?
7051 }
7052
7053 // Sort everything else by location.
7054 SourceLocation LLoc = GetLocationForCandidate(L);
7055 SourceLocation RLoc = GetLocationForCandidate(R);
7056
7057 // Put candidates without locations (e.g. builtins) at the end.
7058 if (LLoc.isInvalid()) return false;
7059 if (RLoc.isInvalid()) return true;
7060
7061 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007062 }
7063};
7064
John McCallfe796dd2010-01-23 05:17:32 +00007065/// CompleteNonViableCandidate - Normally, overload resolution only
7066/// computes up to the first
7067void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7068 Expr **Args, unsigned NumArgs) {
7069 assert(!Cand->Viable);
7070
7071 // Don't do anything on failures other than bad conversion.
7072 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7073
7074 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007075 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007076 unsigned ConvCount = Cand->Conversions.size();
7077 while (true) {
7078 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7079 ConvIdx++;
7080 if (Cand->Conversions[ConvIdx - 1].isBad())
7081 break;
7082 }
7083
7084 if (ConvIdx == ConvCount)
7085 return;
7086
John McCall65eb8792010-02-25 01:37:24 +00007087 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7088 "remaining conversion is initialized?");
7089
Douglas Gregoradc7a702010-04-16 17:45:54 +00007090 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007091 // operation somehow.
7092 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007093
7094 const FunctionProtoType* Proto;
7095 unsigned ArgIdx = ConvIdx;
7096
7097 if (Cand->IsSurrogate) {
7098 QualType ConvType
7099 = Cand->Surrogate->getConversionType().getNonReferenceType();
7100 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7101 ConvType = ConvPtrType->getPointeeType();
7102 Proto = ConvType->getAs<FunctionProtoType>();
7103 ArgIdx--;
7104 } else if (Cand->Function) {
7105 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7106 if (isa<CXXMethodDecl>(Cand->Function) &&
7107 !isa<CXXConstructorDecl>(Cand->Function))
7108 ArgIdx--;
7109 } else {
7110 // Builtin binary operator with a bad first conversion.
7111 assert(ConvCount <= 3);
7112 for (; ConvIdx != ConvCount; ++ConvIdx)
7113 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007114 = TryCopyInitialization(S, Args[ConvIdx],
7115 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007117 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00007118 return;
7119 }
7120
7121 // Fill in the rest of the conversions.
7122 unsigned NumArgsInProto = Proto->getNumArgs();
7123 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7124 if (ArgIdx < NumArgsInProto)
7125 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007126 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007127 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007128 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00007129 else
7130 Cand->Conversions[ConvIdx].setEllipsis();
7131 }
7132}
7133
John McCalld3224162010-01-08 00:58:21 +00007134} // end anonymous namespace
7135
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007136/// PrintOverloadCandidates - When overload resolution fails, prints
7137/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007138/// set.
John McCall5c32be02010-08-24 20:38:10 +00007139void OverloadCandidateSet::NoteCandidates(Sema &S,
7140 OverloadCandidateDisplayKind OCD,
7141 Expr **Args, unsigned NumArgs,
7142 const char *Opc,
7143 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007144 // Sort the candidates by viability and position. Sorting directly would
7145 // be prohibitive, so we make a set of pointers and sort those.
7146 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007147 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7148 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007149 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007150 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007151 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007152 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007153 if (Cand->Function || Cand->IsSurrogate)
7154 Cands.push_back(Cand);
7155 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7156 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007157 }
7158 }
7159
John McCallad2587a2010-01-12 00:48:53 +00007160 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007161 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007162
John McCall0d1da222010-01-12 00:44:57 +00007163 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007164
John McCall12f97bc2010-01-08 04:41:39 +00007165 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007166 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007167 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007168 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7169 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007170
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007171 // Set an arbitrary limit on the number of candidate functions we'll spam
7172 // the user with. FIXME: This limit should depend on details of the
7173 // candidate list.
7174 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7175 break;
7176 }
7177 ++CandsShown;
7178
John McCalld3224162010-01-08 00:58:21 +00007179 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007180 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007181 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007182 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007183 else {
7184 assert(Cand->Viable &&
7185 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007186 // Generally we only see ambiguities including viable builtin
7187 // operators if overload resolution got screwed up by an
7188 // ambiguous user-defined conversion.
7189 //
7190 // FIXME: It's quite possible for different conversions to see
7191 // different ambiguities, though.
7192 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007193 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007194 ReportedAmbiguousConversions = true;
7195 }
John McCalld3224162010-01-08 00:58:21 +00007196
John McCall0d1da222010-01-12 00:44:57 +00007197 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007198 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007199 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007200 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007201
7202 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007203 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007204}
7205
Douglas Gregorb491ed32011-02-19 21:32:49 +00007206// [PossiblyAFunctionType] --> [Return]
7207// NonFunctionType --> NonFunctionType
7208// R (A) --> R(A)
7209// R (*)(A) --> R (A)
7210// R (&)(A) --> R (A)
7211// R (S::*)(A) --> R (A)
7212QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7213 QualType Ret = PossiblyAFunctionType;
7214 if (const PointerType *ToTypePtr =
7215 PossiblyAFunctionType->getAs<PointerType>())
7216 Ret = ToTypePtr->getPointeeType();
7217 else if (const ReferenceType *ToTypeRef =
7218 PossiblyAFunctionType->getAs<ReferenceType>())
7219 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007220 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007221 PossiblyAFunctionType->getAs<MemberPointerType>())
7222 Ret = MemTypePtr->getPointeeType();
7223 Ret =
7224 Context.getCanonicalType(Ret).getUnqualifiedType();
7225 return Ret;
7226}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007227
Douglas Gregorb491ed32011-02-19 21:32:49 +00007228// A helper class to help with address of function resolution
7229// - allows us to avoid passing around all those ugly parameters
7230class AddressOfFunctionResolver
7231{
7232 Sema& S;
7233 Expr* SourceExpr;
7234 const QualType& TargetType;
7235 QualType TargetFunctionType; // Extracted function type from target type
7236
7237 bool Complain;
7238 //DeclAccessPair& ResultFunctionAccessPair;
7239 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007240
Douglas Gregorb491ed32011-02-19 21:32:49 +00007241 bool TargetTypeIsNonStaticMemberFunction;
7242 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007243
Douglas Gregorb491ed32011-02-19 21:32:49 +00007244 OverloadExpr::FindResult OvlExprInfo;
7245 OverloadExpr *OvlExpr;
7246 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007247 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007248
Douglas Gregorb491ed32011-02-19 21:32:49 +00007249public:
7250 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7251 const QualType& TargetType, bool Complain)
7252 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7253 Complain(Complain), Context(S.getASTContext()),
7254 TargetTypeIsNonStaticMemberFunction(
7255 !!TargetType->getAs<MemberPointerType>()),
7256 FoundNonTemplateFunction(false),
7257 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7258 OvlExpr(OvlExprInfo.Expression)
7259 {
7260 ExtractUnqualifiedFunctionTypeFromTargetType();
7261
7262 if (!TargetFunctionType->isFunctionType()) {
7263 if (OvlExpr->hasExplicitTemplateArgs()) {
7264 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007265 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007266 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007267
7268 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7269 if (!Method->isStatic()) {
7270 // If the target type is a non-function type and the function
7271 // found is a non-static member function, pretend as if that was
7272 // the target, it's the only possible type to end up with.
7273 TargetTypeIsNonStaticMemberFunction = true;
7274
7275 // And skip adding the function if its not in the proper form.
7276 // We'll diagnose this due to an empty set of functions.
7277 if (!OvlExprInfo.HasFormOfMemberPointer)
7278 return;
7279 }
7280 }
7281
Douglas Gregorb491ed32011-02-19 21:32:49 +00007282 Matches.push_back(std::make_pair(dap,Fn));
7283 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007284 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007285 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007286 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007287
7288 if (OvlExpr->hasExplicitTemplateArgs())
7289 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007290
Douglas Gregorb491ed32011-02-19 21:32:49 +00007291 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7292 // C++ [over.over]p4:
7293 // If more than one function is selected, [...]
7294 if (Matches.size() > 1) {
7295 if (FoundNonTemplateFunction)
7296 EliminateAllTemplateMatches();
7297 else
7298 EliminateAllExceptMostSpecializedTemplate();
7299 }
7300 }
7301 }
7302
7303private:
7304 bool isTargetTypeAFunction() const {
7305 return TargetFunctionType->isFunctionType();
7306 }
7307
7308 // [ToType] [Return]
7309
7310 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7311 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7312 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7313 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7314 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7315 }
7316
7317 // return true if any matching specializations were found
7318 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7319 const DeclAccessPair& CurAccessFunPair) {
7320 if (CXXMethodDecl *Method
7321 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7322 // Skip non-static function templates when converting to pointer, and
7323 // static when converting to member pointer.
7324 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7325 return false;
7326 }
7327 else if (TargetTypeIsNonStaticMemberFunction)
7328 return false;
7329
7330 // C++ [over.over]p2:
7331 // If the name is a function template, template argument deduction is
7332 // done (14.8.2.2), and if the argument deduction succeeds, the
7333 // resulting template argument list is used to generate a single
7334 // function template specialization, which is added to the set of
7335 // overloaded functions considered.
7336 FunctionDecl *Specialization = 0;
7337 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7338 if (Sema::TemplateDeductionResult Result
7339 = S.DeduceTemplateArguments(FunctionTemplate,
7340 &OvlExplicitTemplateArgs,
7341 TargetFunctionType, Specialization,
7342 Info)) {
7343 // FIXME: make a note of the failed deduction for diagnostics.
7344 (void)Result;
7345 return false;
7346 }
7347
7348 // Template argument deduction ensures that we have an exact match.
7349 // This function template specicalization works.
7350 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7351 assert(TargetFunctionType
7352 == Context.getCanonicalType(Specialization->getType()));
7353 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7354 return true;
7355 }
7356
7357 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7358 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007359 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007360 // Skip non-static functions when converting to pointer, and static
7361 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007362 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7363 return false;
7364 }
7365 else if (TargetTypeIsNonStaticMemberFunction)
7366 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007367
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007368 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007369 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007370 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7371 FunDecl->getType()) ||
7372 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007373 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007374 Matches.push_back(std::make_pair(CurAccessFunPair,
7375 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007376 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007377 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007378 }
Mike Stump11289f42009-09-09 15:08:12 +00007379 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007380
7381 return false;
7382 }
7383
7384 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7385 bool Ret = false;
7386
7387 // If the overload expression doesn't have the form of a pointer to
7388 // member, don't try to convert it to a pointer-to-member type.
7389 if (IsInvalidFormOfPointerToMemberFunction())
7390 return false;
7391
7392 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7393 E = OvlExpr->decls_end();
7394 I != E; ++I) {
7395 // Look through any using declarations to find the underlying function.
7396 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7397
7398 // C++ [over.over]p3:
7399 // Non-member functions and static member functions match
7400 // targets of type "pointer-to-function" or "reference-to-function."
7401 // Nonstatic member functions match targets of
7402 // type "pointer-to-member-function."
7403 // Note that according to DR 247, the containing class does not matter.
7404 if (FunctionTemplateDecl *FunctionTemplate
7405 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7406 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7407 Ret = true;
7408 }
7409 // If we have explicit template arguments supplied, skip non-templates.
7410 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7411 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7412 Ret = true;
7413 }
7414 assert(Ret || Matches.empty());
7415 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007416 }
7417
Douglas Gregorb491ed32011-02-19 21:32:49 +00007418 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007419 // [...] and any given function template specialization F1 is
7420 // eliminated if the set contains a second function template
7421 // specialization whose function template is more specialized
7422 // than the function template of F1 according to the partial
7423 // ordering rules of 14.5.5.2.
7424
7425 // The algorithm specified above is quadratic. We instead use a
7426 // two-pass algorithm (similar to the one used to identify the
7427 // best viable function in an overload set) that identifies the
7428 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007429
7430 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7431 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7432 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007433
John McCall58cc69d2010-01-27 01:50:18 +00007434 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007435 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7436 TPOC_Other, 0, SourceExpr->getLocStart(),
7437 S.PDiag(),
7438 S.PDiag(diag::err_addr_ovl_ambiguous)
7439 << Matches[0].second->getDeclName(),
7440 S.PDiag(diag::note_ovl_candidate)
7441 << (unsigned) oc_function_template,
7442 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007443
Douglas Gregorb491ed32011-02-19 21:32:49 +00007444 if (Result != MatchesCopy.end()) {
7445 // Make it the first and only element
7446 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7447 Matches[0].second = cast<FunctionDecl>(*Result);
7448 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007449 }
7450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007451
Douglas Gregorb491ed32011-02-19 21:32:49 +00007452 void EliminateAllTemplateMatches() {
7453 // [...] any function template specializations in the set are
7454 // eliminated if the set also contains a non-template function, [...]
7455 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7456 if (Matches[I].second->getPrimaryTemplate() == 0)
7457 ++I;
7458 else {
7459 Matches[I] = Matches[--N];
7460 Matches.set_size(N);
7461 }
7462 }
7463 }
7464
7465public:
7466 void ComplainNoMatchesFound() const {
7467 assert(Matches.empty());
7468 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7469 << OvlExpr->getName() << TargetFunctionType
7470 << OvlExpr->getSourceRange();
7471 S.NoteAllOverloadCandidates(OvlExpr);
7472 }
7473
7474 bool IsInvalidFormOfPointerToMemberFunction() const {
7475 return TargetTypeIsNonStaticMemberFunction &&
7476 !OvlExprInfo.HasFormOfMemberPointer;
7477 }
7478
7479 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7480 // TODO: Should we condition this on whether any functions might
7481 // have matched, or is it more appropriate to do that in callers?
7482 // TODO: a fixit wouldn't hurt.
7483 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7484 << TargetType << OvlExpr->getSourceRange();
7485 }
7486
7487 void ComplainOfInvalidConversion() const {
7488 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7489 << OvlExpr->getName() << TargetType;
7490 }
7491
7492 void ComplainMultipleMatchesFound() const {
7493 assert(Matches.size() > 1);
7494 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7495 << OvlExpr->getName()
7496 << OvlExpr->getSourceRange();
7497 S.NoteAllOverloadCandidates(OvlExpr);
7498 }
7499
7500 int getNumMatches() const { return Matches.size(); }
7501
7502 FunctionDecl* getMatchingFunctionDecl() const {
7503 if (Matches.size() != 1) return 0;
7504 return Matches[0].second;
7505 }
7506
7507 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7508 if (Matches.size() != 1) return 0;
7509 return &Matches[0].first;
7510 }
7511};
7512
7513/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7514/// an overloaded function (C++ [over.over]), where @p From is an
7515/// expression with overloaded function type and @p ToType is the type
7516/// we're trying to resolve to. For example:
7517///
7518/// @code
7519/// int f(double);
7520/// int f(int);
7521///
7522/// int (*pfd)(double) = f; // selects f(double)
7523/// @endcode
7524///
7525/// This routine returns the resulting FunctionDecl if it could be
7526/// resolved, and NULL otherwise. When @p Complain is true, this
7527/// routine will emit diagnostics if there is an error.
7528FunctionDecl *
7529Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7530 bool Complain,
7531 DeclAccessPair &FoundResult) {
7532
7533 assert(AddressOfExpr->getType() == Context.OverloadTy);
7534
7535 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7536 int NumMatches = Resolver.getNumMatches();
7537 FunctionDecl* Fn = 0;
7538 if ( NumMatches == 0 && Complain) {
7539 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7540 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7541 else
7542 Resolver.ComplainNoMatchesFound();
7543 }
7544 else if (NumMatches > 1 && Complain)
7545 Resolver.ComplainMultipleMatchesFound();
7546 else if (NumMatches == 1) {
7547 Fn = Resolver.getMatchingFunctionDecl();
7548 assert(Fn);
7549 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7550 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007551 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007552 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007553 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007554
7555 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007556}
7557
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007558/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007559/// resolve that overloaded function expression down to a single function.
7560///
7561/// This routine can only resolve template-ids that refer to a single function
7562/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007563/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007564/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00007565FunctionDecl *
7566Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7567 bool Complain,
7568 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007569 // C++ [over.over]p1:
7570 // [...] [Note: any redundant set of parentheses surrounding the
7571 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007572 // C++ [over.over]p1:
7573 // [...] The overloaded function name can be preceded by the &
7574 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007575
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007576 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00007577 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007578 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007579
7580 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00007581 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007582
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007583 // Look through all of the overloaded functions, searching for one
7584 // whose type matches exactly.
7585 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007586 for (UnresolvedSetIterator I = ovl->decls_begin(),
7587 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007588 // C++0x [temp.arg.explicit]p3:
7589 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007590 // where deduction is not done, if a template argument list is
7591 // specified and it, along with any default template arguments,
7592 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007593 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007594 FunctionTemplateDecl *FunctionTemplate
7595 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007596
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007597 // C++ [over.over]p2:
7598 // If the name is a function template, template argument deduction is
7599 // done (14.8.2.2), and if the argument deduction succeeds, the
7600 // resulting template argument list is used to generate a single
7601 // function template specialization, which is added to the set of
7602 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007603 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007604 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007605 if (TemplateDeductionResult Result
7606 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7607 Specialization, Info)) {
7608 // FIXME: make a note of the failed deduction for diagnostics.
7609 (void)Result;
7610 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007611 }
7612
John McCall0009fcc2011-04-26 20:42:42 +00007613 assert(Specialization && "no specialization and no error?");
7614
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007615 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007616 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007617 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00007618 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7619 << ovl->getName();
7620 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007621 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007622 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00007623 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007624
John McCall0009fcc2011-04-26 20:42:42 +00007625 Matched = Specialization;
7626 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007628
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007629 return Matched;
7630}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007631
Douglas Gregor1beec452011-03-12 01:48:56 +00007632
7633
7634
7635// Resolve and fix an overloaded expression that
7636// can be resolved because it identifies a single function
7637// template specialization
7638// Last three arguments should only be supplied if Complain = true
7639ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00007640 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00007641 const SourceRange& OpRangeForComplaining,
7642 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00007643 unsigned DiagIDForComplaining) {
7644 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00007645
John McCall0009fcc2011-04-26 20:42:42 +00007646 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00007647
John McCall0009fcc2011-04-26 20:42:42 +00007648 DeclAccessPair found;
7649 ExprResult SingleFunctionExpression;
7650 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7651 ovl.Expression, /*complain*/ false, &found)) {
7652 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7653 return ExprError();
7654
7655 // It is only correct to resolve to an instance method if we're
7656 // resolving a form that's permitted to be a pointer to member.
7657 // Otherwise we'll end up making a bound member expression, which
7658 // is illegal in all the contexts we resolve like this.
7659 if (!ovl.HasFormOfMemberPointer &&
7660 isa<CXXMethodDecl>(fn) &&
7661 cast<CXXMethodDecl>(fn)->isInstance()) {
7662 if (complain) {
7663 Diag(ovl.Expression->getExprLoc(),
7664 diag::err_invalid_use_of_bound_member_func)
7665 << ovl.Expression->getSourceRange();
7666 // TODO: I believe we only end up here if there's a mix of
7667 // static and non-static candidates (otherwise the expression
7668 // would have 'bound member' type, not 'overload' type).
7669 // Ideally we would note which candidate was chosen and why
7670 // the static candidates were rejected.
7671 }
7672
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007673 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00007674 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007675
John McCall0009fcc2011-04-26 20:42:42 +00007676 // Fix the expresion to refer to 'fn'.
7677 SingleFunctionExpression =
7678 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7679
7680 // If desired, do function-to-pointer decay.
7681 if (doFunctionPointerConverion)
7682 SingleFunctionExpression =
7683 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7684 }
7685
7686 if (!SingleFunctionExpression.isUsable()) {
7687 if (complain) {
7688 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7689 << ovl.Expression->getName()
7690 << DestTypeForComplaining
7691 << OpRangeForComplaining
7692 << ovl.Expression->getQualifierLoc().getSourceRange();
7693 NoteAllOverloadCandidates(SrcExpr);
7694 }
7695 return ExprError();
7696 }
7697
7698 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00007699}
7700
Douglas Gregorcabea402009-09-22 15:41:20 +00007701/// \brief Add a single candidate to the overload set.
7702static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007703 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007704 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007705 Expr **Args, unsigned NumArgs,
7706 OverloadCandidateSet &CandidateSet,
7707 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007708 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007709 if (isa<UsingShadowDecl>(Callee))
7710 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7711
Douglas Gregorcabea402009-09-22 15:41:20 +00007712 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007713 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007714 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007715 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007716 return;
John McCalld14a8642009-11-21 08:51:07 +00007717 }
7718
7719 if (FunctionTemplateDecl *FuncTemplate
7720 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007721 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7722 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007723 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007724 return;
7725 }
7726
7727 assert(false && "unhandled case in overloaded call candidate");
7728
7729 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007730}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007731
Douglas Gregorcabea402009-09-22 15:41:20 +00007732/// \brief Add the overload candidates named by callee and/or found by argument
7733/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007734void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007735 Expr **Args, unsigned NumArgs,
7736 OverloadCandidateSet &CandidateSet,
7737 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007738
7739#ifndef NDEBUG
7740 // Verify that ArgumentDependentLookup is consistent with the rules
7741 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007742 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007743 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7744 // and let Y be the lookup set produced by argument dependent
7745 // lookup (defined as follows). If X contains
7746 //
7747 // -- a declaration of a class member, or
7748 //
7749 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007750 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007751 //
7752 // -- a declaration that is neither a function or a function
7753 // template
7754 //
7755 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007756
John McCall57500772009-12-16 12:17:52 +00007757 if (ULE->requiresADL()) {
7758 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7759 E = ULE->decls_end(); I != E; ++I) {
7760 assert(!(*I)->getDeclContext()->isRecord());
7761 assert(isa<UsingShadowDecl>(*I) ||
7762 !(*I)->getDeclContext()->isFunctionOrMethod());
7763 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007764 }
7765 }
7766#endif
7767
John McCall57500772009-12-16 12:17:52 +00007768 // It would be nice to avoid this copy.
7769 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00007770 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00007771 if (ULE->hasExplicitTemplateArgs()) {
7772 ULE->copyTemplateArgumentsInto(TABuffer);
7773 ExplicitTemplateArgs = &TABuffer;
7774 }
7775
7776 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7777 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007778 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007779 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007780 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007781
John McCall57500772009-12-16 12:17:52 +00007782 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007783 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7784 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007785 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007786 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007787 PartialOverloading,
7788 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00007789}
John McCalld681c392009-12-16 08:11:27 +00007790
7791/// Attempts to recover from a call where no functions were found.
7792///
7793/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007794static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007795BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007796 UnresolvedLookupExpr *ULE,
7797 SourceLocation LParenLoc,
7798 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007799 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007800
7801 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00007802 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00007803
John McCall57500772009-12-16 12:17:52 +00007804 TemplateArgumentListInfo TABuffer;
7805 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7806 if (ULE->hasExplicitTemplateArgs()) {
7807 ULE->copyTemplateArgumentsInto(TABuffer);
7808 ExplicitTemplateArgs = &TABuffer;
7809 }
7810
John McCalld681c392009-12-16 08:11:27 +00007811 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7812 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007813 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007814 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007815
John McCall57500772009-12-16 12:17:52 +00007816 assert(!R.empty() && "lookup results empty despite recovery");
7817
7818 // Build an implicit member call if appropriate. Just drop the
7819 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007820 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007821 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007822 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7823 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007824 else if (ExplicitTemplateArgs)
7825 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7826 else
7827 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7828
7829 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007830 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007831
7832 // This shouldn't cause an infinite loop because we're giving it
7833 // an expression with non-empty lookup results, which should never
7834 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007835 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007836 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007837}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007838
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007839/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007840/// (which eventually refers to the declaration Func) and the call
7841/// arguments Args/NumArgs, attempt to resolve the function call down
7842/// to a specific function. If overload resolution succeeds, returns
7843/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007844/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007845/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007846ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007847Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007848 SourceLocation LParenLoc,
7849 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00007850 SourceLocation RParenLoc,
7851 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00007852#ifndef NDEBUG
7853 if (ULE->requiresADL()) {
7854 // To do ADL, we must have found an unqualified name.
7855 assert(!ULE->getQualifier() && "qualified name with ADL");
7856
7857 // We don't perform ADL for implicit declarations of builtins.
7858 // Verify that this was correctly set up.
7859 FunctionDecl *F;
7860 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7861 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7862 F->getBuiltinID() && F->isImplicit())
7863 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007864
John McCall57500772009-12-16 12:17:52 +00007865 // We don't perform ADL in C.
7866 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00007867 } else
7868 assert(!ULE->isStdAssociatedNamespace() &&
7869 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00007870#endif
7871
John McCallbc077cf2010-02-08 23:07:23 +00007872 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007873
John McCall57500772009-12-16 12:17:52 +00007874 // Add the functions denoted by the callee to the set of candidate
7875 // functions, including those from argument-dependent lookup.
7876 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007877
7878 // If we found nothing, try to recover.
7879 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7880 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007881 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007882 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007883 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007884
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007885 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007886 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007887 case OR_Success: {
7888 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00007889 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00007890 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007891 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7892 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007893 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00007894 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7895 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00007896 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007897
7898 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007899 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007900 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007901 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007902 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007903 break;
7904
7905 case OR_Ambiguous:
7906 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007907 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007908 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007909 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007910
7911 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007912 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007913 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7914 << Best->Function->isDeleted()
7915 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007916 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007917 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007918 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7919 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00007920 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007921 }
7922
Douglas Gregorb412e172010-07-25 18:17:45 +00007923 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007924 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007925}
7926
John McCall4c4c1df2010-01-26 03:27:55 +00007927static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007928 return Functions.size() > 1 ||
7929 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7930}
7931
Douglas Gregor084d8552009-03-13 23:49:33 +00007932/// \brief Create a unary operation that may resolve to an overloaded
7933/// operator.
7934///
7935/// \param OpLoc The location of the operator itself (e.g., '*').
7936///
7937/// \param OpcIn The UnaryOperator::Opcode that describes this
7938/// operator.
7939///
7940/// \param Functions The set of non-member functions that will be
7941/// considered by overload resolution. The caller needs to build this
7942/// set based on the context using, e.g.,
7943/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7944/// set should not contain any member functions; those will be added
7945/// by CreateOverloadedUnaryOp().
7946///
7947/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007948ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007949Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7950 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007951 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007952 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007953
7954 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7955 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7956 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007957 // TODO: provide better source location info.
7958 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007959
John Wiegley01296292011-04-08 18:41:53 +00007960 if (Input->getObjectKind() == OK_ObjCProperty) {
7961 ExprResult Result = ConvertPropertyForRValue(Input);
7962 if (Result.isInvalid())
7963 return ExprError();
7964 Input = Result.take();
7965 }
John McCalle26a8722010-12-04 08:14:53 +00007966
Douglas Gregor084d8552009-03-13 23:49:33 +00007967 Expr *Args[2] = { Input, 0 };
7968 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007969
Douglas Gregor084d8552009-03-13 23:49:33 +00007970 // For post-increment and post-decrement, add the implicit '0' as
7971 // the second argument, so that we know this is a post-increment or
7972 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007973 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007974 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007975 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7976 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007977 NumArgs = 2;
7978 }
7979
7980 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007981 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007982 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007983 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00007984 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007985 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007986 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987
John McCall58cc69d2010-01-27 01:50:18 +00007988 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007989 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007990 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00007991 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007992 /*ADL*/ true, IsOverloaded(Fns),
7993 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007994 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00007995 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00007996 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007997 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007998 OpLoc));
7999 }
8000
8001 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008002 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008003
8004 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008005 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008006
8007 // Add operator candidates that are member functions.
8008 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8009
John McCall4c4c1df2010-01-26 03:27:55 +00008010 // Add candidates from ADL.
8011 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008012 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008013 /*ExplicitTemplateArgs*/ 0,
8014 CandidateSet);
8015
Douglas Gregor084d8552009-03-13 23:49:33 +00008016 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008017 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008018
8019 // Perform overload resolution.
8020 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008021 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008022 case OR_Success: {
8023 // We found a built-in operator or an overloaded operator.
8024 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008025
Douglas Gregor084d8552009-03-13 23:49:33 +00008026 if (FnDecl) {
8027 // We matched an overloaded operator. Build a call to that
8028 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008029
Chandler Carruth30141632011-02-25 19:41:05 +00008030 MarkDeclarationReferenced(OpLoc, FnDecl);
8031
Douglas Gregor084d8552009-03-13 23:49:33 +00008032 // Convert the arguments.
8033 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008034 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008035
John Wiegley01296292011-04-08 18:41:53 +00008036 ExprResult InputRes =
8037 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8038 Best->FoundDecl, Method);
8039 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008040 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008041 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008042 } else {
8043 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008044 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008045 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008046 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008047 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008048 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008049 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008050 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008051 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008052 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008053 }
8054
John McCall4fa0d5f2010-05-06 18:15:07 +00008055 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8056
John McCall7decc9e2010-11-18 06:31:45 +00008057 // Determine the result type.
8058 QualType ResultTy = FnDecl->getResultType();
8059 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8060 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008061
Douglas Gregor084d8552009-03-13 23:49:33 +00008062 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008063 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8064 if (FnExpr.isInvalid())
8065 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008066
Eli Friedman030eee42009-11-18 03:58:17 +00008067 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008068 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008069 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008070 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008071
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008072 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008073 FnDecl))
8074 return ExprError();
8075
John McCallb268a282010-08-23 23:25:46 +00008076 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008077 } else {
8078 // We matched a built-in operator. Convert the arguments, then
8079 // break out so that we will build the appropriate built-in
8080 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008081 ExprResult InputRes =
8082 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8083 Best->Conversions[0], AA_Passing);
8084 if (InputRes.isInvalid())
8085 return ExprError();
8086 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008087 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008088 }
John Wiegley01296292011-04-08 18:41:53 +00008089 }
8090
8091 case OR_No_Viable_Function:
8092 // No viable function; fall through to handling this as a
8093 // built-in operator, which will produce an error message for us.
8094 break;
8095
8096 case OR_Ambiguous:
8097 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8098 << UnaryOperator::getOpcodeStr(Opc)
8099 << Input->getType()
8100 << Input->getSourceRange();
8101 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8102 Args, NumArgs,
8103 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8104 return ExprError();
8105
8106 case OR_Deleted:
8107 Diag(OpLoc, diag::err_ovl_deleted_oper)
8108 << Best->Function->isDeleted()
8109 << UnaryOperator::getOpcodeStr(Opc)
8110 << getDeletedOrUnavailableSuffix(Best->Function)
8111 << Input->getSourceRange();
8112 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8113 return ExprError();
8114 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008115
8116 // Either we found no viable overloaded operator or we matched a
8117 // built-in operator. In either case, fall through to trying to
8118 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008119 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008120}
8121
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008122/// \brief Create a binary operation that may resolve to an overloaded
8123/// operator.
8124///
8125/// \param OpLoc The location of the operator itself (e.g., '+').
8126///
8127/// \param OpcIn The BinaryOperator::Opcode that describes this
8128/// operator.
8129///
8130/// \param Functions The set of non-member functions that will be
8131/// considered by overload resolution. The caller needs to build this
8132/// set based on the context using, e.g.,
8133/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8134/// set should not contain any member functions; those will be added
8135/// by CreateOverloadedBinOp().
8136///
8137/// \param LHS Left-hand argument.
8138/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008139ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008140Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008141 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008142 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008143 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008144 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008145 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008146
8147 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8148 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8149 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8150
8151 // If either side is type-dependent, create an appropriate dependent
8152 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008153 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008154 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008155 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008156 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008157 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008158 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008159 Context.DependentTy,
8160 VK_RValue, OK_Ordinary,
8161 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008162
Douglas Gregor5287f092009-11-05 00:51:44 +00008163 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8164 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008165 VK_LValue,
8166 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008167 Context.DependentTy,
8168 Context.DependentTy,
8169 OpLoc));
8170 }
John McCall4c4c1df2010-01-26 03:27:55 +00008171
8172 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008173 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008174 // TODO: provide better source location info in DNLoc component.
8175 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008176 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008177 = UnresolvedLookupExpr::Create(Context, NamingClass,
8178 NestedNameSpecifierLoc(), OpNameInfo,
8179 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008180 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008181 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008182 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008183 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008184 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008185 OpLoc));
8186 }
8187
John McCalle26a8722010-12-04 08:14:53 +00008188 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008189 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8190 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8191 if (Result.isInvalid())
8192 return ExprError();
8193 Args[1] = Result.take();
8194 }
John McCalle26a8722010-12-04 08:14:53 +00008195
8196 // The LHS is more complicated.
8197 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8198
8199 // There's a tension for assignment operators between primitive
8200 // property assignment and the overloaded operators.
8201 if (BinaryOperator::isAssignmentOp(Opc)) {
8202 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8203
8204 // Is the property "logically" settable?
8205 bool Settable = (PRE->isExplicitProperty() ||
8206 PRE->getImplicitPropertySetter());
8207
8208 // To avoid gratuitously inventing semantics, use the primitive
8209 // unless it isn't. Thoughts in case we ever really care:
8210 // - If the property isn't logically settable, we have to
8211 // load and hope.
8212 // - If the property is settable and this is simple assignment,
8213 // we really should use the primitive.
8214 // - If the property is settable, then we could try overloading
8215 // on a generic lvalue of the appropriate type; if it works
8216 // out to a builtin candidate, we would do that same operation
8217 // on the property, and otherwise just error.
8218 if (Settable)
8219 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8220 }
8221
John Wiegley01296292011-04-08 18:41:53 +00008222 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8223 if (Result.isInvalid())
8224 return ExprError();
8225 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008226 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008227
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008228 // If this is the assignment operator, we only perform overload resolution
8229 // if the left-hand side is a class or enumeration type. This is actually
8230 // a hack. The standard requires that we do overload resolution between the
8231 // various built-in candidates, but as DR507 points out, this can lead to
8232 // problems. So we do it this way, which pretty much follows what GCC does.
8233 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008234 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008235 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008236
John McCalle26a8722010-12-04 08:14:53 +00008237 // If this is the .* operator, which is not overloadable, just
8238 // create a built-in binary operator.
8239 if (Opc == BO_PtrMemD)
8240 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8241
Douglas Gregor084d8552009-03-13 23:49:33 +00008242 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008243 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008244
8245 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008246 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008247
8248 // Add operator candidates that are member functions.
8249 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8250
John McCall4c4c1df2010-01-26 03:27:55 +00008251 // Add candidates from ADL.
8252 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8253 Args, 2,
8254 /*ExplicitTemplateArgs*/ 0,
8255 CandidateSet);
8256
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008257 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008258 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008259
8260 // Perform overload resolution.
8261 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008262 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008263 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008264 // We found a built-in operator or an overloaded operator.
8265 FunctionDecl *FnDecl = Best->Function;
8266
8267 if (FnDecl) {
8268 // We matched an overloaded operator. Build a call to that
8269 // operator.
8270
Chandler Carruth30141632011-02-25 19:41:05 +00008271 MarkDeclarationReferenced(OpLoc, FnDecl);
8272
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008273 // Convert the arguments.
8274 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008275 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008276 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008277
Chandler Carruth8e543b32010-12-12 08:17:55 +00008278 ExprResult Arg1 =
8279 PerformCopyInitialization(
8280 InitializedEntity::InitializeParameter(Context,
8281 FnDecl->getParamDecl(0)),
8282 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008283 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008284 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008285
John Wiegley01296292011-04-08 18:41:53 +00008286 ExprResult Arg0 =
8287 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8288 Best->FoundDecl, Method);
8289 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008290 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008291 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008292 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008293 } else {
8294 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008295 ExprResult Arg0 = PerformCopyInitialization(
8296 InitializedEntity::InitializeParameter(Context,
8297 FnDecl->getParamDecl(0)),
8298 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008299 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008300 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008301
Chandler Carruth8e543b32010-12-12 08:17:55 +00008302 ExprResult Arg1 =
8303 PerformCopyInitialization(
8304 InitializedEntity::InitializeParameter(Context,
8305 FnDecl->getParamDecl(1)),
8306 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008307 if (Arg1.isInvalid())
8308 return ExprError();
8309 Args[0] = LHS = Arg0.takeAs<Expr>();
8310 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008311 }
8312
John McCall4fa0d5f2010-05-06 18:15:07 +00008313 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8314
John McCall7decc9e2010-11-18 06:31:45 +00008315 // Determine the result type.
8316 QualType ResultTy = FnDecl->getResultType();
8317 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8318 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008319
8320 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008321 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8322 if (FnExpr.isInvalid())
8323 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008324
John McCallb268a282010-08-23 23:25:46 +00008325 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008326 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008327 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008328
8329 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008330 FnDecl))
8331 return ExprError();
8332
John McCallb268a282010-08-23 23:25:46 +00008333 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008334 } else {
8335 // We matched a built-in operator. Convert the arguments, then
8336 // break out so that we will build the appropriate built-in
8337 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008338 ExprResult ArgsRes0 =
8339 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8340 Best->Conversions[0], AA_Passing);
8341 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008342 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008343 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008344
John Wiegley01296292011-04-08 18:41:53 +00008345 ExprResult ArgsRes1 =
8346 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8347 Best->Conversions[1], AA_Passing);
8348 if (ArgsRes1.isInvalid())
8349 return ExprError();
8350 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008351 break;
8352 }
8353 }
8354
Douglas Gregor66950a32009-09-30 21:46:01 +00008355 case OR_No_Viable_Function: {
8356 // C++ [over.match.oper]p9:
8357 // If the operator is the operator , [...] and there are no
8358 // viable functions, then the operator is assumed to be the
8359 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008360 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008361 break;
8362
Chandler Carruth8e543b32010-12-12 08:17:55 +00008363 // For class as left operand for assignment or compound assigment
8364 // operator do not fall through to handling in built-in, but report that
8365 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008366 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008367 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008368 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008369 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8370 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008371 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008372 } else {
8373 // No viable function; try to create a built-in operation, which will
8374 // produce an error. Then, show the non-viable candidates.
8375 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008377 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008378 "C++ binary operator overloading is missing candidates!");
8379 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008380 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8381 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008382 return move(Result);
8383 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008384
8385 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008386 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008387 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008388 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008389 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008390 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8391 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008392 return ExprError();
8393
8394 case OR_Deleted:
8395 Diag(OpLoc, diag::err_ovl_deleted_oper)
8396 << Best->Function->isDeleted()
8397 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008398 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008399 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008400 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008401 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008402 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008403
Douglas Gregor66950a32009-09-30 21:46:01 +00008404 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008405 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008406}
8407
John McCalldadc5752010-08-24 06:29:42 +00008408ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008409Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8410 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008411 Expr *Base, Expr *Idx) {
8412 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008413 DeclarationName OpName =
8414 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8415
8416 // If either side is type-dependent, create an appropriate dependent
8417 // expression.
8418 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8419
John McCall58cc69d2010-01-27 01:50:18 +00008420 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008421 // CHECKME: no 'operator' keyword?
8422 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8423 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008424 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008425 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008426 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008427 /*ADL*/ true, /*Overloaded*/ false,
8428 UnresolvedSetIterator(),
8429 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008430 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008431
Sebastian Redladba46e2009-10-29 20:17:01 +00008432 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8433 Args, 2,
8434 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008435 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008436 RLoc));
8437 }
8438
John Wiegley01296292011-04-08 18:41:53 +00008439 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8440 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8441 if (Result.isInvalid())
8442 return ExprError();
8443 Args[0] = Result.take();
8444 }
8445 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8446 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8447 if (Result.isInvalid())
8448 return ExprError();
8449 Args[1] = Result.take();
8450 }
John McCalle26a8722010-12-04 08:14:53 +00008451
Sebastian Redladba46e2009-10-29 20:17:01 +00008452 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008453 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008454
8455 // Subscript can only be overloaded as a member function.
8456
8457 // Add operator candidates that are member functions.
8458 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8459
8460 // Add builtin operator candidates.
8461 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8462
8463 // Perform overload resolution.
8464 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008465 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008466 case OR_Success: {
8467 // We found a built-in operator or an overloaded operator.
8468 FunctionDecl *FnDecl = Best->Function;
8469
8470 if (FnDecl) {
8471 // We matched an overloaded operator. Build a call to that
8472 // operator.
8473
Chandler Carruth30141632011-02-25 19:41:05 +00008474 MarkDeclarationReferenced(LLoc, FnDecl);
8475
John McCalla0296f72010-03-19 07:35:19 +00008476 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008477 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008478
Sebastian Redladba46e2009-10-29 20:17:01 +00008479 // Convert the arguments.
8480 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00008481 ExprResult Arg0 =
8482 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8483 Best->FoundDecl, Method);
8484 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008485 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008486 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008487
Anders Carlssona68e51e2010-01-29 18:37:50 +00008488 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008489 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008490 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008491 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008492 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008493 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008494 Owned(Args[1]));
8495 if (InputInit.isInvalid())
8496 return ExprError();
8497
8498 Args[1] = InputInit.takeAs<Expr>();
8499
Sebastian Redladba46e2009-10-29 20:17:01 +00008500 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008501 QualType ResultTy = FnDecl->getResultType();
8502 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8503 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008504
8505 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008506 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8507 if (FnExpr.isInvalid())
8508 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008509
John McCallb268a282010-08-23 23:25:46 +00008510 CXXOperatorCallExpr *TheCall =
8511 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00008512 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008513 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008514
John McCallb268a282010-08-23 23:25:46 +00008515 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008516 FnDecl))
8517 return ExprError();
8518
John McCallb268a282010-08-23 23:25:46 +00008519 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008520 } else {
8521 // We matched a built-in operator. Convert the arguments, then
8522 // break out so that we will build the appropriate built-in
8523 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008524 ExprResult ArgsRes0 =
8525 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8526 Best->Conversions[0], AA_Passing);
8527 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008528 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008529 Args[0] = ArgsRes0.take();
8530
8531 ExprResult ArgsRes1 =
8532 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8533 Best->Conversions[1], AA_Passing);
8534 if (ArgsRes1.isInvalid())
8535 return ExprError();
8536 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008537
8538 break;
8539 }
8540 }
8541
8542 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008543 if (CandidateSet.empty())
8544 Diag(LLoc, diag::err_ovl_no_oper)
8545 << Args[0]->getType() << /*subscript*/ 0
8546 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8547 else
8548 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8549 << Args[0]->getType()
8550 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008551 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8552 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008553 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008554 }
8555
8556 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008557 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008558 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008559 << Args[0]->getType() << Args[1]->getType()
8560 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008561 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8562 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008563 return ExprError();
8564
8565 case OR_Deleted:
8566 Diag(LLoc, diag::err_ovl_deleted_oper)
8567 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008568 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00008569 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008570 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8571 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008572 return ExprError();
8573 }
8574
8575 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008576 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008577}
8578
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008579/// BuildCallToMemberFunction - Build a call to a member
8580/// function. MemExpr is the expression that refers to the member
8581/// function (and includes the object parameter), Args/NumArgs are the
8582/// arguments to the function call (not including the object
8583/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00008584/// expression refers to a non-static member function or an overloaded
8585/// member function.
John McCalldadc5752010-08-24 06:29:42 +00008586ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008587Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8588 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008589 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00008590 assert(MemExprE->getType() == Context.BoundMemberTy ||
8591 MemExprE->getType() == Context.OverloadTy);
8592
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008593 // Dig out the member expression. This holds both the object
8594 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008595 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008596
John McCall0009fcc2011-04-26 20:42:42 +00008597 // Determine whether this is a call to a pointer-to-member function.
8598 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
8599 assert(op->getType() == Context.BoundMemberTy);
8600 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
8601
8602 QualType fnType =
8603 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
8604
8605 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
8606 QualType resultType = proto->getCallResultType(Context);
8607 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
8608
8609 // Check that the object type isn't more qualified than the
8610 // member function we're calling.
8611 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
8612
8613 QualType objectType = op->getLHS()->getType();
8614 if (op->getOpcode() == BO_PtrMemI)
8615 objectType = objectType->castAs<PointerType>()->getPointeeType();
8616 Qualifiers objectQuals = objectType.getQualifiers();
8617
8618 Qualifiers difference = objectQuals - funcQuals;
8619 difference.removeObjCGCAttr();
8620 difference.removeAddressSpace();
8621 if (difference) {
8622 std::string qualsString = difference.getAsString();
8623 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
8624 << fnType.getUnqualifiedType()
8625 << qualsString
8626 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
8627 }
8628
8629 CXXMemberCallExpr *call
8630 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
8631 resultType, valueKind, RParenLoc);
8632
8633 if (CheckCallReturnType(proto->getResultType(),
8634 op->getRHS()->getSourceRange().getBegin(),
8635 call, 0))
8636 return ExprError();
8637
8638 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
8639 return ExprError();
8640
8641 return MaybeBindToTemporary(call);
8642 }
8643
John McCall10eae182009-11-30 22:42:35 +00008644 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008645 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008646 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008647 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008648 if (isa<MemberExpr>(NakedMemExpr)) {
8649 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008650 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008651 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008652 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008653 } else {
8654 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008655 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008656
John McCall6e9f8f62009-12-03 04:06:58 +00008657 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008658 Expr::Classification ObjectClassification
8659 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8660 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008661
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008662 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008663 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008664
John McCall2d74de92009-12-01 22:10:20 +00008665 // FIXME: avoid copy.
8666 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8667 if (UnresExpr->hasExplicitTemplateArgs()) {
8668 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8669 TemplateArgs = &TemplateArgsBuffer;
8670 }
8671
John McCall10eae182009-11-30 22:42:35 +00008672 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8673 E = UnresExpr->decls_end(); I != E; ++I) {
8674
John McCall6e9f8f62009-12-03 04:06:58 +00008675 NamedDecl *Func = *I;
8676 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8677 if (isa<UsingShadowDecl>(Func))
8678 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8679
Douglas Gregor02824322011-01-26 19:30:28 +00008680
Francois Pichet64225792011-01-18 05:04:39 +00008681 // Microsoft supports direct constructor calls.
8682 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8683 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8684 CandidateSet);
8685 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008686 // If explicit template arguments were provided, we can't call a
8687 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008688 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008689 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008690
John McCalla0296f72010-03-19 07:35:19 +00008691 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008692 ObjectClassification,
8693 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00008694 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008695 } else {
John McCall10eae182009-11-30 22:42:35 +00008696 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008697 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008698 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00008699 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008700 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008701 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008702 }
Mike Stump11289f42009-09-09 15:08:12 +00008703
John McCall10eae182009-11-30 22:42:35 +00008704 DeclarationName DeclName = UnresExpr->getMemberName();
8705
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008706 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008707 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008708 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008709 case OR_Success:
8710 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00008711 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00008712 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008713 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008714 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008715 break;
8716
8717 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008718 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008719 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008720 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008721 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008722 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008723 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008724
8725 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008726 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008727 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008728 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008729 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008730 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008731
8732 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008733 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008734 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008735 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008736 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008737 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008738 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008739 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008740 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008741 }
8742
John McCall16df1e52010-03-30 21:47:33 +00008743 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008744
John McCall2d74de92009-12-01 22:10:20 +00008745 // If overload resolution picked a static member, build a
8746 // non-member call based on that function.
8747 if (Method->isStatic()) {
8748 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8749 Args, NumArgs, RParenLoc);
8750 }
8751
John McCall10eae182009-11-30 22:42:35 +00008752 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008753 }
8754
John McCall7decc9e2010-11-18 06:31:45 +00008755 QualType ResultType = Method->getResultType();
8756 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8757 ResultType = ResultType.getNonLValueExprType(Context);
8758
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008759 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008760 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00008761 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008762 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008763
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008764 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008765 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008766 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008767 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008768
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008769 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008770 // We only need to do this if there was actually an overload; otherwise
8771 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00008772 if (!Method->isStatic()) {
8773 ExprResult ObjectArg =
8774 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
8775 FoundDecl, Method);
8776 if (ObjectArg.isInvalid())
8777 return ExprError();
8778 MemExpr->setBase(ObjectArg.take());
8779 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008780
8781 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008782 const FunctionProtoType *Proto =
8783 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008784 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008785 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008786 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008787
John McCallb268a282010-08-23 23:25:46 +00008788 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008789 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008790
Anders Carlsson47061ee2011-05-06 14:25:31 +00008791 if ((isa<CXXConstructorDecl>(CurContext) ||
8792 isa<CXXDestructorDecl>(CurContext)) &&
8793 TheCall->getMethodDecl()->isPure()) {
8794 const CXXMethodDecl *MD = TheCall->getMethodDecl();
8795
8796 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()))
8797 Diag(MemExpr->getLocStart(),
8798 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
8799 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
8800 << MD->getParent()->getDeclName();
8801
8802 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
8803 }
John McCallb268a282010-08-23 23:25:46 +00008804 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008805}
8806
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008807/// BuildCallToObjectOfClassType - Build a call to an object of class
8808/// type (C++ [over.call.object]), which can end up invoking an
8809/// overloaded function call operator (@c operator()) or performing a
8810/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008811ExprResult
John Wiegley01296292011-04-08 18:41:53 +00008812Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008813 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008814 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008815 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00008816 ExprResult Object = Owned(Obj);
8817 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
8818 Object = ConvertPropertyForRValue(Object.take());
8819 if (Object.isInvalid())
8820 return ExprError();
8821 }
John McCalle26a8722010-12-04 08:14:53 +00008822
John Wiegley01296292011-04-08 18:41:53 +00008823 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
8824 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008825
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008826 // C++ [over.call.object]p1:
8827 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008828 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008829 // candidate functions includes at least the function call
8830 // operators of T. The function call operators of T are obtained by
8831 // ordinary lookup of the name operator() in the context of
8832 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008833 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008834 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008835
John Wiegley01296292011-04-08 18:41:53 +00008836 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008837 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008838 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008839 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008840
John McCall27b18f82009-11-17 02:14:36 +00008841 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8842 LookupQualifiedName(R, Record->getDecl());
8843 R.suppressDiagnostics();
8844
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008845 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008846 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00008847 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
8848 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008849 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008851
Douglas Gregorab7897a2008-11-19 22:57:39 +00008852 // C++ [over.call.object]p2:
8853 // In addition, for each conversion function declared in T of the
8854 // form
8855 //
8856 // operator conversion-type-id () cv-qualifier;
8857 //
8858 // where cv-qualifier is the same cv-qualification as, or a
8859 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008860 // denotes the type "pointer to function of (P1,...,Pn) returning
8861 // R", or the type "reference to pointer to function of
8862 // (P1,...,Pn) returning R", or the type "reference to function
8863 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008864 // is also considered as a candidate function. Similarly,
8865 // surrogate call functions are added to the set of candidate
8866 // functions for each conversion function declared in an
8867 // accessible base class provided the function is not hidden
8868 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008869 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008870 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008871 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008872 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008873 NamedDecl *D = *I;
8874 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8875 if (isa<UsingShadowDecl>(D))
8876 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008877
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008878 // Skip over templated conversion functions; they aren't
8879 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008880 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008881 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008882
John McCall6e9f8f62009-12-03 04:06:58 +00008883 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008884
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008885 // Strip the reference type (if any) and then the pointer type (if
8886 // any) to get down to what might be a function type.
8887 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8888 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8889 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008890
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008891 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008892 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John Wiegley01296292011-04-08 18:41:53 +00008893 Object.get(), Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008894 }
Mike Stump11289f42009-09-09 15:08:12 +00008895
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008896 // Perform overload resolution.
8897 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00008898 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00008899 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008900 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008901 // Overload resolution succeeded; we'll build the appropriate call
8902 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008903 break;
8904
8905 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008906 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00008907 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8908 << Object.get()->getType() << /*call*/ 1
8909 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00008910 else
John Wiegley01296292011-04-08 18:41:53 +00008911 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00008912 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008913 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008914 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008915 break;
8916
8917 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00008918 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008919 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008920 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008921 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008922 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008923
8924 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00008925 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00008926 diag::err_ovl_deleted_object_call)
8927 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00008928 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008929 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00008930 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008931 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008932 break;
Mike Stump11289f42009-09-09 15:08:12 +00008933 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008934
Douglas Gregorb412e172010-07-25 18:17:45 +00008935 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008936 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008937
Douglas Gregorab7897a2008-11-19 22:57:39 +00008938 if (Best->Function == 0) {
8939 // Since there is no function declaration, this is one of the
8940 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008941 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008942 = cast<CXXConversionDecl>(
8943 Best->Conversions[0].UserDefined.ConversionFunction);
8944
John Wiegley01296292011-04-08 18:41:53 +00008945 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008946 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008947
Douglas Gregorab7897a2008-11-19 22:57:39 +00008948 // We selected one of the surrogate functions that converts the
8949 // object parameter to a function pointer. Perform the conversion
8950 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008951
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008952 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008953 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00008954 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00008955 if (Call.isInvalid())
8956 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008957
Douglas Gregor668443e2011-01-20 00:18:04 +00008958 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008959 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008960 }
8961
Chandler Carruth30141632011-02-25 19:41:05 +00008962 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00008963 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008964 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008965
Douglas Gregorab7897a2008-11-19 22:57:39 +00008966 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8967 // that calls this method, using Object for the implicit object
8968 // parameter and passing along the remaining arguments.
8969 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008970 const FunctionProtoType *Proto =
8971 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008972
8973 unsigned NumArgsInProto = Proto->getNumArgs();
8974 unsigned NumArgsToCheck = NumArgs;
8975
8976 // Build the full argument list for the method call (the
8977 // implicit object parameter is placed at the beginning of the
8978 // list).
8979 Expr **MethodArgs;
8980 if (NumArgs < NumArgsInProto) {
8981 NumArgsToCheck = NumArgsInProto;
8982 MethodArgs = new Expr*[NumArgsInProto + 1];
8983 } else {
8984 MethodArgs = new Expr*[NumArgs + 1];
8985 }
John Wiegley01296292011-04-08 18:41:53 +00008986 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008987 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8988 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008989
John Wiegley01296292011-04-08 18:41:53 +00008990 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
8991 if (NewFn.isInvalid())
8992 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008993
8994 // Once we've built TheCall, all of the expressions are properly
8995 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008996 QualType ResultTy = Method->getResultType();
8997 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8998 ResultTy = ResultTy.getNonLValueExprType(Context);
8999
John McCallb268a282010-08-23 23:25:46 +00009000 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009001 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009002 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009003 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009004 delete [] MethodArgs;
9005
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009006 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009007 Method))
9008 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009009
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009010 // We may have default arguments. If so, we need to allocate more
9011 // slots in the call for them.
9012 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009013 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009014 else if (NumArgs > NumArgsInProto)
9015 NumArgsToCheck = NumArgsInProto;
9016
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009017 bool IsError = false;
9018
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009019 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009020 ExprResult ObjRes =
9021 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9022 Best->FoundDecl, Method);
9023 if (ObjRes.isInvalid())
9024 IsError = true;
9025 else
9026 Object = move(ObjRes);
9027 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009028
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009029 // Check the argument types.
9030 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009031 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009032 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009033 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009034
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009035 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009036
John McCalldadc5752010-08-24 06:29:42 +00009037 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009038 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009039 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009040 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009041 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009042
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009043 IsError |= InputInit.isInvalid();
9044 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009045 } else {
John McCalldadc5752010-08-24 06:29:42 +00009046 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009047 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9048 if (DefArg.isInvalid()) {
9049 IsError = true;
9050 break;
9051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009052
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009053 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009054 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009055
9056 TheCall->setArg(i + 1, Arg);
9057 }
9058
9059 // If this is a variadic call, handle args passed through "...".
9060 if (Proto->isVariadic()) {
9061 // Promote the arguments (C99 6.5.2.2p7).
9062 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009063 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9064 IsError |= Arg.isInvalid();
9065 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009066 }
9067 }
9068
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009069 if (IsError) return true;
9070
John McCallb268a282010-08-23 23:25:46 +00009071 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009072 return true;
9073
John McCalle172be52010-08-24 06:09:16 +00009074 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009075}
9076
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009077/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009078/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009079/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009080ExprResult
John McCallb268a282010-08-23 23:25:46 +00009081Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009082 assert(Base->getType()->isRecordType() &&
9083 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009084
John Wiegley01296292011-04-08 18:41:53 +00009085 if (Base->getObjectKind() == OK_ObjCProperty) {
9086 ExprResult Result = ConvertPropertyForRValue(Base);
9087 if (Result.isInvalid())
9088 return ExprError();
9089 Base = Result.take();
9090 }
John McCalle26a8722010-12-04 08:14:53 +00009091
John McCallbc077cf2010-02-08 23:07:23 +00009092 SourceLocation Loc = Base->getExprLoc();
9093
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009094 // C++ [over.ref]p1:
9095 //
9096 // [...] An expression x->m is interpreted as (x.operator->())->m
9097 // for a class object x of type T if T::operator->() exists and if
9098 // the operator is selected as the best match function by the
9099 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009100 DeclarationName OpName =
9101 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009102 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009103 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009104
John McCallbc077cf2010-02-08 23:07:23 +00009105 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009106 PDiag(diag::err_typecheck_incomplete_tag)
9107 << Base->getSourceRange()))
9108 return ExprError();
9109
John McCall27b18f82009-11-17 02:14:36 +00009110 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9111 LookupQualifiedName(R, BaseRecord->getDecl());
9112 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009113
9114 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009115 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009116 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9117 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009118 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009119
9120 // Perform overload resolution.
9121 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009122 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009123 case OR_Success:
9124 // Overload resolution succeeded; we'll build the call below.
9125 break;
9126
9127 case OR_No_Viable_Function:
9128 if (CandidateSet.empty())
9129 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009130 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009131 else
9132 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009133 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009134 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009135 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009136
9137 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009138 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9139 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009140 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009141 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009142
9143 case OR_Deleted:
9144 Diag(OpLoc, diag::err_ovl_deleted_oper)
9145 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009146 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009147 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009148 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009149 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009150 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009151 }
9152
Chandler Carruth30141632011-02-25 19:41:05 +00009153 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009154 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009155 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009156
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009157 // Convert the object parameter.
9158 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009159 ExprResult BaseResult =
9160 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9161 Best->FoundDecl, Method);
9162 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009163 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009164 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009165
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009166 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009167 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9168 if (FnExpr.isInvalid())
9169 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009170
John McCall7decc9e2010-11-18 06:31:45 +00009171 QualType ResultTy = Method->getResultType();
9172 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9173 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009174 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009175 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009176 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009177
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009178 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009179 Method))
9180 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009181
9182 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009183}
9184
Douglas Gregorcd695e52008-11-10 20:40:00 +00009185/// FixOverloadedFunctionReference - E is an expression that refers to
9186/// a C++ overloaded function (possibly with some parentheses and
9187/// perhaps a '&' around it). We have resolved the overloaded function
9188/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009189/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009190Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009191 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009192 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009193 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9194 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009195 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009196 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009197
Douglas Gregor51c538b2009-11-20 19:42:02 +00009198 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009199 }
9200
Douglas Gregor51c538b2009-11-20 19:42:02 +00009201 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009202 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9203 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009204 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009205 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009206 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009207 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009208 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009209 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009210
9211 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009212 ICE->getCastKind(),
9213 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009214 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009215 }
9216
Douglas Gregor51c538b2009-11-20 19:42:02 +00009217 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009218 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009219 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009220 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9221 if (Method->isStatic()) {
9222 // Do nothing: static member functions aren't any different
9223 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009224 } else {
John McCalle66edc12009-11-24 19:00:30 +00009225 // Fix the sub expression, which really has to be an
9226 // UnresolvedLookupExpr holding an overloaded member function
9227 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009228 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9229 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009230 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009231 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009232
John McCalld14a8642009-11-21 08:51:07 +00009233 assert(isa<DeclRefExpr>(SubExpr)
9234 && "fixed to something other than a decl ref");
9235 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9236 && "fixed to a member ref with no nested name qualifier");
9237
9238 // We have taken the address of a pointer to member
9239 // function. Perform the computation here so that we get the
9240 // appropriate pointer to member type.
9241 QualType ClassType
9242 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9243 QualType MemPtrType
9244 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9245
John McCall7decc9e2010-11-18 06:31:45 +00009246 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9247 VK_RValue, OK_Ordinary,
9248 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009249 }
9250 }
John McCall16df1e52010-03-30 21:47:33 +00009251 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9252 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009253 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009254 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009255
John McCalle3027922010-08-25 11:45:40 +00009256 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009257 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009258 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009259 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009260 }
John McCalld14a8642009-11-21 08:51:07 +00009261
9262 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009263 // FIXME: avoid copy.
9264 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009265 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009266 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9267 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009268 }
9269
John McCalld14a8642009-11-21 08:51:07 +00009270 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009271 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009272 Fn,
9273 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009274 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009275 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009276 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009277 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009278 }
9279
John McCall10eae182009-11-30 22:42:35 +00009280 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009281 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009282 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9283 if (MemExpr->hasExplicitTemplateArgs()) {
9284 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9285 TemplateArgs = &TemplateArgsBuffer;
9286 }
John McCall6b51f282009-11-23 01:53:49 +00009287
John McCall2d74de92009-12-01 22:10:20 +00009288 Expr *Base;
9289
John McCall7decc9e2010-11-18 06:31:45 +00009290 // If we're filling in a static method where we used to have an
9291 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009292 if (MemExpr->isImplicitAccess()) {
9293 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9294 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009295 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009296 Fn,
9297 MemExpr->getMemberLoc(),
9298 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009299 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009300 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009301 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009302 } else {
9303 SourceLocation Loc = MemExpr->getMemberLoc();
9304 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009305 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009306 Base = new (Context) CXXThisExpr(Loc,
9307 MemExpr->getBaseType(),
9308 /*isImplicit=*/true);
9309 }
John McCall2d74de92009-12-01 22:10:20 +00009310 } else
John McCallc3007a22010-10-26 07:05:15 +00009311 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009312
John McCall4adb38c2011-04-27 00:36:17 +00009313 ExprValueKind valueKind;
9314 QualType type;
9315 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9316 valueKind = VK_LValue;
9317 type = Fn->getType();
9318 } else {
9319 valueKind = VK_RValue;
9320 type = Context.BoundMemberTy;
9321 }
9322
John McCall2d74de92009-12-01 22:10:20 +00009323 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009324 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009325 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009326 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009327 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009328 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009329 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009330 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009332
John McCallc3007a22010-10-26 07:05:15 +00009333 llvm_unreachable("Invalid reference to overloaded function");
9334 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009335}
9336
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009337ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009338 DeclAccessPair Found,
9339 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009340 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009341}
9342
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009343} // end namespace clang