blob: 0c9083ef2f2850ff79f8180d3398fea4d951aec9 [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,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
43 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo));
John Wiegley01296292011-04-08 18:41:53 +000045 E = S.DefaultFunctionArrayConversion(E.take());
46 if (E.isInvalid())
47 return ExprError();
48 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000049}
50
John McCall5c32be02010-08-24 20:38:10 +000051static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
52 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000053 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000054 bool CStyle,
55 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000056
57static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
58 QualType &ToType,
59 bool InOverloadResolution,
60 StandardConversionSequence &SCS,
61 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000062static OverloadingResult
63IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
64 UserDefinedConversionSequence& User,
65 OverloadCandidateSet& Conversions,
66 bool AllowExplicit);
67
68
69static ImplicitConversionSequence::CompareKind
70CompareStandardConversionSequences(Sema &S,
71 const StandardConversionSequence& SCS1,
72 const StandardConversionSequence& SCS2);
73
74static ImplicitConversionSequence::CompareKind
75CompareQualificationConversions(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareDerivedToBaseConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84
85
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086/// GetConversionCategory - Retrieve the implicit conversion
87/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000088ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089GetConversionCategory(ImplicitConversionKind Kind) {
90 static const ImplicitConversionCategory
91 Category[(int)ICK_Num_Conversion_Kinds] = {
92 ICC_Identity,
93 ICC_Lvalue_Transformation,
94 ICC_Lvalue_Transformation,
95 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 ICC_Qualification_Adjustment,
98 ICC_Promotion,
99 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 ICC_Promotion,
101 ICC_Conversion,
102 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 ICC_Conversion,
104 ICC_Conversion,
105 ICC_Conversion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000110 ICC_Conversion,
111 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000112 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000113 ICC_Conversion
114 };
115 return Category[(int)Kind];
116}
117
118/// GetConversionRank - Retrieve the implicit conversion rank
119/// corresponding to the given implicit conversion kind.
120ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
121 static const ImplicitConversionRank
122 Rank[(int)ICK_Num_Conversion_Kinds] = {
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000128 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000129 ICR_Promotion,
130 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000131 ICR_Promotion,
132 ICR_Conversion,
133 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000139 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000140 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000141 ICR_Conversion,
142 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000143 ICR_Complex_Real_Conversion,
144 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000145 ICR_Conversion,
146 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 };
148 return Rank[(int)Kind];
149}
150
151/// GetImplicitConversionName - Return the name of this kind of
152/// implicit conversion.
153const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 "No conversion",
156 "Lvalue-to-rvalue",
157 "Array-to-pointer",
158 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000159 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "Qualification",
161 "Integral promotion",
162 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000163 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Integral conversion",
165 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Floating-integral conversion",
168 "Pointer conversion",
169 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000170 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000171 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000172 "Derived-to-base conversion",
173 "Vector conversion",
174 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000175 "Complex-real conversion",
176 "Block Pointer conversion",
177 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000178 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000198 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000199}
200
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregor5c407d92008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000258/// DebugPrint - Print this standard conversion sequence to standard
259/// error. Useful for debugging overloading issues.
260void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000261 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000262 bool PrintedSomething = false;
263 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 PrintedSomething = true;
266 }
267
268 if (Second != ICK_Identity) {
269 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000270 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000271 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000272 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000273
274 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000275 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000276 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000277 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000278 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000279 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000280 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (Third != ICK_Identity) {
285 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000286 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000288 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000289 PrintedSomething = true;
290 }
291
292 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 }
295}
296
297/// DebugPrint - Print this user-defined conversion sequence to standard
298/// error. Useful for debugging overloading issues.
299void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000300 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301 if (Before.First || Before.Second || Before.Third) {
302 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000303 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000305 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 After.DebugPrint();
309 }
310}
311
312/// DebugPrint - Print this implicit conversion sequence to standard
313/// error. Useful for debugging overloading issues.
314void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000315 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000316 switch (ConversionKind) {
317 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000318 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000319 Standard.DebugPrint();
320 break;
321 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000322 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000323 UserDefined.DebugPrint();
324 break;
325 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000326 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000327 break;
John McCall0d1da222010-01-12 00:44:57 +0000328 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000329 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000330 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000331 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000332 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000333 break;
334 }
335
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000336 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337}
338
John McCall0d1da222010-01-12 00:44:57 +0000339void AmbiguousConversionSequence::construct() {
340 new (&conversions()) ConversionSet();
341}
342
343void AmbiguousConversionSequence::destruct() {
344 conversions().~ConversionSet();
345}
346
347void
348AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
349 FromTypePtr = O.FromTypePtr;
350 ToTypePtr = O.ToTypePtr;
351 new (&conversions()) ConversionSet(O.conversions());
352}
353
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354namespace {
355 // Structure used by OverloadCandidate::DeductionFailureInfo to store
356 // template parameter and template argument information.
357 struct DFIParamWithArguments {
358 TemplateParameter Param;
359 TemplateArgument FirstArg;
360 TemplateArgument SecondArg;
361 };
362}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000363
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000364/// \brief Convert from Sema's representation of template deduction information
365/// to the form used in overload-candidate information.
366OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000367static MakeDeductionFailureInfo(ASTContext &Context,
368 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000369 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370 OverloadCandidate::DeductionFailureInfo Result;
371 Result.Result = static_cast<unsigned>(TDK);
372 Result.Data = 0;
373 switch (TDK) {
374 case Sema::TDK_Success:
375 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000376 case Sema::TDK_TooManyArguments:
377 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000378 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000381 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000382 Result.Data = Info.Param.getOpaqueValue();
383 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000386 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000387 // FIXME: Should allocate from normal heap so that we can free this later.
388 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000389 Saved->Param = Info.Param;
390 Saved->FirstArg = Info.FirstArg;
391 Saved->SecondArg = Info.SecondArg;
392 Result.Data = Saved;
393 break;
394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000395
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000397 Result.Data = Info.take();
398 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000399
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000400 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000401 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000404
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000405 return Result;
406}
John McCall0d1da222010-01-12 00:44:57 +0000407
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408void OverloadCandidate::DeductionFailureInfo::Destroy() {
409 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
410 case Sema::TDK_Success:
411 case Sema::TDK_InstantiationDepth:
412 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000413 case Sema::TDK_TooManyArguments:
414 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000415 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000416 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000418 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000419 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000420 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000421 Data = 0;
422 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000423
424 case Sema::TDK_SubstitutionFailure:
425 // FIXME: Destroy the template arugment list?
426 Data = 0;
427 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428
Douglas Gregor461761d2010-05-08 18:20:53 +0000429 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000430 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_FailedOverloadResolution:
432 break;
433 }
434}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
436TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
438 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
439 case Sema::TDK_Success:
440 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000441 case Sema::TDK_TooManyArguments:
442 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000443 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000444 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000446 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000447 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000448 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000449
450 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000451 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000455 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000456 case Sema::TDK_FailedOverloadResolution:
457 break;
458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 return TemplateParameter();
461}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
Douglas Gregord09efd42010-05-08 20:07:26 +0000463TemplateArgumentList *
464OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
465 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
466 case Sema::TDK_Success:
467 case Sema::TDK_InstantiationDepth:
468 case Sema::TDK_TooManyArguments:
469 case Sema::TDK_TooFewArguments:
470 case Sema::TDK_Incomplete:
471 case Sema::TDK_InvalidExplicitArguments:
472 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000473 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000474 return 0;
475
476 case Sema::TDK_SubstitutionFailure:
477 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000478
Douglas Gregord09efd42010-05-08 20:07:26 +0000479 // Unhandled
480 case Sema::TDK_NonDeducedMismatch:
481 case Sema::TDK_FailedOverloadResolution:
482 break;
483 }
484
485 return 0;
486}
487
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000488const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
489 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
490 case Sema::TDK_Success:
491 case Sema::TDK_InstantiationDepth:
492 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000493 case Sema::TDK_TooManyArguments:
494 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000495 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000496 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000497 return 0;
498
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000499 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000500 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502
Douglas Gregor461761d2010-05-08 18:20:53 +0000503 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000504 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_FailedOverloadResolution:
506 break;
507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000509 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000511
512const TemplateArgument *
513OverloadCandidate::DeductionFailureInfo::getSecondArg() {
514 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
515 case Sema::TDK_Success:
516 case Sema::TDK_InstantiationDepth:
517 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000518 case Sema::TDK_TooManyArguments:
519 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000520 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000521 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000522 return 0;
523
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000524 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000525 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000526 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
527
Douglas Gregor461761d2010-05-08 18:20:53 +0000528 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000529 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 case Sema::TDK_FailedOverloadResolution:
531 break;
532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000534 return 0;
535}
536
537void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000538 inherited::clear();
539 Functions.clear();
540}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000541
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000543// overload of the declarations in Old. This routine returns false if
544// New and Old cannot be overloaded, e.g., if New has the same
545// signature as some function in Old (C++ 1.3.10) or if the Old
546// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000547// it does return false, MatchedDecl will point to the decl that New
548// cannot be overloaded with. This decl may be a UsingShadowDecl on
549// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550//
551// Example: Given the following input:
552//
553// void f(int, float); // #1
554// void f(int, int); // #2
555// int f(int, int); // #3
556//
557// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000558// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000559//
John McCall3d988d92009-12-02 08:47:38 +0000560// When we process #2, Old contains only the FunctionDecl for #1. By
561// comparing the parameter types, we see that #1 and #2 are overloaded
562// (since they have different signatures), so this routine returns
563// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000564//
John McCall3d988d92009-12-02 08:47:38 +0000565// When we process #3, Old is an overload set containing #1 and #2. We
566// compare the signatures of #3 to #1 (they're overloaded, so we do
567// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
568// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569// signature), IsOverload returns false and MatchedDecl will be set to
570// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000571//
572// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
573// into a class by a using declaration. The rules for whether to hide
574// shadow declarations ignore some properties which otherwise figure
575// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000576Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000577Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
578 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000579 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000580 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000581 NamedDecl *OldD = *I;
582
583 bool OldIsUsingDecl = false;
584 if (isa<UsingShadowDecl>(OldD)) {
585 OldIsUsingDecl = true;
586
587 // We can always introduce two using declarations into the same
588 // context, even if they have identical signatures.
589 if (NewIsUsingDecl) continue;
590
591 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
592 }
593
594 // If either declaration was introduced by a using declaration,
595 // we'll need to use slightly different rules for matching.
596 // Essentially, these rules are the normal rules, except that
597 // function templates hide function templates with different
598 // return types or template parameter lists.
599 bool UseMemberUsingDeclRules =
600 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
601
John McCall3d988d92009-12-02 08:47:38 +0000602 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000603 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
604 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
605 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
606 continue;
607 }
608
John McCalldaa3d6b2009-12-09 03:35:25 +0000609 Match = *I;
610 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000611 }
John McCall3d988d92009-12-02 08:47:38 +0000612 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000613 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
614 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
615 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
616 continue;
617 }
618
John McCalldaa3d6b2009-12-09 03:35:25 +0000619 Match = *I;
620 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000621 }
John McCalla8987a2942010-11-10 03:01:53 +0000622 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000623 // We can overload with these, which can show up when doing
624 // redeclaration checks for UsingDecls.
625 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000626 } else if (isa<TagDecl>(OldD)) {
627 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000628 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
629 // Optimistically assume that an unresolved using decl will
630 // overload; if it doesn't, we'll have to diagnose during
631 // template instantiation.
632 } else {
John McCall1f82f242009-11-18 22:49:29 +0000633 // (C++ 13p1):
634 // Only function declarations can be overloaded; object and type
635 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000636 Match = *I;
637 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000638 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000639 }
John McCall1f82f242009-11-18 22:49:29 +0000640
John McCalldaa3d6b2009-12-09 03:35:25 +0000641 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000642}
643
John McCalle9cccd82010-06-16 08:42:20 +0000644bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
645 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000646 // If both of the functions are extern "C", then they are not
647 // overloads.
648 if (Old->isExternC() && New->isExternC())
649 return false;
650
John McCall1f82f242009-11-18 22:49:29 +0000651 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
652 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
653
654 // C++ [temp.fct]p2:
655 // A function template can be overloaded with other function templates
656 // and with normal (non-template) functions.
657 if ((OldTemplate == 0) != (NewTemplate == 0))
658 return true;
659
660 // Is the function New an overload of the function Old?
661 QualType OldQType = Context.getCanonicalType(Old->getType());
662 QualType NewQType = Context.getCanonicalType(New->getType());
663
664 // Compare the signatures (C++ 1.3.10) of the two functions to
665 // determine whether they are overloads. If we find any mismatch
666 // in the signature, they are overloads.
667
668 // If either of these functions is a K&R-style function (no
669 // prototype), then we consider them to have matching signatures.
670 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
671 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
672 return false;
673
John McCall424cec92011-01-19 06:33:43 +0000674 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
675 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000676
677 // The signature of a function includes the types of its
678 // parameters (C++ 1.3.10), which includes the presence or absence
679 // of the ellipsis; see C++ DR 357).
680 if (OldQType != NewQType &&
681 (OldType->getNumArgs() != NewType->getNumArgs() ||
682 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000683 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000684 return true;
685
686 // C++ [temp.over.link]p4:
687 // The signature of a function template consists of its function
688 // signature, its return type and its template parameter list. The names
689 // of the template parameters are significant only for establishing the
690 // relationship between the template parameters and the rest of the
691 // signature.
692 //
693 // We check the return type and template parameter lists for function
694 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000695 //
696 // However, we don't consider either of these when deciding whether
697 // a member introduced by a shadow declaration is hidden.
698 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000699 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
700 OldTemplate->getTemplateParameters(),
701 false, TPL_TemplateMatch) ||
702 OldType->getResultType() != NewType->getResultType()))
703 return true;
704
705 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000706 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000707 //
708 // As part of this, also check whether one of the member functions
709 // is static, in which case they are not overloads (C++
710 // 13.1p2). While not part of the definition of the signature,
711 // this check is important to determine whether these functions
712 // can be overloaded.
713 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
714 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
715 if (OldMethod && NewMethod &&
716 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000717 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000718 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
719 if (!UseUsingDeclRules &&
720 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
721 (OldMethod->getRefQualifier() == RQ_None ||
722 NewMethod->getRefQualifier() == RQ_None)) {
723 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 // - Member function declarations with the same name and the same
725 // parameter-type-list as well as member function template
726 // declarations with the same name, the same parameter-type-list, and
727 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000728 // them, but not all, have a ref-qualifier (8.3.5).
729 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
730 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
731 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733
John McCall1f82f242009-11-18 22:49:29 +0000734 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736
John McCall1f82f242009-11-18 22:49:29 +0000737 // The signatures match; this is not an overload.
738 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739}
740
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000741/// \brief Checks availability of the function depending on the current
742/// function context. Inside an unavailable function, unavailability is ignored.
743///
744/// \returns true if \arg FD is unavailable and current context is inside
745/// an available function, false otherwise.
746bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
747 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
748}
749
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000750/// TryImplicitConversion - Attempt to perform an implicit conversion
751/// from the given expression (Expr) to the given type (ToType). This
752/// function returns an implicit conversion sequence that can be used
753/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754///
755/// void f(float f);
756/// void g(int i) { f(i); }
757///
758/// this routine would produce an implicit conversion sequence to
759/// describe the initialization of f from i, which will be a standard
760/// conversion sequence containing an lvalue-to-rvalue conversion (C++
761/// 4.1) followed by a floating-integral conversion (C++ 4.9).
762//
763/// Note that this routine only determines how the conversion can be
764/// performed; it does not actually perform the conversion. As such,
765/// it will not produce any diagnostics if no conversion is available,
766/// but will instead return an implicit conversion sequence of kind
767/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000768///
769/// If @p SuppressUserConversions, then user-defined conversions are
770/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000771/// If @p AllowExplicit, then explicit user-defined conversions are
772/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000773///
774/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
775/// writeback conversion, which allows __autoreleasing id* parameters to
776/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000777static ImplicitConversionSequence
778TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
779 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000781 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000782 bool CStyle,
783 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000785 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000786 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000787 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000788 return ICS;
789 }
790
John McCall5c32be02010-08-24 20:38:10 +0000791 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000792 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000793 return ICS;
794 }
795
Douglas Gregor836a7e82010-08-11 02:15:33 +0000796 // C++ [over.ics.user]p4:
797 // A conversion of an expression of class type to the same class
798 // type is given Exact Match rank, and a conversion of an
799 // expression of class type to a base class of that type is
800 // given Conversion rank, in spite of the fact that a copy/move
801 // constructor (i.e., a user-defined conversion function) is
802 // called for those cases.
803 QualType FromType = From->getType();
804 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000805 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
806 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000807 ICS.setStandard();
808 ICS.Standard.setAsIdentityConversion();
809 ICS.Standard.setFromType(FromType);
810 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
Douglas Gregor5ab11652010-04-17 22:01:05 +0000812 // We don't actually check at this point whether there is a valid
813 // copy/move constructor, since overloading just assumes that it
814 // exists. When we actually perform initialization, we'll find the
815 // appropriate constructor to copy the returned object, if needed.
816 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Douglas Gregor5ab11652010-04-17 22:01:05 +0000818 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000819 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000820 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821
Douglas Gregor836a7e82010-08-11 02:15:33 +0000822 return ICS;
823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Douglas Gregor836a7e82010-08-11 02:15:33 +0000825 if (SuppressUserConversions) {
826 // We're not in the case above, so there is no conversion that
827 // we can perform.
828 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000829 return ICS;
830 }
831
832 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000833 OverloadCandidateSet Conversions(From->getExprLoc());
834 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000835 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000836 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000837
838 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000839 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000840 // C++ [over.ics.user]p4:
841 // A conversion of an expression of class type to the same class
842 // type is given Exact Match rank, and a conversion of an
843 // expression of class type to a base class of that type is
844 // given Conversion rank, in spite of the fact that a copy
845 // constructor (i.e., a user-defined conversion function) is
846 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000847 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000848 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000849 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000850 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
851 QualType ToCanon
852 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000853 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000854 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000855 // Turn this into a "standard" conversion sequence, so that it
856 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000857 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000858 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000859 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000860 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000861 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000862 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000863 ICS.Standard.Second = ICK_Derived_To_Base;
864 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000865 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000866
867 // C++ [over.best.ics]p4:
868 // However, when considering the argument of a user-defined
869 // conversion function that is a candidate by 13.3.1.3 when
870 // invoked for the copying of the temporary in the second step
871 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
872 // 13.3.1.6 in all cases, only standard conversion sequences and
873 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000874 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000875 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000876 }
John McCalle8c8cd22010-01-13 22:30:33 +0000877 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000878 ICS.setAmbiguous();
879 ICS.Ambiguous.setFromType(From->getType());
880 ICS.Ambiguous.setToType(ToType);
881 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
882 Cand != Conversions.end(); ++Cand)
883 if (Cand->Viable)
884 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000885 } else {
John McCall65eb8792010-02-25 01:37:24 +0000886 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000887 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000888
889 return ICS;
890}
891
John McCall31168b02011-06-15 23:02:42 +0000892ImplicitConversionSequence
893Sema::TryImplicitConversion(Expr *From, QualType ToType,
894 bool SuppressUserConversions,
895 bool AllowExplicit,
896 bool InOverloadResolution,
897 bool CStyle,
898 bool AllowObjCWritebackConversion) {
899 return clang::TryImplicitConversion(*this, From, ToType,
900 SuppressUserConversions, AllowExplicit,
901 InOverloadResolution, CStyle,
902 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000903}
904
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000905/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000906/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000907/// converted expression. Flavor is the kind of conversion we're
908/// performing, used in the error message. If @p AllowExplicit,
909/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000910ExprResult
911Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000912 AssignmentAction Action, bool AllowExplicit,
913 bool Diagnose) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000914 ImplicitConversionSequence ICS;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000915 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS,
916 Diagnose);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000917}
918
John Wiegley01296292011-04-08 18:41:53 +0000919ExprResult
920Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000921 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000922 ImplicitConversionSequence& ICS,
923 bool Diagnose) {
John McCall31168b02011-06-15 23:02:42 +0000924 // Objective-C ARC: Determine whether we will allow the writeback conversion.
925 bool AllowObjCWritebackConversion
926 = getLangOptions().ObjCAutoRefCount &&
927 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +0000928
John McCall5c32be02010-08-24 20:38:10 +0000929 ICS = clang::TryImplicitConversion(*this, From, ToType,
930 /*SuppressUserConversions=*/false,
931 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000932 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +0000933 /*CStyle=*/false,
934 AllowObjCWritebackConversion);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000935 if (!Diagnose && ICS.isFailure())
936 return ExprError();
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000937 return PerformImplicitConversion(From, ToType, ICS, Action);
938}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000939
940/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000941/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +0000942bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
943 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000944 if (Context.hasSameUnqualifiedType(FromType, ToType))
945 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946
John McCall991eb4b2010-12-21 00:44:39 +0000947 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
948 // where F adds one of the following at most once:
949 // - a pointer
950 // - a member pointer
951 // - a block pointer
952 CanQualType CanTo = Context.getCanonicalType(ToType);
953 CanQualType CanFrom = Context.getCanonicalType(FromType);
954 Type::TypeClass TyClass = CanTo->getTypeClass();
955 if (TyClass != CanFrom->getTypeClass()) return false;
956 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
957 if (TyClass == Type::Pointer) {
958 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
959 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
960 } else if (TyClass == Type::BlockPointer) {
961 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
962 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
963 } else if (TyClass == Type::MemberPointer) {
964 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
965 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
966 } else {
967 return false;
968 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000969
John McCall991eb4b2010-12-21 00:44:39 +0000970 TyClass = CanTo->getTypeClass();
971 if (TyClass != CanFrom->getTypeClass()) return false;
972 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
973 return false;
974 }
975
976 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
977 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
978 if (!EInfo.getNoReturn()) return false;
979
980 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
981 assert(QualType(FromFn, 0).isCanonical());
982 if (QualType(FromFn, 0) != CanTo) return false;
983
984 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000985 return true;
986}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987
Douglas Gregor46188682010-05-18 22:42:18 +0000988/// \brief Determine whether the conversion from FromType to ToType is a valid
989/// vector conversion.
990///
991/// \param ICK Will be set to the vector conversion kind, if this is a vector
992/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993static bool IsVectorConversion(ASTContext &Context, QualType FromType,
994 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000995 // We need at least one of these types to be a vector type to have a vector
996 // conversion.
997 if (!ToType->isVectorType() && !FromType->isVectorType())
998 return false;
999
1000 // Identical types require no conversions.
1001 if (Context.hasSameUnqualifiedType(FromType, ToType))
1002 return false;
1003
1004 // There are no conversions between extended vector types, only identity.
1005 if (ToType->isExtVectorType()) {
1006 // There are no conversions between extended vector types other than the
1007 // identity conversion.
1008 if (FromType->isExtVectorType())
1009 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Douglas Gregor46188682010-05-18 22:42:18 +00001011 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001012 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001013 ICK = ICK_Vector_Splat;
1014 return true;
1015 }
1016 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001017
1018 // We can perform the conversion between vector types in the following cases:
1019 // 1)vector types are equivalent AltiVec and GCC vector types
1020 // 2)lax vector conversions are permitted and the vector types are of the
1021 // same size
1022 if (ToType->isVectorType() && FromType->isVectorType()) {
1023 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001024 (Context.getLangOptions().LaxVectorConversions &&
1025 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001026 ICK = ICK_Vector_Conversion;
1027 return true;
1028 }
Douglas Gregor46188682010-05-18 22:42:18 +00001029 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001030
Douglas Gregor46188682010-05-18 22:42:18 +00001031 return false;
1032}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001034/// IsStandardConversion - Determines whether there is a standard
1035/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1036/// expression From to the type ToType. Standard conversion sequences
1037/// only consider non-class types; for conversions that involve class
1038/// types, use TryImplicitConversion. If a conversion exists, SCS will
1039/// contain the standard conversion sequence required to perform this
1040/// conversion and this routine will return true. Otherwise, this
1041/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001042static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1043 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001044 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001045 bool CStyle,
1046 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001047 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001049 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001050 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001051 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001052 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001053 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001054 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001055
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001057 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001058 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001059 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001060 return false;
1061
Mike Stump11289f42009-09-09 15:08:12 +00001062 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001063 }
1064
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065 // The first conversion can be an lvalue-to-rvalue conversion,
1066 // array-to-pointer conversion, or function-to-pointer conversion
1067 // (C++ 4p1).
1068
John McCall5c32be02010-08-24 20:38:10 +00001069 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001070 DeclAccessPair AccessPair;
1071 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001073 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001074 // We were able to resolve the address of the overloaded function,
1075 // so we can convert to the type of that function.
1076 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001077
1078 // we can sometimes resolve &foo<int> regardless of ToType, so check
1079 // if the type matches (identity) or we are converting to bool
1080 if (!S.Context.hasSameUnqualifiedType(
1081 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1082 QualType resultTy;
1083 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001084 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001085 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1086 // otherwise, only a boolean conversion is standard
1087 if (!ToType->isBooleanType())
1088 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090
Chandler Carruthffce2452011-03-29 08:08:18 +00001091 // Check if the "from" expression is taking the address of an overloaded
1092 // function and recompute the FromType accordingly. Take advantage of the
1093 // fact that non-static member functions *must* have such an address-of
1094 // expression.
1095 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1096 if (Method && !Method->isStatic()) {
1097 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1098 "Non-unary operator on non-static member address");
1099 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1100 == UO_AddrOf &&
1101 "Non-address-of operator on non-static member address");
1102 const Type *ClassType
1103 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1104 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001105 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1106 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1107 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001108 "Non-address-of operator for overloaded function expression");
1109 FromType = S.Context.getPointerType(FromType);
1110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001111
Douglas Gregor980fb162010-04-29 18:24:40 +00001112 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001113 assert(S.Context.hasSameType(
1114 FromType,
1115 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001116 } else {
1117 return false;
1118 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001119 }
John McCall154a2fd2011-08-30 00:57:29 +00001120 // Lvalue-to-rvalue conversion (C++11 4.1):
1121 // A glvalue (3.10) of a non-function, non-array type T can
1122 // be converted to a prvalue.
1123 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001124 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001125 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001126 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001127 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128
1129 // If T is a non-class type, the type of the rvalue is the
1130 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001131 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1132 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001133 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001134 } else if (FromType->isArrayType()) {
1135 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001136 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001137
1138 // An lvalue or rvalue of type "array of N T" or "array of unknown
1139 // bound of T" can be converted to an rvalue of type "pointer to
1140 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001141 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142
John McCall5c32be02010-08-24 20:38:10 +00001143 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001144 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001145 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001146
1147 // For the purpose of ranking in overload resolution
1148 // (13.3.3.1.1), this conversion is considered an
1149 // array-to-pointer conversion followed by a qualification
1150 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001151 SCS.Second = ICK_Identity;
1152 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001153 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001154 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001156 }
John McCall086a4642010-11-24 05:12:34 +00001157 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001158 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001159 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001160
1161 // An lvalue of function type T can be converted to an rvalue of
1162 // type "pointer to T." The result is a pointer to the
1163 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001164 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001165 } else {
1166 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001167 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001169 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
1171 // The second conversion can be an integral promotion, floating
1172 // point promotion, integral conversion, floating point conversion,
1173 // floating-integral conversion, pointer conversion,
1174 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001175 // For overloading in C, this can also be a "compatible-type"
1176 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001177 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001178 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001179 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 // The unqualified versions of the types are the same: there's no
1181 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001182 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001183 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001184 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001185 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001186 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001187 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001188 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001189 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001190 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001191 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001192 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001193 SCS.Second = ICK_Complex_Promotion;
1194 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001195 } else if (ToType->isBooleanType() &&
1196 (FromType->isArithmeticType() ||
1197 FromType->isAnyPointerType() ||
1198 FromType->isBlockPointerType() ||
1199 FromType->isMemberPointerType() ||
1200 FromType->isNullPtrType())) {
1201 // Boolean conversions (C++ 4.12).
1202 SCS.Second = ICK_Boolean_Conversion;
1203 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001204 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001205 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001206 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001207 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001208 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001209 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001210 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001211 SCS.Second = ICK_Complex_Conversion;
1212 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001213 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1214 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001215 // Complex-real conversions (C99 6.3.1.7)
1216 SCS.Second = ICK_Complex_Real;
1217 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001218 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001219 // Floating point conversions (C++ 4.8).
1220 SCS.Second = ICK_Floating_Conversion;
1221 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001222 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001223 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001224 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001225 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001226 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001227 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001229 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001230 SCS.Second = ICK_Block_Pointer_Conversion;
1231 } else if (AllowObjCWritebackConversion &&
1232 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1233 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001234 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1235 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001236 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001237 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001238 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001239 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001241 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001242 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001243 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001244 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001245 SCS.Second = SecondICK;
1246 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001247 } else if (!S.getLangOptions().CPlusPlus &&
1248 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001249 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001250 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001251 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001252 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001253 // Treat a conversion that strips "noreturn" as an identity conversion.
1254 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001255 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1256 InOverloadResolution,
1257 SCS, CStyle)) {
1258 SCS.Second = ICK_TransparentUnionConversion;
1259 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001260 } else {
1261 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001262 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001263 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001264 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001265
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001266 QualType CanonFrom;
1267 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001268 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001269 bool ObjCLifetimeConversion;
1270 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1271 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001272 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001273 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001274 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001275 CanonFrom = S.Context.getCanonicalType(FromType);
1276 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001277 } else {
1278 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001279 SCS.Third = ICK_Identity;
1280
Mike Stump11289f42009-09-09 15:08:12 +00001281 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001282 // [...] Any difference in top-level cv-qualification is
1283 // subsumed by the initialization itself and does not constitute
1284 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001285 CanonFrom = S.Context.getCanonicalType(FromType);
1286 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001288 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001289 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001290 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1291 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001292 FromType = ToType;
1293 CanonFrom = CanonTo;
1294 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001295 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001296 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297
1298 // If we have not converted the argument type to the parameter type,
1299 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001300 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001301 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001303 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001305
1306static bool
1307IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1308 QualType &ToType,
1309 bool InOverloadResolution,
1310 StandardConversionSequence &SCS,
1311 bool CStyle) {
1312
1313 const RecordType *UT = ToType->getAsUnionType();
1314 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1315 return false;
1316 // The field to initialize within the transparent union.
1317 RecordDecl *UD = UT->getDecl();
1318 // It's compatible if the expression matches any of the fields.
1319 for (RecordDecl::field_iterator it = UD->field_begin(),
1320 itend = UD->field_end();
1321 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001322 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1323 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001324 ToType = it->getType();
1325 return true;
1326 }
1327 }
1328 return false;
1329}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001330
1331/// IsIntegralPromotion - Determines whether the conversion from the
1332/// expression From (whose potentially-adjusted type is FromType) to
1333/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1334/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001335bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001336 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001337 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001338 if (!To) {
1339 return false;
1340 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001341
1342 // An rvalue of type char, signed char, unsigned char, short int, or
1343 // unsigned short int can be converted to an rvalue of type int if
1344 // int can represent all the values of the source type; otherwise,
1345 // the source rvalue can be converted to an rvalue of type unsigned
1346 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001347 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1348 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349 if (// We can promote any signed, promotable integer type to an int
1350 (FromType->isSignedIntegerType() ||
1351 // We can promote any unsigned integer type whose size is
1352 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001353 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001354 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001355 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001356 }
1357
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001358 return To->getKind() == BuiltinType::UInt;
1359 }
1360
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361 // C++0x [conv.prom]p3:
1362 // A prvalue of an unscoped enumeration type whose underlying type is not
1363 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1364 // following types that can represent all the values of the enumeration
1365 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1366 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001367 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001369 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370 // with lowest integer conversion rank (4.13) greater than the rank of long
1371 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001372 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001373 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1374 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1375 // provided for a scoped enumeration.
1376 if (FromEnumType->getDecl()->isScoped())
1377 return false;
1378
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001379 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001381 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001382 return Context.hasSameUnqualifiedType(ToType,
1383 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001384 }
John McCall56774992009-12-09 09:09:27 +00001385
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001386 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1388 // to an rvalue a prvalue of the first of the following types that can
1389 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001390 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001392 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001394 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001396 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001397 // Determine whether the type we're converting from is signed or
1398 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001399 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001402 // The types we'll try to promote to, in the appropriate
1403 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001404 QualType PromoteTypes[6] = {
1405 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001406 Context.LongTy, Context.UnsignedLongTy ,
1407 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001408 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001409 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001410 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1411 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001412 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001413 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1414 // We found the type that we can promote to. If this is the
1415 // type we wanted, we have a promotion. Otherwise, no
1416 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001417 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001418 }
1419 }
1420 }
1421
1422 // An rvalue for an integral bit-field (9.6) can be converted to an
1423 // rvalue of type int if int can represent all the values of the
1424 // bit-field; otherwise, it can be converted to unsigned int if
1425 // unsigned int can represent all the values of the bit-field. If
1426 // the bit-field is larger yet, no integral promotion applies to
1427 // it. If the bit-field has an enumerated type, it is treated as any
1428 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001429 // FIXME: We should delay checking of bit-fields until we actually perform the
1430 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001431 using llvm::APSInt;
1432 if (From)
1433 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001434 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001435 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001436 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1437 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1438 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001439
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001440 // Are we promoting to an int from a bitfield that fits in an int?
1441 if (BitWidth < ToSize ||
1442 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1443 return To->getKind() == BuiltinType::Int;
1444 }
Mike Stump11289f42009-09-09 15:08:12 +00001445
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001446 // Are we promoting to an unsigned int from an unsigned bitfield
1447 // that fits into an unsigned int?
1448 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1449 return To->getKind() == BuiltinType::UInt;
1450 }
Mike Stump11289f42009-09-09 15:08:12 +00001451
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001452 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001453 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001454 }
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001456 // An rvalue of type bool can be converted to an rvalue of type int,
1457 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001458 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001460 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001461
1462 return false;
1463}
1464
1465/// IsFloatingPointPromotion - Determines whether the conversion from
1466/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1467/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001468bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001469 /// An rvalue of type float can be converted to an rvalue of type
1470 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001471 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1472 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001473 if (FromBuiltin->getKind() == BuiltinType::Float &&
1474 ToBuiltin->getKind() == BuiltinType::Double)
1475 return true;
1476
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001477 // C99 6.3.1.5p1:
1478 // When a float is promoted to double or long double, or a
1479 // double is promoted to long double [...].
1480 if (!getLangOptions().CPlusPlus &&
1481 (FromBuiltin->getKind() == BuiltinType::Float ||
1482 FromBuiltin->getKind() == BuiltinType::Double) &&
1483 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1484 return true;
1485 }
1486
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001487 return false;
1488}
1489
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001490/// \brief Determine if a conversion is a complex promotion.
1491///
1492/// A complex promotion is defined as a complex -> complex conversion
1493/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001494/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001495bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001496 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001497 if (!FromComplex)
1498 return false;
1499
John McCall9dd450b2009-09-21 23:43:11 +00001500 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001501 if (!ToComplex)
1502 return false;
1503
1504 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001505 ToComplex->getElementType()) ||
1506 IsIntegralPromotion(0, FromComplex->getElementType(),
1507 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001508}
1509
Douglas Gregor237f96c2008-11-26 23:31:11 +00001510/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1511/// the pointer type FromPtr to a pointer to type ToPointee, with the
1512/// same type qualifiers as FromPtr has on its pointee type. ToType,
1513/// if non-empty, will be a pointer to ToType that may or may not have
1514/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001515///
Mike Stump11289f42009-09-09 15:08:12 +00001516static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001517BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001518 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001519 ASTContext &Context,
1520 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001521 assert((FromPtr->getTypeClass() == Type::Pointer ||
1522 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1523 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524
John McCall31168b02011-06-15 23:02:42 +00001525 /// Conversions to 'id' subsume cv-qualifier conversions.
1526 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001527 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001528
1529 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001530 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001531 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001532 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001533
John McCall31168b02011-06-15 23:02:42 +00001534 if (StripObjCLifetime)
1535 Quals.removeObjCLifetime();
1536
Mike Stump11289f42009-09-09 15:08:12 +00001537 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001538 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001539 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001540 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001541 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001542
1543 // Build a pointer to ToPointee. It has the right qualifiers
1544 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001545 if (isa<ObjCObjectPointerType>(ToType))
1546 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001547 return Context.getPointerType(ToPointee);
1548 }
1549
1550 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001551 QualType QualifiedCanonToPointee
1552 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001554 if (isa<ObjCObjectPointerType>(ToType))
1555 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1556 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001557}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558
Mike Stump11289f42009-09-09 15:08:12 +00001559static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001560 bool InOverloadResolution,
1561 ASTContext &Context) {
1562 // Handle value-dependent integral null pointer constants correctly.
1563 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1564 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001565 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001566 return !InOverloadResolution;
1567
Douglas Gregor56751b52009-09-25 04:25:58 +00001568 return Expr->isNullPointerConstant(Context,
1569 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1570 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001571}
Mike Stump11289f42009-09-09 15:08:12 +00001572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573/// IsPointerConversion - Determines whether the conversion of the
1574/// expression From, which has the (possibly adjusted) type FromType,
1575/// can be converted to the type ToType via a pointer conversion (C++
1576/// 4.10). If so, returns true and places the converted type (that
1577/// might differ from ToType in its cv-qualifiers at some level) into
1578/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001579///
Douglas Gregora29dc052008-11-27 01:19:21 +00001580/// This routine also supports conversions to and from block pointers
1581/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1582/// pointers to interfaces. FIXME: Once we've determined the
1583/// appropriate overloading rules for Objective-C, we may want to
1584/// split the Objective-C checks into a different routine; however,
1585/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001586/// conversions, so for now they live here. IncompatibleObjC will be
1587/// set if the conversion is an allowed Objective-C conversion that
1588/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001590 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001591 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001592 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001593 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001594 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1595 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001596 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001597
Mike Stump11289f42009-09-09 15:08:12 +00001598 // Conversion from a null pointer constant to any Objective-C pointer type.
1599 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001600 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001601 ConvertedType = ToType;
1602 return true;
1603 }
1604
Douglas Gregor231d1c62008-11-27 00:15:41 +00001605 // Blocks: Block pointers can be converted to void*.
1606 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001607 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001608 ConvertedType = ToType;
1609 return true;
1610 }
1611 // Blocks: A null pointer constant can be converted to a block
1612 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001613 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001614 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001615 ConvertedType = ToType;
1616 return true;
1617 }
1618
Sebastian Redl576fd422009-05-10 18:38:11 +00001619 // If the left-hand-side is nullptr_t, the right side can be a null
1620 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001621 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001622 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001623 ConvertedType = ToType;
1624 return true;
1625 }
1626
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001627 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 if (!ToTypePtr)
1629 return false;
1630
1631 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001632 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001633 ConvertedType = ToType;
1634 return true;
1635 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001638 // , including objective-c pointers.
1639 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001640 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1641 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001642 ConvertedType = BuildSimilarlyQualifiedPointerType(
1643 FromType->getAs<ObjCObjectPointerType>(),
1644 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001645 ToType, Context);
1646 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001647 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001648 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001649 if (!FromTypePtr)
1650 return false;
1651
1652 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001653
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001655 // pointer conversion, so don't do all of the work below.
1656 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1657 return false;
1658
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659 // An rvalue of type "pointer to cv T," where T is an object type,
1660 // can be converted to an rvalue of type "pointer to cv void" (C++
1661 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001662 if (FromPointeeType->isIncompleteOrObjectType() &&
1663 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001664 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001665 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001666 ToType, Context,
1667 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668 return true;
1669 }
1670
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001671 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001672 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001673 ToPointeeType->isVoidType()) {
1674 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1675 ToPointeeType,
1676 ToType, Context);
1677 return true;
1678 }
1679
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001680 // When we're overloading in C, we allow a special kind of pointer
1681 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001682 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001683 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001684 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001685 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001686 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001687 return true;
1688 }
1689
Douglas Gregor5c407d92008-10-23 00:40:37 +00001690 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001691 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001692 // An rvalue of type "pointer to cv D," where D is a class type,
1693 // can be converted to an rvalue of type "pointer to cv B," where
1694 // B is a base class (clause 10) of D. If B is an inaccessible
1695 // (clause 11) or ambiguous (10.2) base class of D, a program that
1696 // necessitates this conversion is ill-formed. The result of the
1697 // conversion is a pointer to the base class sub-object of the
1698 // derived class object. The null pointer value is converted to
1699 // the null pointer value of the destination type.
1700 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001701 // Note that we do not check for ambiguity or inaccessibility
1702 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001703 if (getLangOptions().CPlusPlus &&
1704 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001705 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001706 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001707 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001708 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001709 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001710 ToType, Context);
1711 return true;
1712 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001713
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001714 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1715 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1716 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1717 ToPointeeType,
1718 ToType, Context);
1719 return true;
1720 }
1721
Douglas Gregora119f102008-12-19 19:13:09 +00001722 return false;
1723}
Douglas Gregoraec25842011-04-26 23:16:46 +00001724
1725/// \brief Adopt the given qualifiers for the given type.
1726static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1727 Qualifiers TQs = T.getQualifiers();
1728
1729 // Check whether qualifiers already match.
1730 if (TQs == Qs)
1731 return T;
1732
1733 if (Qs.compatiblyIncludes(TQs))
1734 return Context.getQualifiedType(T, Qs);
1735
1736 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1737}
Douglas Gregora119f102008-12-19 19:13:09 +00001738
1739/// isObjCPointerConversion - Determines whether this is an
1740/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1741/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001742bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001743 QualType& ConvertedType,
1744 bool &IncompatibleObjC) {
1745 if (!getLangOptions().ObjC1)
1746 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001747
Douglas Gregoraec25842011-04-26 23:16:46 +00001748 // The set of qualifiers on the type we're converting from.
1749 Qualifiers FromQualifiers = FromType.getQualifiers();
1750
Steve Naroff7cae42b2009-07-10 23:34:53 +00001751 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001752 const ObjCObjectPointerType* ToObjCPtr =
1753 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001754 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001755 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001756
Steve Naroff7cae42b2009-07-10 23:34:53 +00001757 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001758 // If the pointee types are the same (ignoring qualifications),
1759 // then this is not a pointer conversion.
1760 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1761 FromObjCPtr->getPointeeType()))
1762 return false;
1763
Douglas Gregoraec25842011-04-26 23:16:46 +00001764 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001765 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001766 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001767 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001768 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001769 return true;
1770 }
1771 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001772 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001773 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001774 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001775 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001776 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001777 return true;
1778 }
1779 // Objective C++: We're able to convert from a pointer to an
1780 // interface to a pointer to a different interface.
1781 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001782 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1783 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1784 if (getLangOptions().CPlusPlus && LHS && RHS &&
1785 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1786 FromObjCPtr->getPointeeType()))
1787 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001789 ToObjCPtr->getPointeeType(),
1790 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001791 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001792 return true;
1793 }
1794
1795 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1796 // Okay: this is some kind of implicit downcast of Objective-C
1797 // interfaces, which is permitted. However, we're going to
1798 // complain about it.
1799 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001800 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001801 ToObjCPtr->getPointeeType(),
1802 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001803 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001804 return true;
1805 }
Mike Stump11289f42009-09-09 15:08:12 +00001806 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001807 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001808 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001809 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001810 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001812 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001813 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001814 // to a block pointer type.
1815 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001816 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001817 return true;
1818 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001819 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001822 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001824 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001825 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001826 return true;
1827 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001828 else
Douglas Gregora119f102008-12-19 19:13:09 +00001829 return false;
1830
Douglas Gregor033f56d2008-12-23 00:53:59 +00001831 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001832 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001833 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001834 else if (const BlockPointerType *FromBlockPtr =
1835 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001836 FromPointeeType = FromBlockPtr->getPointeeType();
1837 else
Douglas Gregora119f102008-12-19 19:13:09 +00001838 return false;
1839
Douglas Gregora119f102008-12-19 19:13:09 +00001840 // If we have pointers to pointers, recursively check whether this
1841 // is an Objective-C conversion.
1842 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1843 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1844 IncompatibleObjC)) {
1845 // We always complain about this conversion.
1846 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001847 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001848 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001849 return true;
1850 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001851 // Allow conversion of pointee being objective-c pointer to another one;
1852 // as in I* to id.
1853 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1854 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1855 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1856 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001857
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001858 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001859 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001860 return true;
1861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Douglas Gregor033f56d2008-12-23 00:53:59 +00001863 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001864 // differences in the argument and result types are in Objective-C
1865 // pointer conversions. If so, we permit the conversion (but
1866 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001867 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001868 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001869 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001870 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001871 if (FromFunctionType && ToFunctionType) {
1872 // If the function types are exactly the same, this isn't an
1873 // Objective-C pointer conversion.
1874 if (Context.getCanonicalType(FromPointeeType)
1875 == Context.getCanonicalType(ToPointeeType))
1876 return false;
1877
1878 // Perform the quick checks that will tell us whether these
1879 // function types are obviously different.
1880 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1881 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1882 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1883 return false;
1884
1885 bool HasObjCConversion = false;
1886 if (Context.getCanonicalType(FromFunctionType->getResultType())
1887 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1888 // Okay, the types match exactly. Nothing to do.
1889 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1890 ToFunctionType->getResultType(),
1891 ConvertedType, IncompatibleObjC)) {
1892 // Okay, we have an Objective-C pointer conversion.
1893 HasObjCConversion = true;
1894 } else {
1895 // Function types are too different. Abort.
1896 return false;
1897 }
Mike Stump11289f42009-09-09 15:08:12 +00001898
Douglas Gregora119f102008-12-19 19:13:09 +00001899 // Check argument types.
1900 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1901 ArgIdx != NumArgs; ++ArgIdx) {
1902 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1903 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1904 if (Context.getCanonicalType(FromArgType)
1905 == Context.getCanonicalType(ToArgType)) {
1906 // Okay, the types match exactly. Nothing to do.
1907 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1908 ConvertedType, IncompatibleObjC)) {
1909 // Okay, we have an Objective-C pointer conversion.
1910 HasObjCConversion = true;
1911 } else {
1912 // Argument types are too different. Abort.
1913 return false;
1914 }
1915 }
1916
1917 if (HasObjCConversion) {
1918 // We had an Objective-C conversion. Allow this pointer
1919 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001920 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001921 IncompatibleObjC = true;
1922 return true;
1923 }
1924 }
1925
Sebastian Redl72b597d2009-01-25 19:43:20 +00001926 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001927}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928
John McCall31168b02011-06-15 23:02:42 +00001929/// \brief Determine whether this is an Objective-C writeback conversion,
1930/// used for parameter passing when performing automatic reference counting.
1931///
1932/// \param FromType The type we're converting form.
1933///
1934/// \param ToType The type we're converting to.
1935///
1936/// \param ConvertedType The type that will be produced after applying
1937/// this conversion.
1938bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1939 QualType &ConvertedType) {
1940 if (!getLangOptions().ObjCAutoRefCount ||
1941 Context.hasSameUnqualifiedType(FromType, ToType))
1942 return false;
1943
1944 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1945 QualType ToPointee;
1946 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1947 ToPointee = ToPointer->getPointeeType();
1948 else
1949 return false;
1950
1951 Qualifiers ToQuals = ToPointee.getQualifiers();
1952 if (!ToPointee->isObjCLifetimeType() ||
1953 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1954 !ToQuals.withoutObjCGLifetime().empty())
1955 return false;
1956
1957 // Argument must be a pointer to __strong to __weak.
1958 QualType FromPointee;
1959 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1960 FromPointee = FromPointer->getPointeeType();
1961 else
1962 return false;
1963
1964 Qualifiers FromQuals = FromPointee.getQualifiers();
1965 if (!FromPointee->isObjCLifetimeType() ||
1966 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1967 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1968 return false;
1969
1970 // Make sure that we have compatible qualifiers.
1971 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1972 if (!ToQuals.compatiblyIncludes(FromQuals))
1973 return false;
1974
1975 // Remove qualifiers from the pointee type we're converting from; they
1976 // aren't used in the compatibility check belong, and we'll be adding back
1977 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1978 FromPointee = FromPointee.getUnqualifiedType();
1979
1980 // The unqualified form of the pointee types must be compatible.
1981 ToPointee = ToPointee.getUnqualifiedType();
1982 bool IncompatibleObjC;
1983 if (Context.typesAreCompatible(FromPointee, ToPointee))
1984 FromPointee = ToPointee;
1985 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1986 IncompatibleObjC))
1987 return false;
1988
1989 /// \brief Construct the type we're converting to, which is a pointer to
1990 /// __autoreleasing pointee.
1991 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1992 ConvertedType = Context.getPointerType(FromPointee);
1993 return true;
1994}
1995
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001996bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1997 QualType& ConvertedType) {
1998 QualType ToPointeeType;
1999 if (const BlockPointerType *ToBlockPtr =
2000 ToType->getAs<BlockPointerType>())
2001 ToPointeeType = ToBlockPtr->getPointeeType();
2002 else
2003 return false;
2004
2005 QualType FromPointeeType;
2006 if (const BlockPointerType *FromBlockPtr =
2007 FromType->getAs<BlockPointerType>())
2008 FromPointeeType = FromBlockPtr->getPointeeType();
2009 else
2010 return false;
2011 // We have pointer to blocks, check whether the only
2012 // differences in the argument and result types are in Objective-C
2013 // pointer conversions. If so, we permit the conversion.
2014
2015 const FunctionProtoType *FromFunctionType
2016 = FromPointeeType->getAs<FunctionProtoType>();
2017 const FunctionProtoType *ToFunctionType
2018 = ToPointeeType->getAs<FunctionProtoType>();
2019
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002020 if (!FromFunctionType || !ToFunctionType)
2021 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002022
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002023 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002024 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002025
2026 // Perform the quick checks that will tell us whether these
2027 // function types are obviously different.
2028 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2029 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2030 return false;
2031
2032 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2033 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2034 if (FromEInfo != ToEInfo)
2035 return false;
2036
2037 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002038 if (Context.hasSameType(FromFunctionType->getResultType(),
2039 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002040 // Okay, the types match exactly. Nothing to do.
2041 } else {
2042 QualType RHS = FromFunctionType->getResultType();
2043 QualType LHS = ToFunctionType->getResultType();
2044 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2045 !RHS.hasQualifiers() && LHS.hasQualifiers())
2046 LHS = LHS.getUnqualifiedType();
2047
2048 if (Context.hasSameType(RHS,LHS)) {
2049 // OK exact match.
2050 } else if (isObjCPointerConversion(RHS, LHS,
2051 ConvertedType, IncompatibleObjC)) {
2052 if (IncompatibleObjC)
2053 return false;
2054 // Okay, we have an Objective-C pointer conversion.
2055 }
2056 else
2057 return false;
2058 }
2059
2060 // Check argument types.
2061 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2062 ArgIdx != NumArgs; ++ArgIdx) {
2063 IncompatibleObjC = false;
2064 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2065 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2066 if (Context.hasSameType(FromArgType, ToArgType)) {
2067 // Okay, the types match exactly. Nothing to do.
2068 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2069 ConvertedType, IncompatibleObjC)) {
2070 if (IncompatibleObjC)
2071 return false;
2072 // Okay, we have an Objective-C pointer conversion.
2073 } else
2074 // Argument types are too different. Abort.
2075 return false;
2076 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002077 if (LangOpts.ObjCAutoRefCount &&
2078 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2079 ToFunctionType))
2080 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002081
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002082 ConvertedType = ToType;
2083 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002084}
2085
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002086/// FunctionArgTypesAreEqual - This routine checks two function proto types
2087/// for equlity of their argument types. Caller has already checked that
2088/// they have same number of arguments. This routine assumes that Objective-C
2089/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002091 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002092 if (!getLangOptions().ObjC1)
2093 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2094 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002096 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2097 N = NewType->arg_type_begin(),
2098 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2099 QualType ToType = (*O);
2100 QualType FromType = (*N);
2101 if (ToType != FromType) {
2102 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2103 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002104 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2105 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2106 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2107 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002108 continue;
2109 }
John McCall8b07ec22010-05-15 11:32:37 +00002110 else if (const ObjCObjectPointerType *PTTo =
2111 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002113 FromType->getAs<ObjCObjectPointerType>())
2114 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2115 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002117 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002118 }
2119 }
2120 return true;
2121}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002122
Douglas Gregor39c16d42008-10-24 04:54:22 +00002123/// CheckPointerConversion - Check the pointer conversion from the
2124/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002125/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002126/// conversions for which IsPointerConversion has already returned
2127/// true. It returns true and produces a diagnostic if there was an
2128/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002129bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002130 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002131 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002132 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002133 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002134 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002135
John McCall8cb679e2010-11-15 09:13:47 +00002136 Kind = CK_BitCast;
2137
Chandler Carruthffab8732011-04-09 07:32:05 +00002138 if (!IsCStyleOrFunctionalCast &&
2139 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2140 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2141 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002142 PDiag(diag::warn_impcast_bool_to_null_pointer)
2143 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002144
John McCall9320b872011-09-09 05:25:32 +00002145 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2146 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002147 QualType FromPointeeType = FromPtrType->getPointeeType(),
2148 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002149
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002150 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2151 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002152 // We must have a derived-to-base conversion. Check an
2153 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002154 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2155 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002156 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002157 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002158 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002159
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002160 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002161 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002162 }
2163 }
John McCall9320b872011-09-09 05:25:32 +00002164 } else if (const ObjCObjectPointerType *ToPtrType =
2165 ToType->getAs<ObjCObjectPointerType>()) {
2166 if (const ObjCObjectPointerType *FromPtrType =
2167 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002168 // Objective-C++ conversions are always okay.
2169 // FIXME: We should have a different class of conversions for the
2170 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002171 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002172 return false;
John McCall9320b872011-09-09 05:25:32 +00002173 } else if (FromType->isBlockPointerType()) {
2174 Kind = CK_BlockPointerToObjCPointerCast;
2175 } else {
2176 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002177 }
John McCall9320b872011-09-09 05:25:32 +00002178 } else if (ToType->isBlockPointerType()) {
2179 if (!FromType->isBlockPointerType())
2180 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002181 }
John McCall8cb679e2010-11-15 09:13:47 +00002182
2183 // We shouldn't fall into this case unless it's valid for other
2184 // reasons.
2185 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2186 Kind = CK_NullToPointer;
2187
Douglas Gregor39c16d42008-10-24 04:54:22 +00002188 return false;
2189}
2190
Sebastian Redl72b597d2009-01-25 19:43:20 +00002191/// IsMemberPointerConversion - Determines whether the conversion of the
2192/// expression From, which has the (possibly adjusted) type FromType, can be
2193/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2194/// If so, returns true and places the converted type (that might differ from
2195/// ToType in its cv-qualifiers at some level) into ConvertedType.
2196bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002198 bool InOverloadResolution,
2199 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002200 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002201 if (!ToTypePtr)
2202 return false;
2203
2204 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002205 if (From->isNullPointerConstant(Context,
2206 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2207 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002208 ConvertedType = ToType;
2209 return true;
2210 }
2211
2212 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002213 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002214 if (!FromTypePtr)
2215 return false;
2216
2217 // A pointer to member of B can be converted to a pointer to member of D,
2218 // where D is derived from B (C++ 4.11p2).
2219 QualType FromClass(FromTypePtr->getClass(), 0);
2220 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002221
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002222 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2223 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2224 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002225 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2226 ToClass.getTypePtr());
2227 return true;
2228 }
2229
2230 return false;
2231}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002232
Sebastian Redl72b597d2009-01-25 19:43:20 +00002233/// CheckMemberPointerConversion - Check the member pointer conversion from the
2234/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002235/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002236/// for which IsMemberPointerConversion has already returned true. It returns
2237/// true and produces a diagnostic if there was an error, or returns false
2238/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002239bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002240 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002241 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002242 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002243 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002244 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002245 if (!FromPtrType) {
2246 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002247 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002248 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002249 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002250 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002251 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002252 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002253
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002254 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002255 assert(ToPtrType && "No member pointer cast has a target type "
2256 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002257
Sebastian Redled8f2002009-01-28 18:33:18 +00002258 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2259 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002260
Sebastian Redled8f2002009-01-28 18:33:18 +00002261 // FIXME: What about dependent types?
2262 assert(FromClass->isRecordType() && "Pointer into non-class.");
2263 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002264
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002265 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002266 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002267 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2268 assert(DerivationOkay &&
2269 "Should not have been called if derivation isn't OK.");
2270 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002271
Sebastian Redled8f2002009-01-28 18:33:18 +00002272 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2273 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002274 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2275 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2276 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2277 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002278 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002279
Douglas Gregor89ee6822009-02-28 01:32:25 +00002280 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002281 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2282 << FromClass << ToClass << QualType(VBase, 0)
2283 << From->getSourceRange();
2284 return true;
2285 }
2286
John McCall5b0829a2010-02-10 09:31:12 +00002287 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002288 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2289 Paths.front(),
2290 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002291
Anders Carlssond7923c62009-08-22 23:33:40 +00002292 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002293 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002294 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002295 return false;
2296}
2297
Douglas Gregor9a657932008-10-21 23:43:52 +00002298/// IsQualificationConversion - Determines whether the conversion from
2299/// an rvalue of type FromType to ToType is a qualification conversion
2300/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002301///
2302/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2303/// when the qualification conversion involves a change in the Objective-C
2304/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002305bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002306Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002307 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002308 FromType = Context.getCanonicalType(FromType);
2309 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002310 ObjCLifetimeConversion = false;
2311
Douglas Gregor9a657932008-10-21 23:43:52 +00002312 // If FromType and ToType are the same type, this is not a
2313 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002314 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002315 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002316
Douglas Gregor9a657932008-10-21 23:43:52 +00002317 // (C++ 4.4p4):
2318 // A conversion can add cv-qualifiers at levels other than the first
2319 // in multi-level pointers, subject to the following rules: [...]
2320 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002321 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002322 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002323 // Within each iteration of the loop, we check the qualifiers to
2324 // determine if this still looks like a qualification
2325 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002326 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002327 // until there are no more pointers or pointers-to-members left to
2328 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002329 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002330
Douglas Gregor90609aa2011-04-25 18:40:17 +00002331 Qualifiers FromQuals = FromType.getQualifiers();
2332 Qualifiers ToQuals = ToType.getQualifiers();
2333
John McCall31168b02011-06-15 23:02:42 +00002334 // Objective-C ARC:
2335 // Check Objective-C lifetime conversions.
2336 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2337 UnwrappedAnyPointer) {
2338 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2339 ObjCLifetimeConversion = true;
2340 FromQuals.removeObjCLifetime();
2341 ToQuals.removeObjCLifetime();
2342 } else {
2343 // Qualification conversions cannot cast between different
2344 // Objective-C lifetime qualifiers.
2345 return false;
2346 }
2347 }
2348
Douglas Gregorf30053d2011-05-08 06:09:53 +00002349 // Allow addition/removal of GC attributes but not changing GC attributes.
2350 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2351 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2352 FromQuals.removeObjCGCAttr();
2353 ToQuals.removeObjCGCAttr();
2354 }
2355
Douglas Gregor9a657932008-10-21 23:43:52 +00002356 // -- for every j > 0, if const is in cv 1,j then const is in cv
2357 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002358 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002359 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002360
Douglas Gregor9a657932008-10-21 23:43:52 +00002361 // -- if the cv 1,j and cv 2,j are different, then const is in
2362 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002363 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002364 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002365 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002366
Douglas Gregor9a657932008-10-21 23:43:52 +00002367 // Keep track of whether all prior cv-qualifiers in the "to" type
2368 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002369 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002370 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002371 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002372
2373 // We are left with FromType and ToType being the pointee types
2374 // after unwrapping the original FromType and ToType the same number
2375 // of types. If we unwrapped any pointers, and if FromType and
2376 // ToType have the same unqualified type (since we checked
2377 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002378 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002379}
2380
Douglas Gregor576e98c2009-01-30 23:27:23 +00002381/// Determines whether there is a user-defined conversion sequence
2382/// (C++ [over.ics.user]) that converts expression From to the type
2383/// ToType. If such a conversion exists, User will contain the
2384/// user-defined conversion sequence that performs such a conversion
2385/// and this routine will return true. Otherwise, this routine returns
2386/// false and User is unspecified.
2387///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002388/// \param AllowExplicit true if the conversion should consider C++0x
2389/// "explicit" conversion functions as well as non-explicit conversion
2390/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002391static OverloadingResult
2392IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2393 UserDefinedConversionSequence& User,
2394 OverloadCandidateSet& CandidateSet,
2395 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002396 // Whether we will only visit constructors.
2397 bool ConstructorsOnly = false;
2398
2399 // If the type we are conversion to is a class type, enumerate its
2400 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002401 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002402 // C++ [over.match.ctor]p1:
2403 // When objects of class type are direct-initialized (8.5), or
2404 // copy-initialized from an expression of the same or a
2405 // derived class type (8.5), overload resolution selects the
2406 // constructor. [...] For copy-initialization, the candidate
2407 // functions are all the converting constructors (12.3.1) of
2408 // that class. The argument list is the expression-list within
2409 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002410 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002411 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002412 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002413 ConstructorsOnly = true;
2414
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002415 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2416 // RequireCompleteType may have returned true due to some invalid decl
2417 // during template instantiation, but ToType may be complete enough now
2418 // to try to recover.
2419 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002420 // We're not going to find any constructors.
2421 } else if (CXXRecordDecl *ToRecordDecl
2422 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002423 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002424 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002425 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002426 NamedDecl *D = *Con;
2427 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2428
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002429 // Find the constructor (which may be a template).
2430 CXXConstructorDecl *Constructor = 0;
2431 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002432 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002433 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002434 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002435 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2436 else
John McCalla0296f72010-03-19 07:35:19 +00002437 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002438
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002439 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002440 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002441 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002442 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2443 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002444 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002445 /*SuppressUserConversions=*/
2446 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002447 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002448 // Allow one user-defined conversion when user specifies a
2449 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002450 S.AddOverloadCandidate(Constructor, FoundDecl,
2451 &From, 1, CandidateSet,
2452 /*SuppressUserConversions=*/
2453 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002454 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002455 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002456 }
2457 }
2458
Douglas Gregor5ab11652010-04-17 22:01:05 +00002459 // Enumerate conversion functions, if we're allowed to.
2460 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002461 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2462 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002463 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002464 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002465 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002466 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002467 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2468 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002469 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002470 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002471 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002472 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002473 DeclAccessPair FoundDecl = I.getPair();
2474 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002475 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2476 if (isa<UsingShadowDecl>(D))
2477 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2478
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002479 CXXConversionDecl *Conv;
2480 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002481 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2482 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002483 else
John McCallda4458e2010-03-31 01:36:47 +00002484 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002485
2486 if (AllowExplicit || !Conv->isExplicit()) {
2487 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002488 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2489 ActingContext, From, ToType,
2490 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002491 else
John McCall5c32be02010-08-24 20:38:10 +00002492 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2493 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002494 }
2495 }
2496 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002497 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002498
2499 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002500 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002501 case OR_Success:
2502 // Record the standard conversion we used and the conversion function.
2503 if (CXXConstructorDecl *Constructor
2504 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002505 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2506
John McCall5c32be02010-08-24 20:38:10 +00002507 // C++ [over.ics.user]p1:
2508 // If the user-defined conversion is specified by a
2509 // constructor (12.3.1), the initial standard conversion
2510 // sequence converts the source type to the type required by
2511 // the argument of the constructor.
2512 //
2513 QualType ThisType = Constructor->getThisType(S.Context);
2514 if (Best->Conversions[0].isEllipsis())
2515 User.EllipsisConversion = true;
2516 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002517 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002518 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002519 }
John McCall5c32be02010-08-24 20:38:10 +00002520 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002521 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002522 User.After.setAsIdentityConversion();
2523 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2524 User.After.setAllToTypes(ToType);
2525 return OR_Success;
2526 } else if (CXXConversionDecl *Conversion
2527 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002528 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2529
John McCall5c32be02010-08-24 20:38:10 +00002530 // C++ [over.ics.user]p1:
2531 //
2532 // [...] If the user-defined conversion is specified by a
2533 // conversion function (12.3.2), the initial standard
2534 // conversion sequence converts the source type to the
2535 // implicit object parameter of the conversion function.
2536 User.Before = Best->Conversions[0].Standard;
2537 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002538 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002539 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002540
John McCall5c32be02010-08-24 20:38:10 +00002541 // C++ [over.ics.user]p2:
2542 // The second standard conversion sequence converts the
2543 // result of the user-defined conversion to the target type
2544 // for the sequence. Since an implicit conversion sequence
2545 // is an initialization, the special rules for
2546 // initialization by user-defined conversion apply when
2547 // selecting the best user-defined conversion for a
2548 // user-defined conversion sequence (see 13.3.3 and
2549 // 13.3.3.1).
2550 User.After = Best->FinalConversion;
2551 return OR_Success;
2552 } else {
2553 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002554 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002555 }
2556
John McCall5c32be02010-08-24 20:38:10 +00002557 case OR_No_Viable_Function:
2558 return OR_No_Viable_Function;
2559 case OR_Deleted:
2560 // No conversion here! We're done.
2561 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002562
John McCall5c32be02010-08-24 20:38:10 +00002563 case OR_Ambiguous:
2564 return OR_Ambiguous;
2565 }
2566
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002567 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002568}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002570bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002571Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002572 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002573 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002575 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002576 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002577 if (OvResult == OR_Ambiguous)
2578 Diag(From->getSourceRange().getBegin(),
2579 diag::err_typecheck_ambiguous_condition)
2580 << From->getType() << ToType << From->getSourceRange();
2581 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2582 Diag(From->getSourceRange().getBegin(),
2583 diag::err_typecheck_nonviable_condition)
2584 << From->getType() << ToType << From->getSourceRange();
2585 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002586 return false;
John McCall5c32be02010-08-24 20:38:10 +00002587 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002588 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002589}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002590
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002591/// CompareImplicitConversionSequences - Compare two implicit
2592/// conversion sequences to determine whether one is better than the
2593/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002594static ImplicitConversionSequence::CompareKind
2595CompareImplicitConversionSequences(Sema &S,
2596 const ImplicitConversionSequence& ICS1,
2597 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002598{
2599 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2600 // conversion sequences (as defined in 13.3.3.1)
2601 // -- a standard conversion sequence (13.3.3.1.1) is a better
2602 // conversion sequence than a user-defined conversion sequence or
2603 // an ellipsis conversion sequence, and
2604 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2605 // conversion sequence than an ellipsis conversion sequence
2606 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002607 //
John McCall0d1da222010-01-12 00:44:57 +00002608 // C++0x [over.best.ics]p10:
2609 // For the purpose of ranking implicit conversion sequences as
2610 // described in 13.3.3.2, the ambiguous conversion sequence is
2611 // treated as a user-defined sequence that is indistinguishable
2612 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002613 if (ICS1.getKindRank() < ICS2.getKindRank())
2614 return ImplicitConversionSequence::Better;
2615 else if (ICS2.getKindRank() < ICS1.getKindRank())
2616 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002617
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002618 // The following checks require both conversion sequences to be of
2619 // the same kind.
2620 if (ICS1.getKind() != ICS2.getKind())
2621 return ImplicitConversionSequence::Indistinguishable;
2622
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002623 // Two implicit conversion sequences of the same form are
2624 // indistinguishable conversion sequences unless one of the
2625 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002626 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002627 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002628 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002629 // User-defined conversion sequence U1 is a better conversion
2630 // sequence than another user-defined conversion sequence U2 if
2631 // they contain the same user-defined conversion function or
2632 // constructor and if the second standard conversion sequence of
2633 // U1 is better than the second standard conversion sequence of
2634 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002635 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002636 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002637 return CompareStandardConversionSequences(S,
2638 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002639 ICS2.UserDefined.After);
2640 }
2641
2642 return ImplicitConversionSequence::Indistinguishable;
2643}
2644
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002645static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2646 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2647 Qualifiers Quals;
2648 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002650 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002651
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002652 return Context.hasSameUnqualifiedType(T1, T2);
2653}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002654
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002655// Per 13.3.3.2p3, compare the given standard conversion sequences to
2656// determine if one is a proper subset of the other.
2657static ImplicitConversionSequence::CompareKind
2658compareStandardConversionSubsets(ASTContext &Context,
2659 const StandardConversionSequence& SCS1,
2660 const StandardConversionSequence& SCS2) {
2661 ImplicitConversionSequence::CompareKind Result
2662 = ImplicitConversionSequence::Indistinguishable;
2663
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002665 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002666 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2667 return ImplicitConversionSequence::Better;
2668 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2669 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002670
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002671 if (SCS1.Second != SCS2.Second) {
2672 if (SCS1.Second == ICK_Identity)
2673 Result = ImplicitConversionSequence::Better;
2674 else if (SCS2.Second == ICK_Identity)
2675 Result = ImplicitConversionSequence::Worse;
2676 else
2677 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002678 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002679 return ImplicitConversionSequence::Indistinguishable;
2680
2681 if (SCS1.Third == SCS2.Third) {
2682 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2683 : ImplicitConversionSequence::Indistinguishable;
2684 }
2685
2686 if (SCS1.Third == ICK_Identity)
2687 return Result == ImplicitConversionSequence::Worse
2688 ? ImplicitConversionSequence::Indistinguishable
2689 : ImplicitConversionSequence::Better;
2690
2691 if (SCS2.Third == ICK_Identity)
2692 return Result == ImplicitConversionSequence::Better
2693 ? ImplicitConversionSequence::Indistinguishable
2694 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002696 return ImplicitConversionSequence::Indistinguishable;
2697}
2698
Douglas Gregore696ebb2011-01-26 14:52:12 +00002699/// \brief Determine whether one of the given reference bindings is better
2700/// than the other based on what kind of bindings they are.
2701static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2702 const StandardConversionSequence &SCS2) {
2703 // C++0x [over.ics.rank]p3b4:
2704 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2705 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002707 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002708 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002709 // reference*.
2710 //
2711 // FIXME: Rvalue references. We're going rogue with the above edits,
2712 // because the semantics in the current C++0x working paper (N3225 at the
2713 // time of this writing) break the standard definition of std::forward
2714 // and std::reference_wrapper when dealing with references to functions.
2715 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002716 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2717 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2718 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002719
Douglas Gregore696ebb2011-01-26 14:52:12 +00002720 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2721 SCS2.IsLvalueReference) ||
2722 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2723 !SCS2.IsLvalueReference);
2724}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002725
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002726/// CompareStandardConversionSequences - Compare two standard
2727/// conversion sequences to determine whether one is better than the
2728/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002729static ImplicitConversionSequence::CompareKind
2730CompareStandardConversionSequences(Sema &S,
2731 const StandardConversionSequence& SCS1,
2732 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002733{
2734 // Standard conversion sequence S1 is a better conversion sequence
2735 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2736
2737 // -- S1 is a proper subsequence of S2 (comparing the conversion
2738 // sequences in the canonical form defined by 13.3.3.1.1,
2739 // excluding any Lvalue Transformation; the identity conversion
2740 // sequence is considered to be a subsequence of any
2741 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002742 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002743 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002744 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002745
2746 // -- the rank of S1 is better than the rank of S2 (by the rules
2747 // defined below), or, if not that,
2748 ImplicitConversionRank Rank1 = SCS1.getRank();
2749 ImplicitConversionRank Rank2 = SCS2.getRank();
2750 if (Rank1 < Rank2)
2751 return ImplicitConversionSequence::Better;
2752 else if (Rank2 < Rank1)
2753 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002754
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002755 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2756 // are indistinguishable unless one of the following rules
2757 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002758
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002759 // A conversion that is not a conversion of a pointer, or
2760 // pointer to member, to bool is better than another conversion
2761 // that is such a conversion.
2762 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2763 return SCS2.isPointerConversionToBool()
2764 ? ImplicitConversionSequence::Better
2765 : ImplicitConversionSequence::Worse;
2766
Douglas Gregor5c407d92008-10-23 00:40:37 +00002767 // C++ [over.ics.rank]p4b2:
2768 //
2769 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002770 // conversion of B* to A* is better than conversion of B* to
2771 // void*, and conversion of A* to void* is better than conversion
2772 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002773 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002774 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002775 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002776 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002777 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2778 // Exactly one of the conversion sequences is a conversion to
2779 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002780 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2781 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002782 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2783 // Neither conversion sequence converts to a void pointer; compare
2784 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002785 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002786 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002787 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002788 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2789 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002790 // Both conversion sequences are conversions to void
2791 // pointers. Compare the source types to determine if there's an
2792 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002793 QualType FromType1 = SCS1.getFromType();
2794 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002795
2796 // Adjust the types we're converting from via the array-to-pointer
2797 // conversion, if we need to.
2798 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002799 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002800 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002801 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002802
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002803 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2804 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002805
John McCall5c32be02010-08-24 20:38:10 +00002806 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002807 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002808 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002809 return ImplicitConversionSequence::Worse;
2810
2811 // Objective-C++: If one interface is more specific than the
2812 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002813 const ObjCObjectPointerType* FromObjCPtr1
2814 = FromType1->getAs<ObjCObjectPointerType>();
2815 const ObjCObjectPointerType* FromObjCPtr2
2816 = FromType2->getAs<ObjCObjectPointerType>();
2817 if (FromObjCPtr1 && FromObjCPtr2) {
2818 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2819 FromObjCPtr2);
2820 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2821 FromObjCPtr1);
2822 if (AssignLeft != AssignRight) {
2823 return AssignLeft? ImplicitConversionSequence::Better
2824 : ImplicitConversionSequence::Worse;
2825 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002826 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002827 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002828
2829 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2830 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002831 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002832 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002833 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002834
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002835 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002836 // Check for a better reference binding based on the kind of bindings.
2837 if (isBetterReferenceBindingKind(SCS1, SCS2))
2838 return ImplicitConversionSequence::Better;
2839 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2840 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841
Sebastian Redlb28b4072009-03-22 23:49:27 +00002842 // C++ [over.ics.rank]p3b4:
2843 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2844 // which the references refer are the same type except for
2845 // top-level cv-qualifiers, and the type to which the reference
2846 // initialized by S2 refers is more cv-qualified than the type
2847 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002848 QualType T1 = SCS1.getToType(2);
2849 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002850 T1 = S.Context.getCanonicalType(T1);
2851 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002852 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002853 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2854 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002855 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002856 // Objective-C++ ARC: If the references refer to objects with different
2857 // lifetimes, prefer bindings that don't change lifetime.
2858 if (SCS1.ObjCLifetimeConversionBinding !=
2859 SCS2.ObjCLifetimeConversionBinding) {
2860 return SCS1.ObjCLifetimeConversionBinding
2861 ? ImplicitConversionSequence::Worse
2862 : ImplicitConversionSequence::Better;
2863 }
2864
Chandler Carruth8e543b32010-12-12 08:17:55 +00002865 // If the type is an array type, promote the element qualifiers to the
2866 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002867 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002868 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002869 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002870 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002871 if (T2.isMoreQualifiedThan(T1))
2872 return ImplicitConversionSequence::Better;
2873 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002874 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002875 }
2876 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002877
Francois Pichet08d2fa02011-09-18 21:37:37 +00002878 // In Microsoft mode, prefer an integral conversion to a
2879 // floating-to-integral conversion if the integral conversion
2880 // is between types of the same size.
2881 // For example:
2882 // void f(float);
2883 // void f(int);
2884 // int main {
2885 // long a;
2886 // f(a);
2887 // }
2888 // Here, MSVC will call f(int) instead of generating a compile error
2889 // as clang will do in standard mode.
2890 if (S.getLangOptions().MicrosoftMode &&
2891 SCS1.Second == ICK_Integral_Conversion &&
2892 SCS2.Second == ICK_Floating_Integral &&
2893 S.Context.getTypeSize(SCS1.getFromType()) ==
2894 S.Context.getTypeSize(SCS1.getToType(2)))
2895 return ImplicitConversionSequence::Better;
2896
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002897 return ImplicitConversionSequence::Indistinguishable;
2898}
2899
2900/// CompareQualificationConversions - Compares two standard conversion
2901/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002902/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2903ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002904CompareQualificationConversions(Sema &S,
2905 const StandardConversionSequence& SCS1,
2906 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002907 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002908 // -- S1 and S2 differ only in their qualification conversion and
2909 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2910 // cv-qualification signature of type T1 is a proper subset of
2911 // the cv-qualification signature of type T2, and S1 is not the
2912 // deprecated string literal array-to-pointer conversion (4.2).
2913 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2914 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2915 return ImplicitConversionSequence::Indistinguishable;
2916
2917 // FIXME: the example in the standard doesn't use a qualification
2918 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002919 QualType T1 = SCS1.getToType(2);
2920 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002921 T1 = S.Context.getCanonicalType(T1);
2922 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002923 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002924 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2925 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002926
2927 // If the types are the same, we won't learn anything by unwrapped
2928 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002929 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002930 return ImplicitConversionSequence::Indistinguishable;
2931
Chandler Carruth607f38e2009-12-29 07:16:59 +00002932 // If the type is an array type, promote the element qualifiers to the type
2933 // for comparison.
2934 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002935 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002936 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002937 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002938
Mike Stump11289f42009-09-09 15:08:12 +00002939 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002940 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00002941
2942 // Objective-C++ ARC:
2943 // Prefer qualification conversions not involving a change in lifetime
2944 // to qualification conversions that do not change lifetime.
2945 if (SCS1.QualificationIncludesObjCLifetime !=
2946 SCS2.QualificationIncludesObjCLifetime) {
2947 Result = SCS1.QualificationIncludesObjCLifetime
2948 ? ImplicitConversionSequence::Worse
2949 : ImplicitConversionSequence::Better;
2950 }
2951
John McCall5c32be02010-08-24 20:38:10 +00002952 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002953 // Within each iteration of the loop, we check the qualifiers to
2954 // determine if this still looks like a qualification
2955 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002956 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002957 // until there are no more pointers or pointers-to-members left
2958 // to unwrap. This essentially mimics what
2959 // IsQualificationConversion does, but here we're checking for a
2960 // strict subset of qualifiers.
2961 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2962 // The qualifiers are the same, so this doesn't tell us anything
2963 // about how the sequences rank.
2964 ;
2965 else if (T2.isMoreQualifiedThan(T1)) {
2966 // T1 has fewer qualifiers, so it could be the better sequence.
2967 if (Result == ImplicitConversionSequence::Worse)
2968 // Neither has qualifiers that are a subset of the other's
2969 // qualifiers.
2970 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002972 Result = ImplicitConversionSequence::Better;
2973 } else if (T1.isMoreQualifiedThan(T2)) {
2974 // T2 has fewer qualifiers, so it could be the better sequence.
2975 if (Result == ImplicitConversionSequence::Better)
2976 // Neither has qualifiers that are a subset of the other's
2977 // qualifiers.
2978 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002979
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002980 Result = ImplicitConversionSequence::Worse;
2981 } else {
2982 // Qualifiers are disjoint.
2983 return ImplicitConversionSequence::Indistinguishable;
2984 }
2985
2986 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002987 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002988 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002989 }
2990
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002991 // Check that the winning standard conversion sequence isn't using
2992 // the deprecated string literal array to pointer conversion.
2993 switch (Result) {
2994 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002995 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002996 Result = ImplicitConversionSequence::Indistinguishable;
2997 break;
2998
2999 case ImplicitConversionSequence::Indistinguishable:
3000 break;
3001
3002 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003003 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003004 Result = ImplicitConversionSequence::Indistinguishable;
3005 break;
3006 }
3007
3008 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003009}
3010
Douglas Gregor5c407d92008-10-23 00:40:37 +00003011/// CompareDerivedToBaseConversions - Compares two standard conversion
3012/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003013/// various kinds of derived-to-base conversions (C++
3014/// [over.ics.rank]p4b3). As part of these checks, we also look at
3015/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003016ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003017CompareDerivedToBaseConversions(Sema &S,
3018 const StandardConversionSequence& SCS1,
3019 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003020 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003021 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003022 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003023 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003024
3025 // Adjust the types we're converting from via the array-to-pointer
3026 // conversion, if we need to.
3027 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003028 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003029 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003030 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003031
3032 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003033 FromType1 = S.Context.getCanonicalType(FromType1);
3034 ToType1 = S.Context.getCanonicalType(ToType1);
3035 FromType2 = S.Context.getCanonicalType(FromType2);
3036 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003037
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003038 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003039 //
3040 // If class B is derived directly or indirectly from class A and
3041 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003042 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003043 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003044 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003045 SCS2.Second == ICK_Pointer_Conversion &&
3046 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3047 FromType1->isPointerType() && FromType2->isPointerType() &&
3048 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003049 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003050 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003051 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003052 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003053 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003054 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003055 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003056 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003057
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003058 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003059 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003060 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003061 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003062 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003063 return ImplicitConversionSequence::Worse;
3064 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003065
3066 // -- conversion of B* to A* is better than conversion of C* to A*,
3067 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003068 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003069 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003070 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003071 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003072 }
3073 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3074 SCS2.Second == ICK_Pointer_Conversion) {
3075 const ObjCObjectPointerType *FromPtr1
3076 = FromType1->getAs<ObjCObjectPointerType>();
3077 const ObjCObjectPointerType *FromPtr2
3078 = FromType2->getAs<ObjCObjectPointerType>();
3079 const ObjCObjectPointerType *ToPtr1
3080 = ToType1->getAs<ObjCObjectPointerType>();
3081 const ObjCObjectPointerType *ToPtr2
3082 = ToType2->getAs<ObjCObjectPointerType>();
3083
3084 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3085 // Apply the same conversion ranking rules for Objective-C pointer types
3086 // that we do for C++ pointers to class types. However, we employ the
3087 // Objective-C pseudo-subtyping relationship used for assignment of
3088 // Objective-C pointer types.
3089 bool FromAssignLeft
3090 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3091 bool FromAssignRight
3092 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3093 bool ToAssignLeft
3094 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3095 bool ToAssignRight
3096 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3097
3098 // A conversion to an a non-id object pointer type or qualified 'id'
3099 // type is better than a conversion to 'id'.
3100 if (ToPtr1->isObjCIdType() &&
3101 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3102 return ImplicitConversionSequence::Worse;
3103 if (ToPtr2->isObjCIdType() &&
3104 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3105 return ImplicitConversionSequence::Better;
3106
3107 // A conversion to a non-id object pointer type is better than a
3108 // conversion to a qualified 'id' type
3109 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3110 return ImplicitConversionSequence::Worse;
3111 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3112 return ImplicitConversionSequence::Better;
3113
3114 // A conversion to an a non-Class object pointer type or qualified 'Class'
3115 // type is better than a conversion to 'Class'.
3116 if (ToPtr1->isObjCClassType() &&
3117 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3118 return ImplicitConversionSequence::Worse;
3119 if (ToPtr2->isObjCClassType() &&
3120 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3121 return ImplicitConversionSequence::Better;
3122
3123 // A conversion to a non-Class object pointer type is better than a
3124 // conversion to a qualified 'Class' type.
3125 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3126 return ImplicitConversionSequence::Worse;
3127 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3128 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003129
Douglas Gregor058d3de2011-01-31 18:51:41 +00003130 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3131 if (S.Context.hasSameType(FromType1, FromType2) &&
3132 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3133 (ToAssignLeft != ToAssignRight))
3134 return ToAssignLeft? ImplicitConversionSequence::Worse
3135 : ImplicitConversionSequence::Better;
3136
3137 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3138 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3139 (FromAssignLeft != FromAssignRight))
3140 return FromAssignLeft? ImplicitConversionSequence::Better
3141 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003142 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003143 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003144
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003145 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003146 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3147 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3148 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003150 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003152 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003154 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003156 ToType2->getAs<MemberPointerType>();
3157 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3158 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3159 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3160 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3161 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3162 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3163 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3164 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003165 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003166 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003167 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003168 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003169 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003170 return ImplicitConversionSequence::Better;
3171 }
3172 // conversion of B::* to C::* is better than conversion of A::* to C::*
3173 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003174 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003175 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003176 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003177 return ImplicitConversionSequence::Worse;
3178 }
3179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003180
Douglas Gregor5ab11652010-04-17 22:01:05 +00003181 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003182 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003183 // -- binding of an expression of type C to a reference of type
3184 // B& is better than binding an expression of type C to a
3185 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003186 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3187 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3188 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003189 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003190 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003191 return ImplicitConversionSequence::Worse;
3192 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003193
Douglas Gregor2fe98832008-11-03 19:09:14 +00003194 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003195 // -- binding of an expression of type B to a reference of type
3196 // A& is better than binding an expression of type C to a
3197 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003198 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3199 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3200 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003201 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003202 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003203 return ImplicitConversionSequence::Worse;
3204 }
3205 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003206
Douglas Gregor5c407d92008-10-23 00:40:37 +00003207 return ImplicitConversionSequence::Indistinguishable;
3208}
3209
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003210/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3211/// determine whether they are reference-related,
3212/// reference-compatible, reference-compatible with added
3213/// qualification, or incompatible, for use in C++ initialization by
3214/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3215/// type, and the first type (T1) is the pointee type of the reference
3216/// type being initialized.
3217Sema::ReferenceCompareResult
3218Sema::CompareReferenceRelationship(SourceLocation Loc,
3219 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003220 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003221 bool &ObjCConversion,
3222 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003223 assert(!OrigT1->isReferenceType() &&
3224 "T1 must be the pointee type of the reference type");
3225 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3226
3227 QualType T1 = Context.getCanonicalType(OrigT1);
3228 QualType T2 = Context.getCanonicalType(OrigT2);
3229 Qualifiers T1Quals, T2Quals;
3230 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3231 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3232
3233 // C++ [dcl.init.ref]p4:
3234 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3235 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3236 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003237 DerivedToBase = false;
3238 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003239 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003240 if (UnqualT1 == UnqualT2) {
3241 // Nothing to do.
3242 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003243 IsDerivedFrom(UnqualT2, UnqualT1))
3244 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003245 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3246 UnqualT2->isObjCObjectOrInterfaceType() &&
3247 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3248 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003249 else
3250 return Ref_Incompatible;
3251
3252 // At this point, we know that T1 and T2 are reference-related (at
3253 // least).
3254
3255 // If the type is an array type, promote the element qualifiers to the type
3256 // for comparison.
3257 if (isa<ArrayType>(T1) && T1Quals)
3258 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3259 if (isa<ArrayType>(T2) && T2Quals)
3260 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3261
3262 // C++ [dcl.init.ref]p4:
3263 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3264 // reference-related to T2 and cv1 is the same cv-qualification
3265 // as, or greater cv-qualification than, cv2. For purposes of
3266 // overload resolution, cases for which cv1 is greater
3267 // cv-qualification than cv2 are identified as
3268 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003269 //
3270 // Note that we also require equivalence of Objective-C GC and address-space
3271 // qualifiers when performing these computations, so that e.g., an int in
3272 // address space 1 is not reference-compatible with an int in address
3273 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003274 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3275 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3276 T1Quals.removeObjCLifetime();
3277 T2Quals.removeObjCLifetime();
3278 ObjCLifetimeConversion = true;
3279 }
3280
Douglas Gregord517d552011-04-28 17:56:11 +00003281 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003282 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003283 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003284 return Ref_Compatible_With_Added_Qualification;
3285 else
3286 return Ref_Related;
3287}
3288
Douglas Gregor836a7e82010-08-11 02:15:33 +00003289/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003290/// with DeclType. Return true if something definite is found.
3291static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003292FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3293 QualType DeclType, SourceLocation DeclLoc,
3294 Expr *Init, QualType T2, bool AllowRvalues,
3295 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003296 assert(T2->isRecordType() && "Can only find conversions of record types.");
3297 CXXRecordDecl *T2RecordDecl
3298 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3299
3300 OverloadCandidateSet CandidateSet(DeclLoc);
3301 const UnresolvedSetImpl *Conversions
3302 = T2RecordDecl->getVisibleConversionFunctions();
3303 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3304 E = Conversions->end(); I != E; ++I) {
3305 NamedDecl *D = *I;
3306 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3307 if (isa<UsingShadowDecl>(D))
3308 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3309
3310 FunctionTemplateDecl *ConvTemplate
3311 = dyn_cast<FunctionTemplateDecl>(D);
3312 CXXConversionDecl *Conv;
3313 if (ConvTemplate)
3314 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3315 else
3316 Conv = cast<CXXConversionDecl>(D);
3317
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003319 // explicit conversions, skip it.
3320 if (!AllowExplicit && Conv->isExplicit())
3321 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003322
Douglas Gregor836a7e82010-08-11 02:15:33 +00003323 if (AllowRvalues) {
3324 bool DerivedToBase = false;
3325 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003326 bool ObjCLifetimeConversion = false;
Douglas Gregor836a7e82010-08-11 02:15:33 +00003327 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003328 S.CompareReferenceRelationship(
3329 DeclLoc,
3330 Conv->getConversionType().getNonReferenceType()
3331 .getUnqualifiedType(),
3332 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003333 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003334 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003335 continue;
3336 } else {
3337 // If the conversion function doesn't return a reference type,
3338 // it can't be considered for this conversion. An rvalue reference
3339 // is only acceptable if its referencee is a function type.
3340
3341 const ReferenceType *RefType =
3342 Conv->getConversionType()->getAs<ReferenceType>();
3343 if (!RefType ||
3344 (!RefType->isLValueReferenceType() &&
3345 !RefType->getPointeeType()->isFunctionType()))
3346 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003347 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348
Douglas Gregor836a7e82010-08-11 02:15:33 +00003349 if (ConvTemplate)
3350 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003351 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003352 else
3353 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003354 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003355 }
3356
3357 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003358 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003359 case OR_Success:
3360 // C++ [over.ics.ref]p1:
3361 //
3362 // [...] If the parameter binds directly to the result of
3363 // applying a conversion function to the argument
3364 // expression, the implicit conversion sequence is a
3365 // user-defined conversion sequence (13.3.3.1.2), with the
3366 // second standard conversion sequence either an identity
3367 // conversion or, if the conversion function returns an
3368 // entity of a type that is a derived class of the parameter
3369 // type, a derived-to-base Conversion.
3370 if (!Best->FinalConversion.DirectBinding)
3371 return false;
3372
Chandler Carruth30141632011-02-25 19:41:05 +00003373 if (Best->Function)
3374 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003375 ICS.setUserDefined();
3376 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3377 ICS.UserDefined.After = Best->FinalConversion;
3378 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003379 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003380 ICS.UserDefined.EllipsisConversion = false;
3381 assert(ICS.UserDefined.After.ReferenceBinding &&
3382 ICS.UserDefined.After.DirectBinding &&
3383 "Expected a direct reference binding!");
3384 return true;
3385
3386 case OR_Ambiguous:
3387 ICS.setAmbiguous();
3388 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3389 Cand != CandidateSet.end(); ++Cand)
3390 if (Cand->Viable)
3391 ICS.Ambiguous.addConversion(Cand->Function);
3392 return true;
3393
3394 case OR_No_Viable_Function:
3395 case OR_Deleted:
3396 // There was no suitable conversion, or we found a deleted
3397 // conversion; continue with other checks.
3398 return false;
3399 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400
Eric Christopheraba9fb22010-06-30 18:36:32 +00003401 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003402}
3403
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003404/// \brief Compute an implicit conversion sequence for reference
3405/// initialization.
3406static ImplicitConversionSequence
3407TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3408 SourceLocation DeclLoc,
3409 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003410 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003411 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3412
3413 // Most paths end in a failed conversion.
3414 ImplicitConversionSequence ICS;
3415 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3416
3417 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3418 QualType T2 = Init->getType();
3419
3420 // If the initializer is the address of an overloaded function, try
3421 // to resolve the overloaded function. If all goes well, T2 is the
3422 // type of the resulting function.
3423 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3424 DeclAccessPair Found;
3425 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3426 false, Found))
3427 T2 = Fn->getType();
3428 }
3429
3430 // Compute some basic properties of the types and the initializer.
3431 bool isRValRef = DeclType->isRValueReferenceType();
3432 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003433 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003434 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003435 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003436 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003437 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003438 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003439
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003440
Sebastian Redld92badf2010-06-30 18:13:39 +00003441 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003442 // A reference to type "cv1 T1" is initialized by an expression
3443 // of type "cv2 T2" as follows:
3444
Sebastian Redld92badf2010-06-30 18:13:39 +00003445 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003446 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003447 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3448 // reference-compatible with "cv2 T2," or
3449 //
3450 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3451 if (InitCategory.isLValue() &&
3452 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003453 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003454 // When a parameter of reference type binds directly (8.5.3)
3455 // to an argument expression, the implicit conversion sequence
3456 // is the identity conversion, unless the argument expression
3457 // has a type that is a derived class of the parameter type,
3458 // in which case the implicit conversion sequence is a
3459 // derived-to-base Conversion (13.3.3.1).
3460 ICS.setStandard();
3461 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003462 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3463 : ObjCConversion? ICK_Compatible_Conversion
3464 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003465 ICS.Standard.Third = ICK_Identity;
3466 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3467 ICS.Standard.setToType(0, T2);
3468 ICS.Standard.setToType(1, T1);
3469 ICS.Standard.setToType(2, T1);
3470 ICS.Standard.ReferenceBinding = true;
3471 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003472 ICS.Standard.IsLvalueReference = !isRValRef;
3473 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3474 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003475 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003476 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003477 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003478
Sebastian Redld92badf2010-06-30 18:13:39 +00003479 // Nothing more to do: the inaccessibility/ambiguity check for
3480 // derived-to-base conversions is suppressed when we're
3481 // computing the implicit conversion sequence (C++
3482 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003483 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003484 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003485
Sebastian Redld92badf2010-06-30 18:13:39 +00003486 // -- has a class type (i.e., T2 is a class type), where T1 is
3487 // not reference-related to T2, and can be implicitly
3488 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3489 // is reference-compatible with "cv3 T3" 92) (this
3490 // conversion is selected by enumerating the applicable
3491 // conversion functions (13.3.1.6) and choosing the best
3492 // one through overload resolution (13.3)),
3493 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003495 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003496 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3497 Init, T2, /*AllowRvalues=*/false,
3498 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003499 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003500 }
3501 }
3502
Sebastian Redld92badf2010-06-30 18:13:39 +00003503 // -- Otherwise, the reference shall be an lvalue reference to a
3504 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003505 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003507 // We actually handle one oddity of C++ [over.ics.ref] at this
3508 // point, which is that, due to p2 (which short-circuits reference
3509 // binding by only attempting a simple conversion for non-direct
3510 // bindings) and p3's strange wording, we allow a const volatile
3511 // reference to bind to an rvalue. Hence the check for the presence
3512 // of "const" rather than checking for "const" being the only
3513 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003514 // This is also the point where rvalue references and lvalue inits no longer
3515 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003516 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003517 return ICS;
3518
Douglas Gregorf143cd52011-01-24 16:14:37 +00003519 // -- If the initializer expression
3520 //
3521 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003522 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003523 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3524 (InitCategory.isXValue() ||
3525 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3526 (InitCategory.isLValue() && T2->isFunctionType()))) {
3527 ICS.setStandard();
3528 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003530 : ObjCConversion? ICK_Compatible_Conversion
3531 : ICK_Identity;
3532 ICS.Standard.Third = ICK_Identity;
3533 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3534 ICS.Standard.setToType(0, T2);
3535 ICS.Standard.setToType(1, T1);
3536 ICS.Standard.setToType(2, T1);
3537 ICS.Standard.ReferenceBinding = true;
3538 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3539 // binding unless we're binding to a class prvalue.
3540 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3541 // allow the use of rvalue references in C++98/03 for the benefit of
3542 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543 ICS.Standard.DirectBinding =
3544 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003545 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003546 ICS.Standard.IsLvalueReference = !isRValRef;
3547 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003549 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003550 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003551 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003552 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003554
Douglas Gregorf143cd52011-01-24 16:14:37 +00003555 // -- has a class type (i.e., T2 is a class type), where T1 is not
3556 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557 // an xvalue, class prvalue, or function lvalue of type
3558 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003559 // "cv3 T3",
3560 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003561 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003562 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003564 // class subobject).
3565 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003567 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3568 Init, T2, /*AllowRvalues=*/true,
3569 AllowExplicit)) {
3570 // In the second case, if the reference is an rvalue reference
3571 // and the second standard conversion sequence of the
3572 // user-defined conversion sequence includes an lvalue-to-rvalue
3573 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003575 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3576 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3577
Douglas Gregor95273c32011-01-21 16:36:05 +00003578 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003581 // -- Otherwise, a temporary of type "cv1 T1" is created and
3582 // initialized from the initializer expression using the
3583 // rules for a non-reference copy initialization (8.5). The
3584 // reference is then bound to the temporary. If T1 is
3585 // reference-related to T2, cv1 must be the same
3586 // cv-qualification as, or greater cv-qualification than,
3587 // cv2; otherwise, the program is ill-formed.
3588 if (RefRelationship == Sema::Ref_Related) {
3589 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3590 // we would be reference-compatible or reference-compatible with
3591 // added qualification. But that wasn't the case, so the reference
3592 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003593 //
3594 // Note that we only want to check address spaces and cvr-qualifiers here.
3595 // ObjC GC and lifetime qualifiers aren't important.
3596 Qualifiers T1Quals = T1.getQualifiers();
3597 Qualifiers T2Quals = T2.getQualifiers();
3598 T1Quals.removeObjCGCAttr();
3599 T1Quals.removeObjCLifetime();
3600 T2Quals.removeObjCGCAttr();
3601 T2Quals.removeObjCLifetime();
3602 if (!T1Quals.compatiblyIncludes(T2Quals))
3603 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003604 }
3605
3606 // If at least one of the types is a class type, the types are not
3607 // related, and we aren't allowed any user conversions, the
3608 // reference binding fails. This case is important for breaking
3609 // recursion, since TryImplicitConversion below will attempt to
3610 // create a temporary through the use of a copy constructor.
3611 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3612 (T1->isRecordType() || T2->isRecordType()))
3613 return ICS;
3614
Douglas Gregorcba72b12011-01-21 05:18:22 +00003615 // If T1 is reference-related to T2 and the reference is an rvalue
3616 // reference, the initializer expression shall not be an lvalue.
3617 if (RefRelationship >= Sema::Ref_Related &&
3618 isRValRef && Init->Classify(S.Context).isLValue())
3619 return ICS;
3620
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003621 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003622 // When a parameter of reference type is not bound directly to
3623 // an argument expression, the conversion sequence is the one
3624 // required to convert the argument expression to the
3625 // underlying type of the reference according to
3626 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3627 // to copy-initializing a temporary of the underlying type with
3628 // the argument expression. Any difference in top-level
3629 // cv-qualification is subsumed by the initialization itself
3630 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003631 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3632 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003633 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003634 /*CStyle=*/false,
3635 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003636
3637 // Of course, that's still a reference binding.
3638 if (ICS.isStandard()) {
3639 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003640 ICS.Standard.IsLvalueReference = !isRValRef;
3641 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3642 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003643 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003644 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003645 } else if (ICS.isUserDefined()) {
3646 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003647 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3648 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3649 ICS.UserDefined.After.BindsToRvalue = true;
3650 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3651 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003652 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003653
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003654 return ICS;
3655}
3656
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003657/// TryCopyInitialization - Try to copy-initialize a value of type
3658/// ToType from the expression From. Return the implicit conversion
3659/// sequence required to pass this argument, which may be a bad
3660/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003661/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003662/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003663static ImplicitConversionSequence
3664TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003666 bool InOverloadResolution,
3667 bool AllowObjCWritebackConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003668 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003669 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003670 /*FIXME:*/From->getLocStart(),
3671 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003672 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003673
John McCall5c32be02010-08-24 20:38:10 +00003674 return TryImplicitConversion(S, From, ToType,
3675 SuppressUserConversions,
3676 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003677 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003678 /*CStyle=*/false,
3679 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003680}
3681
Anna Zaks1b068122011-07-28 19:46:48 +00003682static bool TryCopyInitialization(const CanQualType FromQTy,
3683 const CanQualType ToQTy,
3684 Sema &S,
3685 SourceLocation Loc,
3686 ExprValueKind FromVK) {
3687 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3688 ImplicitConversionSequence ICS =
3689 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3690
3691 return !ICS.isBad();
3692}
3693
Douglas Gregor436424c2008-11-18 23:14:02 +00003694/// TryObjectArgumentInitialization - Try to initialize the object
3695/// parameter of the given member function (@c Method) from the
3696/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003697static ImplicitConversionSequence
3698TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003699 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003700 CXXMethodDecl *Method,
3701 CXXRecordDecl *ActingContext) {
3702 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003703 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3704 // const volatile object.
3705 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3706 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003707 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003708
3709 // Set up the conversion sequence as a "bad" conversion, to allow us
3710 // to exit early.
3711 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003712
3713 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003714 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003715 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003716 FromType = PT->getPointeeType();
3717
Douglas Gregor02824322011-01-26 19:30:28 +00003718 // When we had a pointer, it's implicitly dereferenced, so we
3719 // better have an lvalue.
3720 assert(FromClassification.isLValue());
3721 }
3722
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003723 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003724
Douglas Gregor02824322011-01-26 19:30:28 +00003725 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003727 // parameter is
3728 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003729 // - "lvalue reference to cv X" for functions declared without a
3730 // ref-qualifier or with the & ref-qualifier
3731 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003732 // ref-qualifier
3733 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003734 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003735 // cv-qualification on the member function declaration.
3736 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003738 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003739 // (C++ [over.match.funcs]p5). We perform a simplified version of
3740 // reference binding here, that allows class rvalues to bind to
3741 // non-constant references.
3742
Douglas Gregor02824322011-01-26 19:30:28 +00003743 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003744 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003746 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003747 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003748 ICS.setBad(BadConversionSequence::bad_qualifiers,
3749 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003750 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003751 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003752
3753 // Check that we have either the same type or a derived type. It
3754 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003755 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003756 ImplicitConversionKind SecondKind;
3757 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3758 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003759 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003760 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003761 else {
John McCall65eb8792010-02-25 01:37:24 +00003762 ICS.setBad(BadConversionSequence::unrelated_class,
3763 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003764 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003765 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003766
Douglas Gregor02824322011-01-26 19:30:28 +00003767 // Check the ref-qualifier.
3768 switch (Method->getRefQualifier()) {
3769 case RQ_None:
3770 // Do nothing; we don't care about lvalueness or rvalueness.
3771 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772
Douglas Gregor02824322011-01-26 19:30:28 +00003773 case RQ_LValue:
3774 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3775 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003777 ImplicitParamType);
3778 return ICS;
3779 }
3780 break;
3781
3782 case RQ_RValue:
3783 if (!FromClassification.isRValue()) {
3784 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003786 ImplicitParamType);
3787 return ICS;
3788 }
3789 break;
3790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791
Douglas Gregor436424c2008-11-18 23:14:02 +00003792 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003793 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003794 ICS.Standard.setAsIdentityConversion();
3795 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003796 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003797 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003798 ICS.Standard.ReferenceBinding = true;
3799 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003801 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003802 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3803 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3804 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003805 return ICS;
3806}
3807
3808/// PerformObjectArgumentInitialization - Perform initialization of
3809/// the implicit object parameter for the given Method with the given
3810/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003811ExprResult
3812Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003814 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003815 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003816 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003817 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003818 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003819
Douglas Gregor02824322011-01-26 19:30:28 +00003820 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003821 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003822 FromRecordType = PT->getPointeeType();
3823 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003824 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003825 } else {
3826 FromRecordType = From->getType();
3827 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003828 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003829 }
3830
John McCall6e9f8f62009-12-03 04:06:58 +00003831 // Note that we always use the true parent context when performing
3832 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003833 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003834 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3835 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003836 if (ICS.isBad()) {
3837 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3838 Qualifiers FromQs = FromRecordType.getQualifiers();
3839 Qualifiers ToQs = DestType.getQualifiers();
3840 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3841 if (CVR) {
3842 Diag(From->getSourceRange().getBegin(),
3843 diag::err_member_function_call_bad_cvr)
3844 << Method->getDeclName() << FromRecordType << (CVR - 1)
3845 << From->getSourceRange();
3846 Diag(Method->getLocation(), diag::note_previous_decl)
3847 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003848 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003849 }
3850 }
3851
Douglas Gregor436424c2008-11-18 23:14:02 +00003852 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003853 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003854 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003855 }
Mike Stump11289f42009-09-09 15:08:12 +00003856
John Wiegley01296292011-04-08 18:41:53 +00003857 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3858 ExprResult FromRes =
3859 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3860 if (FromRes.isInvalid())
3861 return ExprError();
3862 From = FromRes.take();
3863 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003864
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003865 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003866 From = ImpCastExprToType(From, DestType, CK_NoOp,
3867 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3868 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003869}
3870
Douglas Gregor5fb53972009-01-14 15:45:31 +00003871/// TryContextuallyConvertToBool - Attempt to contextually convert the
3872/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003873static ImplicitConversionSequence
3874TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003875 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003876 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003877 // FIXME: Are these flags correct?
3878 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003879 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003880 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003881 /*CStyle=*/false,
3882 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003883}
3884
3885/// PerformContextuallyConvertToBool - Perform a contextual conversion
3886/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003887ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003888 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003889 if (!ICS.isBad())
3890 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891
Fariborz Jahanian76197412009-11-18 18:26:29 +00003892 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003893 return Diag(From->getSourceRange().getBegin(),
3894 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003895 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003896 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003897}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898
John McCallfec112d2011-09-09 06:11:02 +00003899/// dropPointerConversions - If the given standard conversion sequence
3900/// involves any pointer conversions, remove them. This may change
3901/// the result type of the conversion sequence.
3902static void dropPointerConversion(StandardConversionSequence &SCS) {
3903 if (SCS.Second == ICK_Pointer_Conversion) {
3904 SCS.Second = ICK_Identity;
3905 SCS.Third = ICK_Identity;
3906 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
3907 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003908}
John McCall5c32be02010-08-24 20:38:10 +00003909
John McCallfec112d2011-09-09 06:11:02 +00003910/// TryContextuallyConvertToObjCPointer - Attempt to contextually
3911/// convert the expression From to an Objective-C pointer type.
3912static ImplicitConversionSequence
3913TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
3914 // Do an implicit conversion to 'id'.
3915 QualType Ty = S.Context.getObjCIdType();
3916 ImplicitConversionSequence ICS
3917 = TryImplicitConversion(S, From, Ty,
3918 // FIXME: Are these flags correct?
3919 /*SuppressUserConversions=*/false,
3920 /*AllowExplicit=*/true,
3921 /*InOverloadResolution=*/false,
3922 /*CStyle=*/false,
3923 /*AllowObjCWritebackConversion=*/false);
3924
3925 // Strip off any final conversions to 'id'.
3926 switch (ICS.getKind()) {
3927 case ImplicitConversionSequence::BadConversion:
3928 case ImplicitConversionSequence::AmbiguousConversion:
3929 case ImplicitConversionSequence::EllipsisConversion:
3930 break;
3931
3932 case ImplicitConversionSequence::UserDefinedConversion:
3933 dropPointerConversion(ICS.UserDefined.After);
3934 break;
3935
3936 case ImplicitConversionSequence::StandardConversion:
3937 dropPointerConversion(ICS.Standard);
3938 break;
3939 }
3940
3941 return ICS;
3942}
3943
3944/// PerformContextuallyConvertToObjCPointer - Perform a contextual
3945/// conversion of the expression From to an Objective-C pointer type.
3946ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003947 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00003948 ImplicitConversionSequence ICS =
3949 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003950 if (!ICS.isBad())
3951 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003952 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003953}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003954
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003956/// enumeration type.
3957///
3958/// This routine will attempt to convert an expression of class type to an
3959/// integral or enumeration type, if that class type only has a single
3960/// conversion to an integral or enumeration type.
3961///
Douglas Gregor4799d032010-06-30 00:20:43 +00003962/// \param Loc The source location of the construct that requires the
3963/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003964///
Douglas Gregor4799d032010-06-30 00:20:43 +00003965/// \param FromE The expression we're converting from.
3966///
3967/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3968/// have integral or enumeration type.
3969///
3970/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3971/// incomplete class type.
3972///
3973/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3974/// explicit conversion function (because no implicit conversion functions
3975/// were available). This is a recovery mode.
3976///
3977/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3978/// showing which conversion was picked.
3979///
3980/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3981/// conversion function that could convert to integral or enumeration type.
3982///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003984/// usable conversion function.
3985///
3986/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3987/// function, which may be an extension in this case.
3988///
3989/// \returns The expression, converted to an integral or enumeration type if
3990/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991ExprResult
John McCallb268a282010-08-23 23:25:46 +00003992Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003993 const PartialDiagnostic &NotIntDiag,
3994 const PartialDiagnostic &IncompleteDiag,
3995 const PartialDiagnostic &ExplicitConvDiag,
3996 const PartialDiagnostic &ExplicitConvNote,
3997 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003998 const PartialDiagnostic &AmbigNote,
3999 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004000 // We can't perform any more checking for type-dependent expressions.
4001 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004002 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004004 // If the expression already has integral or enumeration type, we're golden.
4005 QualType T = From->getType();
4006 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004007 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004008
4009 // FIXME: Check for missing '()' if T is a function type?
4010
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004011 // 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 +00004012 // expression of integral or enumeration type.
4013 const RecordType *RecordTy = T->getAs<RecordType>();
4014 if (!RecordTy || !getLangOptions().CPlusPlus) {
4015 Diag(Loc, NotIntDiag)
4016 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004017 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004020 // We must have a complete class type.
4021 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004022 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004024 // Look for a conversion to an integral or enumeration type.
4025 UnresolvedSet<4> ViableConversions;
4026 UnresolvedSet<4> ExplicitConversions;
4027 const UnresolvedSetImpl *Conversions
4028 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004029
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004030 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031 E = Conversions->end();
4032 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004033 ++I) {
4034 if (CXXConversionDecl *Conversion
4035 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4036 if (Conversion->getConversionType().getNonReferenceType()
4037 ->isIntegralOrEnumerationType()) {
4038 if (Conversion->isExplicit())
4039 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4040 else
4041 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4042 }
4043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004045 switch (ViableConversions.size()) {
4046 case 0:
4047 if (ExplicitConversions.size() == 1) {
4048 DeclAccessPair Found = ExplicitConversions[0];
4049 CXXConversionDecl *Conversion
4050 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004052 // The user probably meant to invoke the given explicit
4053 // conversion; use it.
4054 QualType ConvTy
4055 = Conversion->getConversionType().getNonReferenceType();
4056 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004057 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004059 Diag(Loc, ExplicitConvDiag)
4060 << T << ConvTy
4061 << FixItHint::CreateInsertion(From->getLocStart(),
4062 "static_cast<" + TypeStr + ">(")
4063 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4064 ")");
4065 Diag(Conversion->getLocation(), ExplicitConvNote)
4066 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067
4068 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004069 // explicit conversion function.
4070 if (isSFINAEContext())
4071 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004073 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00004074 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
4075 if (Result.isInvalid())
4076 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077
Douglas Gregor668443e2011-01-20 00:18:04 +00004078 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004081 // We'll complain below about a non-integral condition type.
4082 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004084 case 1: {
4085 // Apply this conversion.
4086 DeclAccessPair Found = ViableConversions[0];
4087 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
Douglas Gregor4799d032010-06-30 00:20:43 +00004089 CXXConversionDecl *Conversion
4090 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4091 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004092 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004093 if (ConvDiag.getDiagID()) {
4094 if (isSFINAEContext())
4095 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096
Douglas Gregor4799d032010-06-30 00:20:43 +00004097 Diag(Loc, ConvDiag)
4098 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100
Douglas Gregor668443e2011-01-20 00:18:04 +00004101 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004102 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00004103 if (Result.isInvalid())
4104 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105
Douglas Gregor668443e2011-01-20 00:18:04 +00004106 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004107 break;
4108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004109
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004110 default:
4111 Diag(Loc, AmbigDiag)
4112 << T << From->getSourceRange();
4113 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4114 CXXConversionDecl *Conv
4115 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4116 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4117 Diag(Conv->getLocation(), AmbigNote)
4118 << ConvTy->isEnumeralType() << ConvTy;
4119 }
John McCallb268a282010-08-23 23:25:46 +00004120 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122
Douglas Gregor5823da32010-06-29 23:25:20 +00004123 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004124 Diag(Loc, NotIntDiag)
4125 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004126
John McCallb268a282010-08-23 23:25:46 +00004127 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004128}
4129
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004130/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004131/// candidate functions, using the given function call arguments. If
4132/// @p SuppressUserConversions, then don't allow user-defined
4133/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004134///
4135/// \para PartialOverloading true if we are performing "partial" overloading
4136/// based on an incomplete set of function arguments. This feature is used by
4137/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004138void
4139Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004140 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004141 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004142 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004143 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004144 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004145 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004146 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004147 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004148 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004149 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004150
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004151 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004152 if (!isa<CXXConstructorDecl>(Method)) {
4153 // If we get here, it's because we're calling a member function
4154 // that is named without a member access expression (e.g.,
4155 // "this->f") that was either written explicitly or created
4156 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004157 // function, e.g., X::f(). We use an empty type for the implied
4158 // object argument (C++ [over.call.func]p3), and the acting context
4159 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004160 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004162 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004163 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004164 return;
4165 }
4166 // We treat a constructor like a non-member function, since its object
4167 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004168 }
4169
Douglas Gregorff7028a2009-11-13 23:59:09 +00004170 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004171 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004172
Douglas Gregor27381f32009-11-23 12:27:39 +00004173 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004174 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004175
Douglas Gregorffe14e32009-11-14 01:20:54 +00004176 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4177 // C++ [class.copy]p3:
4178 // A member function template is never instantiated to perform the copy
4179 // of a class object to an object of its class type.
4180 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004182 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004183 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4184 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004185 return;
4186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004187
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004188 // Add this candidate
4189 CandidateSet.push_back(OverloadCandidate());
4190 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004191 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004192 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004193 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004194 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004195 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004196 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004198 unsigned NumArgsInProto = Proto->getNumArgs();
4199
4200 // (C++ 13.3.2p2): A candidate function having fewer than m
4201 // parameters is viable only if it has an ellipsis in its parameter
4202 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004204 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004205 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004206 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004207 return;
4208 }
4209
4210 // (C++ 13.3.2p2): A candidate function having more than m parameters
4211 // is viable only if the (m+1)st parameter has a default argument
4212 // (8.3.6). For the purposes of overload resolution, the
4213 // parameter list is truncated on the right, so that there are
4214 // exactly m parameters.
4215 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004216 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004217 // Not enough arguments.
4218 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004219 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004220 return;
4221 }
4222
4223 // Determine the implicit conversion sequences for each of the
4224 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004225 Candidate.Conversions.resize(NumArgs);
4226 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4227 if (ArgIdx < NumArgsInProto) {
4228 // (C++ 13.3.2p3): for F to be a viable function, there shall
4229 // exist for each argument an implicit conversion sequence
4230 // (13.3.3.1) that converts that argument to the corresponding
4231 // parameter of F.
4232 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004233 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004234 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004236 /*InOverloadResolution=*/true,
4237 /*AllowObjCWritebackConversion=*/
4238 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004239 if (Candidate.Conversions[ArgIdx].isBad()) {
4240 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004241 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004242 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004243 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004244 } else {
4245 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4246 // argument for which there is no corresponding parameter is
4247 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004248 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004249 }
4250 }
4251}
4252
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004253/// \brief Add all of the function declarations in the given function set to
4254/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004255void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004256 Expr **Args, unsigned NumArgs,
4257 OverloadCandidateSet& CandidateSet,
4258 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004259 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004260 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4261 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004262 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004263 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004264 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004265 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004266 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004267 CandidateSet, SuppressUserConversions);
4268 else
John McCalla0296f72010-03-19 07:35:19 +00004269 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004270 SuppressUserConversions);
4271 } else {
John McCalla0296f72010-03-19 07:35:19 +00004272 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004273 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4274 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004275 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004276 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004277 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004279 Args[0]->Classify(Context),
4280 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004281 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004282 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004283 else
John McCalla0296f72010-03-19 07:35:19 +00004284 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004285 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004286 Args, NumArgs, CandidateSet,
4287 SuppressUserConversions);
4288 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004289 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004290}
4291
John McCallf0f1cf02009-11-17 07:50:12 +00004292/// AddMethodCandidate - Adds a named decl (which is some kind of
4293/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004294void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004295 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004296 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004297 Expr **Args, unsigned NumArgs,
4298 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004299 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004300 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004301 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004302
4303 if (isa<UsingShadowDecl>(Decl))
4304 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305
John McCallf0f1cf02009-11-17 07:50:12 +00004306 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4307 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4308 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004309 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4310 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004311 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004312 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004313 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004314 } else {
John McCalla0296f72010-03-19 07:35:19 +00004315 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004316 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004317 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004318 }
4319}
4320
Douglas Gregor436424c2008-11-18 23:14:02 +00004321/// AddMethodCandidate - Adds the given C++ member function to the set
4322/// of candidate functions, using the given function call arguments
4323/// and the object argument (@c Object). For example, in a call
4324/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4325/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4326/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004327/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004328void
John McCalla0296f72010-03-19 07:35:19 +00004329Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004330 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004331 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004332 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004333 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004334 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004335 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004336 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004337 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004338 assert(!isa<CXXConstructorDecl>(Method) &&
4339 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004340
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004341 if (!CandidateSet.isNewCandidate(Method))
4342 return;
4343
Douglas Gregor27381f32009-11-23 12:27:39 +00004344 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004345 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004346
Douglas Gregor436424c2008-11-18 23:14:02 +00004347 // Add this candidate
4348 CandidateSet.push_back(OverloadCandidate());
4349 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004350 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004351 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004352 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004353 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004354 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004355
4356 unsigned NumArgsInProto = Proto->getNumArgs();
4357
4358 // (C++ 13.3.2p2): A candidate function having fewer than m
4359 // parameters is viable only if it has an ellipsis in its parameter
4360 // list (8.3.5).
4361 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4362 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004363 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004364 return;
4365 }
4366
4367 // (C++ 13.3.2p2): A candidate function having more than m parameters
4368 // is viable only if the (m+1)st parameter has a default argument
4369 // (8.3.6). For the purposes of overload resolution, the
4370 // parameter list is truncated on the right, so that there are
4371 // exactly m parameters.
4372 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4373 if (NumArgs < MinRequiredArgs) {
4374 // Not enough arguments.
4375 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004376 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004377 return;
4378 }
4379
4380 Candidate.Viable = true;
4381 Candidate.Conversions.resize(NumArgs + 1);
4382
John McCall6e9f8f62009-12-03 04:06:58 +00004383 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004384 // The implicit object argument is ignored.
4385 Candidate.IgnoreObjectArgument = true;
4386 else {
4387 // Determine the implicit conversion sequence for the object
4388 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004389 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004390 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4391 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004392 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004393 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004394 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004395 return;
4396 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004397 }
4398
4399 // Determine the implicit conversion sequences for each of the
4400 // arguments.
4401 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4402 if (ArgIdx < NumArgsInProto) {
4403 // (C++ 13.3.2p3): for F to be a viable function, there shall
4404 // exist for each argument an implicit conversion sequence
4405 // (13.3.3.1) that converts that argument to the corresponding
4406 // parameter of F.
4407 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004408 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004409 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004411 /*InOverloadResolution=*/true,
4412 /*AllowObjCWritebackConversion=*/
4413 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004414 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004415 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004416 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004417 break;
4418 }
4419 } else {
4420 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4421 // argument for which there is no corresponding parameter is
4422 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004423 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004424 }
4425 }
4426}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
Douglas Gregor97628d62009-08-21 00:16:32 +00004428/// \brief Add a C++ member function template as a candidate to the candidate
4429/// set, using template argument deduction to produce an appropriate member
4430/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004431void
Douglas Gregor97628d62009-08-21 00:16:32 +00004432Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004433 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004434 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004435 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004436 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004437 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004438 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004439 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004440 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004441 if (!CandidateSet.isNewCandidate(MethodTmpl))
4442 return;
4443
Douglas Gregor97628d62009-08-21 00:16:32 +00004444 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004445 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004446 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004447 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004448 // candidate functions in the usual way.113) A given name can refer to one
4449 // or more function templates and also to a set of overloaded non-template
4450 // functions. In such a case, the candidate functions generated from each
4451 // function template are combined with the set of non-template candidate
4452 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004453 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004454 FunctionDecl *Specialization = 0;
4455 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004456 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004457 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004458 CandidateSet.push_back(OverloadCandidate());
4459 OverloadCandidate &Candidate = CandidateSet.back();
4460 Candidate.FoundDecl = FoundDecl;
4461 Candidate.Function = MethodTmpl->getTemplatedDecl();
4462 Candidate.Viable = false;
4463 Candidate.FailureKind = ovl_fail_bad_deduction;
4464 Candidate.IsSurrogate = false;
4465 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004466 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004468 Info);
4469 return;
4470 }
Mike Stump11289f42009-09-09 15:08:12 +00004471
Douglas Gregor97628d62009-08-21 00:16:32 +00004472 // Add the function template specialization produced by template argument
4473 // deduction as a candidate.
4474 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004475 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004476 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004477 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004478 ActingContext, ObjectType, ObjectClassification,
4479 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004480}
4481
Douglas Gregor05155d82009-08-21 23:19:43 +00004482/// \brief Add a C++ function template specialization as a candidate
4483/// in the candidate set, using template argument deduction to produce
4484/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004485void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004486Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004487 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004488 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004489 Expr **Args, unsigned NumArgs,
4490 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004491 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004492 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4493 return;
4494
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004495 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004496 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004497 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004498 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004499 // candidate functions in the usual way.113) A given name can refer to one
4500 // or more function templates and also to a set of overloaded non-template
4501 // functions. In such a case, the candidate functions generated from each
4502 // function template are combined with the set of non-template candidate
4503 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004504 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004505 FunctionDecl *Specialization = 0;
4506 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004507 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004508 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004509 CandidateSet.push_back(OverloadCandidate());
4510 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004511 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004512 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4513 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004514 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004515 Candidate.IsSurrogate = false;
4516 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004517 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004519 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004520 return;
4521 }
Mike Stump11289f42009-09-09 15:08:12 +00004522
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004523 // Add the function template specialization produced by template argument
4524 // deduction as a candidate.
4525 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004526 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004527 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004528}
Mike Stump11289f42009-09-09 15:08:12 +00004529
Douglas Gregora1f013e2008-11-07 22:36:19 +00004530/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004531/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004532/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004533/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004534/// (which may or may not be the same type as the type that the
4535/// conversion function produces).
4536void
4537Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004538 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004539 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004540 Expr *From, QualType ToType,
4541 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004542 assert(!Conversion->getDescribedFunctionTemplate() &&
4543 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004544 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004545 if (!CandidateSet.isNewCandidate(Conversion))
4546 return;
4547
Douglas Gregor27381f32009-11-23 12:27:39 +00004548 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004549 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004550
Douglas Gregora1f013e2008-11-07 22:36:19 +00004551 // Add this candidate
4552 CandidateSet.push_back(OverloadCandidate());
4553 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004554 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004555 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004556 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004557 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004558 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004559 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004560 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004561 Candidate.Viable = true;
4562 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004563 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004564
Douglas Gregor6affc782010-08-19 15:37:02 +00004565 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566 // For conversion functions, the function is considered to be a member of
4567 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004568 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004569 //
4570 // Determine the implicit conversion sequence for the implicit
4571 // object parameter.
4572 QualType ImplicitParamType = From->getType();
4573 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4574 ImplicitParamType = FromPtrType->getPointeeType();
4575 CXXRecordDecl *ConversionContext
4576 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004578 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004579 = TryObjectArgumentInitialization(*this, From->getType(),
4580 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004581 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004582
John McCall0d1da222010-01-12 00:44:57 +00004583 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004584 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004585 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004586 return;
4587 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004588
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004590 // derived to base as such conversions are given Conversion Rank. They only
4591 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4592 QualType FromCanon
4593 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4594 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4595 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4596 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004597 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004598 return;
4599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600
Douglas Gregora1f013e2008-11-07 22:36:19 +00004601 // To determine what the conversion from the result of calling the
4602 // conversion function to the type we're eventually trying to
4603 // convert to (ToType), we need to synthesize a call to the
4604 // conversion function and attempt copy initialization from it. This
4605 // makes sure that we get the right semantics with respect to
4606 // lvalues/rvalues and the type. Fortunately, we can allocate this
4607 // call on the stack and we don't need its arguments to be
4608 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004609 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004610 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004611 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4612 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004613 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004614 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004615
Richard Smith48d24642011-07-13 22:53:21 +00004616 QualType ConversionType = Conversion->getConversionType();
4617 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004618 Candidate.Viable = false;
4619 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4620 return;
4621 }
4622
Richard Smith48d24642011-07-13 22:53:21 +00004623 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004624
Mike Stump11289f42009-09-09 15:08:12 +00004625 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004626 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4627 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004628 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004629 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004630 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004631 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004632 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004633 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004634 /*InOverloadResolution=*/false,
4635 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004636
John McCall0d1da222010-01-12 00:44:57 +00004637 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004638 case ImplicitConversionSequence::StandardConversion:
4639 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004641 // C++ [over.ics.user]p3:
4642 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004643 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004644 // shall have exact match rank.
4645 if (Conversion->getPrimaryTemplate() &&
4646 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4647 Candidate.Viable = false;
4648 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650
Douglas Gregorcba72b12011-01-21 05:18:22 +00004651 // C++0x [dcl.init.ref]p5:
4652 // In the second case, if the reference is an rvalue reference and
4653 // the second standard conversion sequence of the user-defined
4654 // conversion sequence includes an lvalue-to-rvalue conversion, the
4655 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004657 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4658 Candidate.Viable = false;
4659 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4660 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004661 break;
4662
4663 case ImplicitConversionSequence::BadConversion:
4664 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004665 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004666 break;
4667
4668 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004669 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00004670 "Can only end up with a standard conversion sequence or failure");
4671 }
4672}
4673
Douglas Gregor05155d82009-08-21 23:19:43 +00004674/// \brief Adds a conversion function template specialization
4675/// candidate to the overload set, using template argument deduction
4676/// to deduce the template arguments of the conversion function
4677/// template from the type that we are converting to (C++
4678/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004679void
Douglas Gregor05155d82009-08-21 23:19:43 +00004680Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004681 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004682 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004683 Expr *From, QualType ToType,
4684 OverloadCandidateSet &CandidateSet) {
4685 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4686 "Only conversion function templates permitted here");
4687
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004688 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4689 return;
4690
John McCallbc077cf2010-02-08 23:07:23 +00004691 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004692 CXXConversionDecl *Specialization = 0;
4693 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004694 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004695 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004696 CandidateSet.push_back(OverloadCandidate());
4697 OverloadCandidate &Candidate = CandidateSet.back();
4698 Candidate.FoundDecl = FoundDecl;
4699 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4700 Candidate.Viable = false;
4701 Candidate.FailureKind = ovl_fail_bad_deduction;
4702 Candidate.IsSurrogate = false;
4703 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004704 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004706 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004707 return;
4708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709
Douglas Gregor05155d82009-08-21 23:19:43 +00004710 // Add the conversion function template specialization produced by
4711 // template argument deduction as a candidate.
4712 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004713 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004714 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004715}
4716
Douglas Gregorab7897a2008-11-19 22:57:39 +00004717/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4718/// converts the given @c Object to a function pointer via the
4719/// conversion function @c Conversion, and then attempts to call it
4720/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4721/// the type of function that we'll eventually be calling.
4722void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004723 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004724 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004725 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004726 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004727 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004728 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004729 if (!CandidateSet.isNewCandidate(Conversion))
4730 return;
4731
Douglas Gregor27381f32009-11-23 12:27:39 +00004732 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004733 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004734
Douglas Gregorab7897a2008-11-19 22:57:39 +00004735 CandidateSet.push_back(OverloadCandidate());
4736 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004737 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004738 Candidate.Function = 0;
4739 Candidate.Surrogate = Conversion;
4740 Candidate.Viable = true;
4741 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004742 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004743 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004744 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004745
4746 // Determine the implicit conversion sequence for the implicit
4747 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004748 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004749 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004750 Object->Classify(Context),
4751 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004752 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004753 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004754 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004755 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004756 return;
4757 }
4758
4759 // The first conversion is actually a user-defined conversion whose
4760 // first conversion is ObjectInit's standard conversion (which is
4761 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004762 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004763 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004764 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004765 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00004766 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004767 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004768 = Candidate.Conversions[0].UserDefined.Before;
4769 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4770
Mike Stump11289f42009-09-09 15:08:12 +00004771 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004772 unsigned NumArgsInProto = Proto->getNumArgs();
4773
4774 // (C++ 13.3.2p2): A candidate function having fewer than m
4775 // parameters is viable only if it has an ellipsis in its parameter
4776 // list (8.3.5).
4777 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4778 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004779 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004780 return;
4781 }
4782
4783 // Function types don't have any default arguments, so just check if
4784 // we have enough arguments.
4785 if (NumArgs < NumArgsInProto) {
4786 // Not enough arguments.
4787 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004788 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004789 return;
4790 }
4791
4792 // Determine the implicit conversion sequences for each of the
4793 // arguments.
4794 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4795 if (ArgIdx < NumArgsInProto) {
4796 // (C++ 13.3.2p3): for F to be a viable function, there shall
4797 // exist for each argument an implicit conversion sequence
4798 // (13.3.3.1) that converts that argument to the corresponding
4799 // parameter of F.
4800 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004801 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004802 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004803 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00004804 /*InOverloadResolution=*/false,
4805 /*AllowObjCWritebackConversion=*/
4806 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004807 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004808 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004809 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004810 break;
4811 }
4812 } else {
4813 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4814 // argument for which there is no corresponding parameter is
4815 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004816 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004817 }
4818 }
4819}
4820
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004821/// \brief Add overload candidates for overloaded operators that are
4822/// member functions.
4823///
4824/// Add the overloaded operator candidates that are member functions
4825/// for the operator Op that was used in an operator expression such
4826/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4827/// CandidateSet will store the added overload candidates. (C++
4828/// [over.match.oper]).
4829void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4830 SourceLocation OpLoc,
4831 Expr **Args, unsigned NumArgs,
4832 OverloadCandidateSet& CandidateSet,
4833 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004834 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4835
4836 // C++ [over.match.oper]p3:
4837 // For a unary operator @ with an operand of a type whose
4838 // cv-unqualified version is T1, and for a binary operator @ with
4839 // a left operand of a type whose cv-unqualified version is T1 and
4840 // a right operand of a type whose cv-unqualified version is T2,
4841 // three sets of candidate functions, designated member
4842 // candidates, non-member candidates and built-in candidates, are
4843 // constructed as follows:
4844 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004845
4846 // -- If T1 is a class type, the set of member candidates is the
4847 // result of the qualified lookup of T1::operator@
4848 // (13.3.1.1.1); otherwise, the set of member candidates is
4849 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004850 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004851 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004852 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004853 return;
Mike Stump11289f42009-09-09 15:08:12 +00004854
John McCall27b18f82009-11-17 02:14:36 +00004855 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4856 LookupQualifiedName(Operators, T1Rec->getDecl());
4857 Operators.suppressDiagnostics();
4858
Mike Stump11289f42009-09-09 15:08:12 +00004859 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004860 OperEnd = Operators.end();
4861 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004862 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004863 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004864 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004865 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004866 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004867 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004868}
4869
Douglas Gregora11693b2008-11-12 17:17:38 +00004870/// AddBuiltinCandidate - Add a candidate for a built-in
4871/// operator. ResultTy and ParamTys are the result and parameter types
4872/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004873/// arguments being passed to the candidate. IsAssignmentOperator
4874/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004875/// operator. NumContextualBoolArguments is the number of arguments
4876/// (at the beginning of the argument list) that will be contextually
4877/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004878void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004879 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004880 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004881 bool IsAssignmentOperator,
4882 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004883 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004884 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004885
Douglas Gregora11693b2008-11-12 17:17:38 +00004886 // Add this candidate
4887 CandidateSet.push_back(OverloadCandidate());
4888 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004889 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004890 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004891 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004892 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004893 Candidate.BuiltinTypes.ResultTy = ResultTy;
4894 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4895 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4896
4897 // Determine the implicit conversion sequences for each of the
4898 // arguments.
4899 Candidate.Viable = true;
4900 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004901 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004902 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004903 // C++ [over.match.oper]p4:
4904 // For the built-in assignment operators, conversions of the
4905 // left operand are restricted as follows:
4906 // -- no temporaries are introduced to hold the left operand, and
4907 // -- no user-defined conversions are applied to the left
4908 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004909 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004910 //
4911 // We block these conversions by turning off user-defined
4912 // conversions, since that is the only way that initialization of
4913 // a reference to a non-class type can occur from something that
4914 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004915 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004916 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004917 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004918 Candidate.Conversions[ArgIdx]
4919 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004920 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004921 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004922 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004923 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00004924 /*InOverloadResolution=*/false,
4925 /*AllowObjCWritebackConversion=*/
4926 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004927 }
John McCall0d1da222010-01-12 00:44:57 +00004928 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004929 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004930 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004931 break;
4932 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004933 }
4934}
4935
4936/// BuiltinCandidateTypeSet - A set of types that will be used for the
4937/// candidate operator functions for built-in operators (C++
4938/// [over.built]). The types are separated into pointer types and
4939/// enumeration types.
4940class BuiltinCandidateTypeSet {
4941 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004942 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004943
4944 /// PointerTypes - The set of pointer types that will be used in the
4945 /// built-in candidates.
4946 TypeSet PointerTypes;
4947
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004948 /// MemberPointerTypes - The set of member pointer types that will be
4949 /// used in the built-in candidates.
4950 TypeSet MemberPointerTypes;
4951
Douglas Gregora11693b2008-11-12 17:17:38 +00004952 /// EnumerationTypes - The set of enumeration types that will be
4953 /// used in the built-in candidates.
4954 TypeSet EnumerationTypes;
4955
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004957 /// candidates.
4958 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004959
4960 /// \brief A flag indicating non-record types are viable candidates
4961 bool HasNonRecordTypes;
4962
4963 /// \brief A flag indicating whether either arithmetic or enumeration types
4964 /// were present in the candidate set.
4965 bool HasArithmeticOrEnumeralTypes;
4966
Douglas Gregor80af3132011-05-21 23:15:46 +00004967 /// \brief A flag indicating whether the nullptr type was present in the
4968 /// candidate set.
4969 bool HasNullPtrType;
4970
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004971 /// Sema - The semantic analysis instance where we are building the
4972 /// candidate type set.
4973 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004974
Douglas Gregora11693b2008-11-12 17:17:38 +00004975 /// Context - The AST context in which we will build the type sets.
4976 ASTContext &Context;
4977
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004978 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4979 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004980 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004981
4982public:
4983 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004984 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004985
Mike Stump11289f42009-09-09 15:08:12 +00004986 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004987 : HasNonRecordTypes(false),
4988 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00004989 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00004990 SemaRef(SemaRef),
4991 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004992
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004993 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004994 SourceLocation Loc,
4995 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004996 bool AllowExplicitConversions,
4997 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004998
4999 /// pointer_begin - First pointer type found;
5000 iterator pointer_begin() { return PointerTypes.begin(); }
5001
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005002 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005003 iterator pointer_end() { return PointerTypes.end(); }
5004
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005005 /// member_pointer_begin - First member pointer type found;
5006 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5007
5008 /// member_pointer_end - Past the last member pointer type found;
5009 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5010
Douglas Gregora11693b2008-11-12 17:17:38 +00005011 /// enumeration_begin - First enumeration type found;
5012 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5013
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005014 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005015 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005016
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005017 iterator vector_begin() { return VectorTypes.begin(); }
5018 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005019
5020 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5021 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005022 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005023};
5024
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005025/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005026/// the set of pointer types along with any more-qualified variants of
5027/// that type. For example, if @p Ty is "int const *", this routine
5028/// will add "int const *", "int const volatile *", "int const
5029/// restrict *", and "int const volatile restrict *" to the set of
5030/// pointer types. Returns true if the add of @p Ty itself succeeded,
5031/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005032///
5033/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005034bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005035BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5036 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005037
Douglas Gregora11693b2008-11-12 17:17:38 +00005038 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005039 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005040 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005042 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005043 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005044 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005045 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005046 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005047 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005048 buildObjCPtr = true;
5049 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005050 else
David Blaikie83d382b2011-09-23 05:06:16 +00005051 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005052 }
5053 else
5054 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055
Sebastian Redl4990a632009-11-18 20:39:26 +00005056 // Don't add qualified variants of arrays. For one, they're not allowed
5057 // (the qualifier would sink to the element type), and for another, the
5058 // only overload situation where it matters is subscript or pointer +- int,
5059 // and those shouldn't have qualifier variants anyway.
5060 if (PointeeTy->isArrayType())
5061 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005062 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005063 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005064 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005065 bool hasVolatile = VisibleQuals.hasVolatile();
5066 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
John McCall8ccfcb52009-09-24 19:53:00 +00005068 // Iterate through all strict supersets of BaseCVR.
5069 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5070 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005071 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5072 // in the types.
5073 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5074 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005075 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005076 if (!buildObjCPtr)
5077 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5078 else
5079 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005080 }
5081
5082 return true;
5083}
5084
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005085/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5086/// to the set of pointer types along with any more-qualified variants of
5087/// that type. For example, if @p Ty is "int const *", this routine
5088/// will add "int const *", "int const volatile *", "int const
5089/// restrict *", and "int const volatile restrict *" to the set of
5090/// pointer types. Returns true if the add of @p Ty itself succeeded,
5091/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005092///
5093/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005094bool
5095BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5096 QualType Ty) {
5097 // Insert this type.
5098 if (!MemberPointerTypes.insert(Ty))
5099 return false;
5100
John McCall8ccfcb52009-09-24 19:53:00 +00005101 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5102 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005103
John McCall8ccfcb52009-09-24 19:53:00 +00005104 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005105 // Don't add qualified variants of arrays. For one, they're not allowed
5106 // (the qualifier would sink to the element type), and for another, the
5107 // only overload situation where it matters is subscript or pointer +- int,
5108 // and those shouldn't have qualifier variants anyway.
5109 if (PointeeTy->isArrayType())
5110 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005111 const Type *ClassTy = PointerTy->getClass();
5112
5113 // Iterate through all strict supersets of the pointee type's CVR
5114 // qualifiers.
5115 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5116 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5117 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005118
John McCall8ccfcb52009-09-24 19:53:00 +00005119 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005120 MemberPointerTypes.insert(
5121 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005122 }
5123
5124 return true;
5125}
5126
Douglas Gregora11693b2008-11-12 17:17:38 +00005127/// AddTypesConvertedFrom - Add each of the types to which the type @p
5128/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005129/// primarily interested in pointer types and enumeration types. We also
5130/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005131/// AllowUserConversions is true if we should look at the conversion
5132/// functions of a class type, and AllowExplicitConversions if we
5133/// should also include the explicit conversion functions of a class
5134/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005135void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005136BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005137 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005138 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005139 bool AllowExplicitConversions,
5140 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005141 // Only deal with canonical types.
5142 Ty = Context.getCanonicalType(Ty);
5143
5144 // Look through reference types; they aren't part of the type of an
5145 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005146 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005147 Ty = RefTy->getPointeeType();
5148
John McCall33ddac02011-01-19 10:06:00 +00005149 // If we're dealing with an array type, decay to the pointer.
5150 if (Ty->isArrayType())
5151 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5152
5153 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005154 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005155
Chandler Carruth00a38332010-12-13 01:44:01 +00005156 // Flag if we ever add a non-record type.
5157 const RecordType *TyRec = Ty->getAs<RecordType>();
5158 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5159
Chandler Carruth00a38332010-12-13 01:44:01 +00005160 // Flag if we encounter an arithmetic type.
5161 HasArithmeticOrEnumeralTypes =
5162 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5163
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005164 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5165 PointerTypes.insert(Ty);
5166 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005167 // Insert our type, and its more-qualified variants, into the set
5168 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005169 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005170 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005171 } else if (Ty->isMemberPointerType()) {
5172 // Member pointers are far easier, since the pointee can't be converted.
5173 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5174 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005175 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005176 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005177 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005178 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005179 // We treat vector types as arithmetic types in many contexts as an
5180 // extension.
5181 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005182 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005183 } else if (Ty->isNullPtrType()) {
5184 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005185 } else if (AllowUserConversions && TyRec) {
5186 // No conversion functions in incomplete types.
5187 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5188 return;
Mike Stump11289f42009-09-09 15:08:12 +00005189
Chandler Carruth00a38332010-12-13 01:44:01 +00005190 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5191 const UnresolvedSetImpl *Conversions
5192 = ClassDecl->getVisibleConversionFunctions();
5193 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5194 E = Conversions->end(); I != E; ++I) {
5195 NamedDecl *D = I.getDecl();
5196 if (isa<UsingShadowDecl>(D))
5197 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005198
Chandler Carruth00a38332010-12-13 01:44:01 +00005199 // Skip conversion function templates; they don't tell us anything
5200 // about which builtin types we can convert to.
5201 if (isa<FunctionTemplateDecl>(D))
5202 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005203
Chandler Carruth00a38332010-12-13 01:44:01 +00005204 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5205 if (AllowExplicitConversions || !Conv->isExplicit()) {
5206 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5207 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005208 }
5209 }
5210 }
5211}
5212
Douglas Gregor84605ae2009-08-24 13:43:27 +00005213/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5214/// the volatile- and non-volatile-qualified assignment operators for the
5215/// given type to the candidate set.
5216static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5217 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005218 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005219 unsigned NumArgs,
5220 OverloadCandidateSet &CandidateSet) {
5221 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005222
Douglas Gregor84605ae2009-08-24 13:43:27 +00005223 // T& operator=(T&, T)
5224 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5225 ParamTypes[1] = T;
5226 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5227 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005228
Douglas Gregor84605ae2009-08-24 13:43:27 +00005229 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5230 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005231 ParamTypes[0]
5232 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005233 ParamTypes[1] = T;
5234 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005235 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005236 }
5237}
Mike Stump11289f42009-09-09 15:08:12 +00005238
Sebastian Redl1054fae2009-10-25 17:03:50 +00005239/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5240/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005241static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5242 Qualifiers VRQuals;
5243 const RecordType *TyRec;
5244 if (const MemberPointerType *RHSMPType =
5245 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005246 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005247 else
5248 TyRec = ArgExpr->getType()->getAs<RecordType>();
5249 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005250 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005251 VRQuals.addVolatile();
5252 VRQuals.addRestrict();
5253 return VRQuals;
5254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005256 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005257 if (!ClassDecl->hasDefinition())
5258 return VRQuals;
5259
John McCallad371252010-01-20 00:46:10 +00005260 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005261 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005262
John McCallad371252010-01-20 00:46:10 +00005263 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005264 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005265 NamedDecl *D = I.getDecl();
5266 if (isa<UsingShadowDecl>(D))
5267 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5268 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005269 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5270 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5271 CanTy = ResTypeRef->getPointeeType();
5272 // Need to go down the pointer/mempointer chain and add qualifiers
5273 // as see them.
5274 bool done = false;
5275 while (!done) {
5276 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5277 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005278 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005279 CanTy->getAs<MemberPointerType>())
5280 CanTy = ResTypeMPtr->getPointeeType();
5281 else
5282 done = true;
5283 if (CanTy.isVolatileQualified())
5284 VRQuals.addVolatile();
5285 if (CanTy.isRestrictQualified())
5286 VRQuals.addRestrict();
5287 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5288 return VRQuals;
5289 }
5290 }
5291 }
5292 return VRQuals;
5293}
John McCall52872982010-11-13 05:51:15 +00005294
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005295namespace {
John McCall52872982010-11-13 05:51:15 +00005296
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005297/// \brief Helper class to manage the addition of builtin operator overload
5298/// candidates. It provides shared state and utility methods used throughout
5299/// the process, as well as a helper method to add each group of builtin
5300/// operator overloads from the standard to a candidate set.
5301class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005302 // Common instance state available to all overload candidate addition methods.
5303 Sema &S;
5304 Expr **Args;
5305 unsigned NumArgs;
5306 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005307 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005308 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005309 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005310
Chandler Carruthc6586e52010-12-12 10:35:00 +00005311 // Define some constants used to index and iterate over the arithemetic types
5312 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005313 // The "promoted arithmetic types" are the arithmetic
5314 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005315 static const unsigned FirstIntegralType = 3;
5316 static const unsigned LastIntegralType = 18;
5317 static const unsigned FirstPromotedIntegralType = 3,
5318 LastPromotedIntegralType = 9;
5319 static const unsigned FirstPromotedArithmeticType = 0,
5320 LastPromotedArithmeticType = 9;
5321 static const unsigned NumArithmeticTypes = 18;
5322
Chandler Carruthc6586e52010-12-12 10:35:00 +00005323 /// \brief Get the canonical type for a given arithmetic type index.
5324 CanQualType getArithmeticType(unsigned index) {
5325 assert(index < NumArithmeticTypes);
5326 static CanQualType ASTContext::* const
5327 ArithmeticTypes[NumArithmeticTypes] = {
5328 // Start of promoted types.
5329 &ASTContext::FloatTy,
5330 &ASTContext::DoubleTy,
5331 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005332
Chandler Carruthc6586e52010-12-12 10:35:00 +00005333 // Start of integral types.
5334 &ASTContext::IntTy,
5335 &ASTContext::LongTy,
5336 &ASTContext::LongLongTy,
5337 &ASTContext::UnsignedIntTy,
5338 &ASTContext::UnsignedLongTy,
5339 &ASTContext::UnsignedLongLongTy,
5340 // End of promoted types.
5341
5342 &ASTContext::BoolTy,
5343 &ASTContext::CharTy,
5344 &ASTContext::WCharTy,
5345 &ASTContext::Char16Ty,
5346 &ASTContext::Char32Ty,
5347 &ASTContext::SignedCharTy,
5348 &ASTContext::ShortTy,
5349 &ASTContext::UnsignedCharTy,
5350 &ASTContext::UnsignedShortTy,
5351 // End of integral types.
5352 // FIXME: What about complex?
5353 };
5354 return S.Context.*ArithmeticTypes[index];
5355 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005356
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005357 /// \brief Gets the canonical type resulting from the usual arithemetic
5358 /// converions for the given arithmetic types.
5359 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5360 // Accelerator table for performing the usual arithmetic conversions.
5361 // The rules are basically:
5362 // - if either is floating-point, use the wider floating-point
5363 // - if same signedness, use the higher rank
5364 // - if same size, use unsigned of the higher rank
5365 // - use the larger type
5366 // These rules, together with the axiom that higher ranks are
5367 // never smaller, are sufficient to precompute all of these results
5368 // *except* when dealing with signed types of higher rank.
5369 // (we could precompute SLL x UI for all known platforms, but it's
5370 // better not to make any assumptions).
5371 enum PromotedType {
5372 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5373 };
5374 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5375 [LastPromotedArithmeticType] = {
5376 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5377 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5378 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5379 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5380 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5381 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5382 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5383 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5384 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5385 };
5386
5387 assert(L < LastPromotedArithmeticType);
5388 assert(R < LastPromotedArithmeticType);
5389 int Idx = ConversionsTable[L][R];
5390
5391 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005392 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005393
5394 // Slow path: we need to compare widths.
5395 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005396 CanQualType LT = getArithmeticType(L),
5397 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005398 unsigned LW = S.Context.getIntWidth(LT),
5399 RW = S.Context.getIntWidth(RT);
5400
5401 // If they're different widths, use the signed type.
5402 if (LW > RW) return LT;
5403 else if (LW < RW) return RT;
5404
5405 // Otherwise, use the unsigned type of the signed type's rank.
5406 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5407 assert(L == SLL || R == SLL);
5408 return S.Context.UnsignedLongLongTy;
5409 }
5410
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005411 /// \brief Helper method to factor out the common pattern of adding overloads
5412 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005413 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5414 bool HasVolatile) {
5415 QualType ParamTypes[2] = {
5416 S.Context.getLValueReferenceType(CandidateTy),
5417 S.Context.IntTy
5418 };
5419
5420 // Non-volatile version.
5421 if (NumArgs == 1)
5422 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5423 else
5424 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5425
5426 // Use a heuristic to reduce number of builtin candidates in the set:
5427 // add volatile version only if there are conversions to a volatile type.
5428 if (HasVolatile) {
5429 ParamTypes[0] =
5430 S.Context.getLValueReferenceType(
5431 S.Context.getVolatileType(CandidateTy));
5432 if (NumArgs == 1)
5433 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5434 else
5435 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5436 }
5437 }
5438
5439public:
5440 BuiltinOperatorOverloadBuilder(
5441 Sema &S, Expr **Args, unsigned NumArgs,
5442 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005443 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005444 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005445 OverloadCandidateSet &CandidateSet)
5446 : S(S), Args(Args), NumArgs(NumArgs),
5447 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005448 HasArithmeticOrEnumeralCandidateType(
5449 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005450 CandidateTypes(CandidateTypes),
5451 CandidateSet(CandidateSet) {
5452 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005453 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005454 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005455 assert(getArithmeticType(LastPromotedIntegralType - 1)
5456 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005457 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005458 assert(getArithmeticType(FirstPromotedArithmeticType)
5459 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005460 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005461 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5462 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005463 "Invalid last promoted arithmetic type");
5464 }
5465
5466 // C++ [over.built]p3:
5467 //
5468 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5469 // is either volatile or empty, there exist candidate operator
5470 // functions of the form
5471 //
5472 // VQ T& operator++(VQ T&);
5473 // T operator++(VQ T&, int);
5474 //
5475 // C++ [over.built]p4:
5476 //
5477 // For every pair (T, VQ), where T is an arithmetic type other
5478 // than bool, and VQ is either volatile or empty, there exist
5479 // candidate operator functions of the form
5480 //
5481 // VQ T& operator--(VQ T&);
5482 // T operator--(VQ T&, int);
5483 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005484 if (!HasArithmeticOrEnumeralCandidateType)
5485 return;
5486
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005487 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5488 Arith < NumArithmeticTypes; ++Arith) {
5489 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005490 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005491 VisibleTypeConversionsQuals.hasVolatile());
5492 }
5493 }
5494
5495 // C++ [over.built]p5:
5496 //
5497 // For every pair (T, VQ), where T is a cv-qualified or
5498 // cv-unqualified object type, and VQ is either volatile or
5499 // empty, there exist candidate operator functions of the form
5500 //
5501 // T*VQ& operator++(T*VQ&);
5502 // T*VQ& operator--(T*VQ&);
5503 // T* operator++(T*VQ&, int);
5504 // T* operator--(T*VQ&, int);
5505 void addPlusPlusMinusMinusPointerOverloads() {
5506 for (BuiltinCandidateTypeSet::iterator
5507 Ptr = CandidateTypes[0].pointer_begin(),
5508 PtrEnd = CandidateTypes[0].pointer_end();
5509 Ptr != PtrEnd; ++Ptr) {
5510 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005511 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005512 continue;
5513
5514 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5515 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5516 VisibleTypeConversionsQuals.hasVolatile()));
5517 }
5518 }
5519
5520 // C++ [over.built]p6:
5521 // For every cv-qualified or cv-unqualified object type T, there
5522 // exist candidate operator functions of the form
5523 //
5524 // T& operator*(T*);
5525 //
5526 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005527 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005528 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005529 // T& operator*(T*);
5530 void addUnaryStarPointerOverloads() {
5531 for (BuiltinCandidateTypeSet::iterator
5532 Ptr = CandidateTypes[0].pointer_begin(),
5533 PtrEnd = CandidateTypes[0].pointer_end();
5534 Ptr != PtrEnd; ++Ptr) {
5535 QualType ParamTy = *Ptr;
5536 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005537 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5538 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005539
Douglas Gregor02824322011-01-26 19:30:28 +00005540 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5541 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5542 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005543
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005544 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5545 &ParamTy, Args, 1, CandidateSet);
5546 }
5547 }
5548
5549 // C++ [over.built]p9:
5550 // For every promoted arithmetic type T, there exist candidate
5551 // operator functions of the form
5552 //
5553 // T operator+(T);
5554 // T operator-(T);
5555 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005556 if (!HasArithmeticOrEnumeralCandidateType)
5557 return;
5558
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005559 for (unsigned Arith = FirstPromotedArithmeticType;
5560 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005561 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005562 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5563 }
5564
5565 // Extension: We also add these operators for vector types.
5566 for (BuiltinCandidateTypeSet::iterator
5567 Vec = CandidateTypes[0].vector_begin(),
5568 VecEnd = CandidateTypes[0].vector_end();
5569 Vec != VecEnd; ++Vec) {
5570 QualType VecTy = *Vec;
5571 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5572 }
5573 }
5574
5575 // C++ [over.built]p8:
5576 // For every type T, there exist candidate operator functions of
5577 // the form
5578 //
5579 // T* operator+(T*);
5580 void addUnaryPlusPointerOverloads() {
5581 for (BuiltinCandidateTypeSet::iterator
5582 Ptr = CandidateTypes[0].pointer_begin(),
5583 PtrEnd = CandidateTypes[0].pointer_end();
5584 Ptr != PtrEnd; ++Ptr) {
5585 QualType ParamTy = *Ptr;
5586 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5587 }
5588 }
5589
5590 // C++ [over.built]p10:
5591 // For every promoted integral type T, there exist candidate
5592 // operator functions of the form
5593 //
5594 // T operator~(T);
5595 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005596 if (!HasArithmeticOrEnumeralCandidateType)
5597 return;
5598
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005599 for (unsigned Int = FirstPromotedIntegralType;
5600 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005601 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005602 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5603 }
5604
5605 // Extension: We also add this operator for vector types.
5606 for (BuiltinCandidateTypeSet::iterator
5607 Vec = CandidateTypes[0].vector_begin(),
5608 VecEnd = CandidateTypes[0].vector_end();
5609 Vec != VecEnd; ++Vec) {
5610 QualType VecTy = *Vec;
5611 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5612 }
5613 }
5614
5615 // C++ [over.match.oper]p16:
5616 // For every pointer to member type T, there exist candidate operator
5617 // functions of the form
5618 //
5619 // bool operator==(T,T);
5620 // bool operator!=(T,T);
5621 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5622 /// Set of (canonical) types that we've already handled.
5623 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5624
5625 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5626 for (BuiltinCandidateTypeSet::iterator
5627 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5628 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5629 MemPtr != MemPtrEnd;
5630 ++MemPtr) {
5631 // Don't add the same builtin candidate twice.
5632 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5633 continue;
5634
5635 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5636 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5637 CandidateSet);
5638 }
5639 }
5640 }
5641
5642 // C++ [over.built]p15:
5643 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005644 // For every T, where T is an enumeration type, a pointer type, or
5645 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005646 //
5647 // bool operator<(T, T);
5648 // bool operator>(T, T);
5649 // bool operator<=(T, T);
5650 // bool operator>=(T, T);
5651 // bool operator==(T, T);
5652 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005653 void addRelationalPointerOrEnumeralOverloads() {
5654 // C++ [over.built]p1:
5655 // If there is a user-written candidate with the same name and parameter
5656 // types as a built-in candidate operator function, the built-in operator
5657 // function is hidden and is not included in the set of candidate
5658 // functions.
5659 //
5660 // The text is actually in a note, but if we don't implement it then we end
5661 // up with ambiguities when the user provides an overloaded operator for
5662 // an enumeration type. Note that only enumeration types have this problem,
5663 // so we track which enumeration types we've seen operators for. Also, the
5664 // only other overloaded operator with enumeration argumenst, operator=,
5665 // cannot be overloaded for enumeration types, so this is the only place
5666 // where we must suppress candidates like this.
5667 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5668 UserDefinedBinaryOperators;
5669
5670 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5671 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5672 CandidateTypes[ArgIdx].enumeration_end()) {
5673 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5674 CEnd = CandidateSet.end();
5675 C != CEnd; ++C) {
5676 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5677 continue;
5678
5679 QualType FirstParamType =
5680 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5681 QualType SecondParamType =
5682 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5683
5684 // Skip if either parameter isn't of enumeral type.
5685 if (!FirstParamType->isEnumeralType() ||
5686 !SecondParamType->isEnumeralType())
5687 continue;
5688
5689 // Add this operator to the set of known user-defined operators.
5690 UserDefinedBinaryOperators.insert(
5691 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5692 S.Context.getCanonicalType(SecondParamType)));
5693 }
5694 }
5695 }
5696
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005697 /// Set of (canonical) types that we've already handled.
5698 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5699
5700 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5701 for (BuiltinCandidateTypeSet::iterator
5702 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5703 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5704 Ptr != PtrEnd; ++Ptr) {
5705 // Don't add the same builtin candidate twice.
5706 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5707 continue;
5708
5709 QualType ParamTypes[2] = { *Ptr, *Ptr };
5710 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5711 CandidateSet);
5712 }
5713 for (BuiltinCandidateTypeSet::iterator
5714 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5715 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5716 Enum != EnumEnd; ++Enum) {
5717 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5718
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005719 // Don't add the same builtin candidate twice, or if a user defined
5720 // candidate exists.
5721 if (!AddedTypes.insert(CanonType) ||
5722 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5723 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005724 continue;
5725
5726 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005727 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5728 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005729 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005730
5731 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5732 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5733 if (AddedTypes.insert(NullPtrTy) &&
5734 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5735 NullPtrTy))) {
5736 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5737 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5738 CandidateSet);
5739 }
5740 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005741 }
5742 }
5743
5744 // C++ [over.built]p13:
5745 //
5746 // For every cv-qualified or cv-unqualified object type T
5747 // there exist candidate operator functions of the form
5748 //
5749 // T* operator+(T*, ptrdiff_t);
5750 // T& operator[](T*, ptrdiff_t); [BELOW]
5751 // T* operator-(T*, ptrdiff_t);
5752 // T* operator+(ptrdiff_t, T*);
5753 // T& operator[](ptrdiff_t, T*); [BELOW]
5754 //
5755 // C++ [over.built]p14:
5756 //
5757 // For every T, where T is a pointer to object type, there
5758 // exist candidate operator functions of the form
5759 //
5760 // ptrdiff_t operator-(T, T);
5761 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5762 /// Set of (canonical) types that we've already handled.
5763 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5764
5765 for (int Arg = 0; Arg < 2; ++Arg) {
5766 QualType AsymetricParamTypes[2] = {
5767 S.Context.getPointerDiffType(),
5768 S.Context.getPointerDiffType(),
5769 };
5770 for (BuiltinCandidateTypeSet::iterator
5771 Ptr = CandidateTypes[Arg].pointer_begin(),
5772 PtrEnd = CandidateTypes[Arg].pointer_end();
5773 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005774 QualType PointeeTy = (*Ptr)->getPointeeType();
5775 if (!PointeeTy->isObjectType())
5776 continue;
5777
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005778 AsymetricParamTypes[Arg] = *Ptr;
5779 if (Arg == 0 || Op == OO_Plus) {
5780 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5781 // T* operator+(ptrdiff_t, T*);
5782 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5783 CandidateSet);
5784 }
5785 if (Op == OO_Minus) {
5786 // ptrdiff_t operator-(T, T);
5787 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5788 continue;
5789
5790 QualType ParamTypes[2] = { *Ptr, *Ptr };
5791 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5792 Args, 2, CandidateSet);
5793 }
5794 }
5795 }
5796 }
5797
5798 // C++ [over.built]p12:
5799 //
5800 // For every pair of promoted arithmetic types L and R, there
5801 // exist candidate operator functions of the form
5802 //
5803 // LR operator*(L, R);
5804 // LR operator/(L, R);
5805 // LR operator+(L, R);
5806 // LR operator-(L, R);
5807 // bool operator<(L, R);
5808 // bool operator>(L, R);
5809 // bool operator<=(L, R);
5810 // bool operator>=(L, R);
5811 // bool operator==(L, R);
5812 // bool operator!=(L, R);
5813 //
5814 // where LR is the result of the usual arithmetic conversions
5815 // between types L and R.
5816 //
5817 // C++ [over.built]p24:
5818 //
5819 // For every pair of promoted arithmetic types L and R, there exist
5820 // candidate operator functions of the form
5821 //
5822 // LR operator?(bool, L, R);
5823 //
5824 // where LR is the result of the usual arithmetic conversions
5825 // between types L and R.
5826 // Our candidates ignore the first parameter.
5827 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005828 if (!HasArithmeticOrEnumeralCandidateType)
5829 return;
5830
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005831 for (unsigned Left = FirstPromotedArithmeticType;
5832 Left < LastPromotedArithmeticType; ++Left) {
5833 for (unsigned Right = FirstPromotedArithmeticType;
5834 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005835 QualType LandR[2] = { getArithmeticType(Left),
5836 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005837 QualType Result =
5838 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005839 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005840 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5841 }
5842 }
5843
5844 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5845 // conditional operator for vector types.
5846 for (BuiltinCandidateTypeSet::iterator
5847 Vec1 = CandidateTypes[0].vector_begin(),
5848 Vec1End = CandidateTypes[0].vector_end();
5849 Vec1 != Vec1End; ++Vec1) {
5850 for (BuiltinCandidateTypeSet::iterator
5851 Vec2 = CandidateTypes[1].vector_begin(),
5852 Vec2End = CandidateTypes[1].vector_end();
5853 Vec2 != Vec2End; ++Vec2) {
5854 QualType LandR[2] = { *Vec1, *Vec2 };
5855 QualType Result = S.Context.BoolTy;
5856 if (!isComparison) {
5857 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5858 Result = *Vec1;
5859 else
5860 Result = *Vec2;
5861 }
5862
5863 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5864 }
5865 }
5866 }
5867
5868 // C++ [over.built]p17:
5869 //
5870 // For every pair of promoted integral types L and R, there
5871 // exist candidate operator functions of the form
5872 //
5873 // LR operator%(L, R);
5874 // LR operator&(L, R);
5875 // LR operator^(L, R);
5876 // LR operator|(L, R);
5877 // L operator<<(L, R);
5878 // L operator>>(L, R);
5879 //
5880 // where LR is the result of the usual arithmetic conversions
5881 // between types L and R.
5882 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005883 if (!HasArithmeticOrEnumeralCandidateType)
5884 return;
5885
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005886 for (unsigned Left = FirstPromotedIntegralType;
5887 Left < LastPromotedIntegralType; ++Left) {
5888 for (unsigned Right = FirstPromotedIntegralType;
5889 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005890 QualType LandR[2] = { getArithmeticType(Left),
5891 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005892 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5893 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005894 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005895 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5896 }
5897 }
5898 }
5899
5900 // C++ [over.built]p20:
5901 //
5902 // For every pair (T, VQ), where T is an enumeration or
5903 // pointer to member type and VQ is either volatile or
5904 // empty, there exist candidate operator functions of the form
5905 //
5906 // VQ T& operator=(VQ T&, T);
5907 void addAssignmentMemberPointerOrEnumeralOverloads() {
5908 /// Set of (canonical) types that we've already handled.
5909 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5910
5911 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5912 for (BuiltinCandidateTypeSet::iterator
5913 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5914 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5915 Enum != EnumEnd; ++Enum) {
5916 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5917 continue;
5918
5919 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5920 CandidateSet);
5921 }
5922
5923 for (BuiltinCandidateTypeSet::iterator
5924 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5925 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5926 MemPtr != MemPtrEnd; ++MemPtr) {
5927 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5928 continue;
5929
5930 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5931 CandidateSet);
5932 }
5933 }
5934 }
5935
5936 // C++ [over.built]p19:
5937 //
5938 // For every pair (T, VQ), where T is any type and VQ is either
5939 // volatile or empty, there exist candidate operator functions
5940 // of the form
5941 //
5942 // T*VQ& operator=(T*VQ&, T*);
5943 //
5944 // C++ [over.built]p21:
5945 //
5946 // For every pair (T, VQ), where T is a cv-qualified or
5947 // cv-unqualified object type and VQ is either volatile or
5948 // empty, there exist candidate operator functions of the form
5949 //
5950 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5951 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5952 void addAssignmentPointerOverloads(bool isEqualOp) {
5953 /// Set of (canonical) types that we've already handled.
5954 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5955
5956 for (BuiltinCandidateTypeSet::iterator
5957 Ptr = CandidateTypes[0].pointer_begin(),
5958 PtrEnd = CandidateTypes[0].pointer_end();
5959 Ptr != PtrEnd; ++Ptr) {
5960 // If this is operator=, keep track of the builtin candidates we added.
5961 if (isEqualOp)
5962 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005963 else if (!(*Ptr)->getPointeeType()->isObjectType())
5964 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005965
5966 // non-volatile version
5967 QualType ParamTypes[2] = {
5968 S.Context.getLValueReferenceType(*Ptr),
5969 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5970 };
5971 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5972 /*IsAssigmentOperator=*/ isEqualOp);
5973
5974 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5975 VisibleTypeConversionsQuals.hasVolatile()) {
5976 // volatile version
5977 ParamTypes[0] =
5978 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5979 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5980 /*IsAssigmentOperator=*/isEqualOp);
5981 }
5982 }
5983
5984 if (isEqualOp) {
5985 for (BuiltinCandidateTypeSet::iterator
5986 Ptr = CandidateTypes[1].pointer_begin(),
5987 PtrEnd = CandidateTypes[1].pointer_end();
5988 Ptr != PtrEnd; ++Ptr) {
5989 // Make sure we don't add the same candidate twice.
5990 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5991 continue;
5992
Chandler Carruth8e543b32010-12-12 08:17:55 +00005993 QualType ParamTypes[2] = {
5994 S.Context.getLValueReferenceType(*Ptr),
5995 *Ptr,
5996 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005997
5998 // non-volatile version
5999 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6000 /*IsAssigmentOperator=*/true);
6001
6002 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6003 VisibleTypeConversionsQuals.hasVolatile()) {
6004 // volatile version
6005 ParamTypes[0] =
6006 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006007 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6008 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006009 }
6010 }
6011 }
6012 }
6013
6014 // C++ [over.built]p18:
6015 //
6016 // For every triple (L, VQ, R), where L is an arithmetic type,
6017 // VQ is either volatile or empty, and R is a promoted
6018 // arithmetic type, there exist candidate operator functions of
6019 // the form
6020 //
6021 // VQ L& operator=(VQ L&, R);
6022 // VQ L& operator*=(VQ L&, R);
6023 // VQ L& operator/=(VQ L&, R);
6024 // VQ L& operator+=(VQ L&, R);
6025 // VQ L& operator-=(VQ L&, R);
6026 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006027 if (!HasArithmeticOrEnumeralCandidateType)
6028 return;
6029
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006030 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6031 for (unsigned Right = FirstPromotedArithmeticType;
6032 Right < LastPromotedArithmeticType; ++Right) {
6033 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006034 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006035
6036 // Add this built-in operator as a candidate (VQ is empty).
6037 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006038 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006039 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6040 /*IsAssigmentOperator=*/isEqualOp);
6041
6042 // Add this built-in operator as a candidate (VQ is 'volatile').
6043 if (VisibleTypeConversionsQuals.hasVolatile()) {
6044 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006045 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006046 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006047 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6048 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006049 /*IsAssigmentOperator=*/isEqualOp);
6050 }
6051 }
6052 }
6053
6054 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6055 for (BuiltinCandidateTypeSet::iterator
6056 Vec1 = CandidateTypes[0].vector_begin(),
6057 Vec1End = CandidateTypes[0].vector_end();
6058 Vec1 != Vec1End; ++Vec1) {
6059 for (BuiltinCandidateTypeSet::iterator
6060 Vec2 = CandidateTypes[1].vector_begin(),
6061 Vec2End = CandidateTypes[1].vector_end();
6062 Vec2 != Vec2End; ++Vec2) {
6063 QualType ParamTypes[2];
6064 ParamTypes[1] = *Vec2;
6065 // Add this built-in operator as a candidate (VQ is empty).
6066 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6067 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6068 /*IsAssigmentOperator=*/isEqualOp);
6069
6070 // Add this built-in operator as a candidate (VQ is 'volatile').
6071 if (VisibleTypeConversionsQuals.hasVolatile()) {
6072 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6073 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006074 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6075 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006076 /*IsAssigmentOperator=*/isEqualOp);
6077 }
6078 }
6079 }
6080 }
6081
6082 // C++ [over.built]p22:
6083 //
6084 // For every triple (L, VQ, R), where L is an integral type, VQ
6085 // is either volatile or empty, and R is a promoted integral
6086 // type, there exist candidate operator functions of the form
6087 //
6088 // VQ L& operator%=(VQ L&, R);
6089 // VQ L& operator<<=(VQ L&, R);
6090 // VQ L& operator>>=(VQ L&, R);
6091 // VQ L& operator&=(VQ L&, R);
6092 // VQ L& operator^=(VQ L&, R);
6093 // VQ L& operator|=(VQ L&, R);
6094 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006095 if (!HasArithmeticOrEnumeralCandidateType)
6096 return;
6097
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006098 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6099 for (unsigned Right = FirstPromotedIntegralType;
6100 Right < LastPromotedIntegralType; ++Right) {
6101 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006102 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006103
6104 // Add this built-in operator as a candidate (VQ is empty).
6105 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006106 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006107 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6108 if (VisibleTypeConversionsQuals.hasVolatile()) {
6109 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006110 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006111 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6112 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6113 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6114 CandidateSet);
6115 }
6116 }
6117 }
6118 }
6119
6120 // C++ [over.operator]p23:
6121 //
6122 // There also exist candidate operator functions of the form
6123 //
6124 // bool operator!(bool);
6125 // bool operator&&(bool, bool);
6126 // bool operator||(bool, bool);
6127 void addExclaimOverload() {
6128 QualType ParamTy = S.Context.BoolTy;
6129 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6130 /*IsAssignmentOperator=*/false,
6131 /*NumContextualBoolArguments=*/1);
6132 }
6133 void addAmpAmpOrPipePipeOverload() {
6134 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6135 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6136 /*IsAssignmentOperator=*/false,
6137 /*NumContextualBoolArguments=*/2);
6138 }
6139
6140 // C++ [over.built]p13:
6141 //
6142 // For every cv-qualified or cv-unqualified object type T there
6143 // exist candidate operator functions of the form
6144 //
6145 // T* operator+(T*, ptrdiff_t); [ABOVE]
6146 // T& operator[](T*, ptrdiff_t);
6147 // T* operator-(T*, ptrdiff_t); [ABOVE]
6148 // T* operator+(ptrdiff_t, T*); [ABOVE]
6149 // T& operator[](ptrdiff_t, T*);
6150 void addSubscriptOverloads() {
6151 for (BuiltinCandidateTypeSet::iterator
6152 Ptr = CandidateTypes[0].pointer_begin(),
6153 PtrEnd = CandidateTypes[0].pointer_end();
6154 Ptr != PtrEnd; ++Ptr) {
6155 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6156 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006157 if (!PointeeType->isObjectType())
6158 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006159
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006160 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6161
6162 // T& operator[](T*, ptrdiff_t)
6163 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6164 }
6165
6166 for (BuiltinCandidateTypeSet::iterator
6167 Ptr = CandidateTypes[1].pointer_begin(),
6168 PtrEnd = CandidateTypes[1].pointer_end();
6169 Ptr != PtrEnd; ++Ptr) {
6170 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6171 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006172 if (!PointeeType->isObjectType())
6173 continue;
6174
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006175 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6176
6177 // T& operator[](ptrdiff_t, T*)
6178 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6179 }
6180 }
6181
6182 // C++ [over.built]p11:
6183 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6184 // C1 is the same type as C2 or is a derived class of C2, T is an object
6185 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6186 // there exist candidate operator functions of the form
6187 //
6188 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6189 //
6190 // where CV12 is the union of CV1 and CV2.
6191 void addArrowStarOverloads() {
6192 for (BuiltinCandidateTypeSet::iterator
6193 Ptr = CandidateTypes[0].pointer_begin(),
6194 PtrEnd = CandidateTypes[0].pointer_end();
6195 Ptr != PtrEnd; ++Ptr) {
6196 QualType C1Ty = (*Ptr);
6197 QualType C1;
6198 QualifierCollector Q1;
6199 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6200 if (!isa<RecordType>(C1))
6201 continue;
6202 // heuristic to reduce number of builtin candidates in the set.
6203 // Add volatile/restrict version only if there are conversions to a
6204 // volatile/restrict type.
6205 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6206 continue;
6207 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6208 continue;
6209 for (BuiltinCandidateTypeSet::iterator
6210 MemPtr = CandidateTypes[1].member_pointer_begin(),
6211 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6212 MemPtr != MemPtrEnd; ++MemPtr) {
6213 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6214 QualType C2 = QualType(mptr->getClass(), 0);
6215 C2 = C2.getUnqualifiedType();
6216 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6217 break;
6218 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6219 // build CV12 T&
6220 QualType T = mptr->getPointeeType();
6221 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6222 T.isVolatileQualified())
6223 continue;
6224 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6225 T.isRestrictQualified())
6226 continue;
6227 T = Q1.apply(S.Context, T);
6228 QualType ResultTy = S.Context.getLValueReferenceType(T);
6229 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6230 }
6231 }
6232 }
6233
6234 // Note that we don't consider the first argument, since it has been
6235 // contextually converted to bool long ago. The candidates below are
6236 // therefore added as binary.
6237 //
6238 // C++ [over.built]p25:
6239 // For every type T, where T is a pointer, pointer-to-member, or scoped
6240 // enumeration type, there exist candidate operator functions of the form
6241 //
6242 // T operator?(bool, T, T);
6243 //
6244 void addConditionalOperatorOverloads() {
6245 /// Set of (canonical) types that we've already handled.
6246 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6247
6248 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6249 for (BuiltinCandidateTypeSet::iterator
6250 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6251 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6252 Ptr != PtrEnd; ++Ptr) {
6253 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6254 continue;
6255
6256 QualType ParamTypes[2] = { *Ptr, *Ptr };
6257 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6258 }
6259
6260 for (BuiltinCandidateTypeSet::iterator
6261 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6262 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6263 MemPtr != MemPtrEnd; ++MemPtr) {
6264 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6265 continue;
6266
6267 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6268 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6269 }
6270
6271 if (S.getLangOptions().CPlusPlus0x) {
6272 for (BuiltinCandidateTypeSet::iterator
6273 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6274 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6275 Enum != EnumEnd; ++Enum) {
6276 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6277 continue;
6278
6279 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6280 continue;
6281
6282 QualType ParamTypes[2] = { *Enum, *Enum };
6283 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6284 }
6285 }
6286 }
6287 }
6288};
6289
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006290} // end anonymous namespace
6291
6292/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6293/// operator overloads to the candidate set (C++ [over.built]), based
6294/// on the operator @p Op and the arguments given. For example, if the
6295/// operator is a binary '+', this routine might add "int
6296/// operator+(int, int)" to cover integer addition.
6297void
6298Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6299 SourceLocation OpLoc,
6300 Expr **Args, unsigned NumArgs,
6301 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006302 // Find all of the types that the arguments can convert to, but only
6303 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006304 // that make use of these types. Also record whether we encounter non-record
6305 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006306 Qualifiers VisibleTypeConversionsQuals;
6307 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006308 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6309 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006310
6311 bool HasNonRecordCandidateType = false;
6312 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006313 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006314 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6315 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6316 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6317 OpLoc,
6318 true,
6319 (Op == OO_Exclaim ||
6320 Op == OO_AmpAmp ||
6321 Op == OO_PipePipe),
6322 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006323 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6324 CandidateTypes[ArgIdx].hasNonRecordTypes();
6325 HasArithmeticOrEnumeralCandidateType =
6326 HasArithmeticOrEnumeralCandidateType ||
6327 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006328 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006329
Chandler Carruth00a38332010-12-13 01:44:01 +00006330 // Exit early when no non-record types have been added to the candidate set
6331 // for any of the arguments to the operator.
6332 if (!HasNonRecordCandidateType)
6333 return;
6334
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006335 // Setup an object to manage the common state for building overloads.
6336 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6337 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006338 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006339 CandidateTypes, CandidateSet);
6340
6341 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006342 switch (Op) {
6343 case OO_None:
6344 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006345 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006346
Chandler Carruth5184de02010-12-12 08:51:33 +00006347 case OO_New:
6348 case OO_Delete:
6349 case OO_Array_New:
6350 case OO_Array_Delete:
6351 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006352 llvm_unreachable(
6353 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006354
6355 case OO_Comma:
6356 case OO_Arrow:
6357 // C++ [over.match.oper]p3:
6358 // -- For the operator ',', the unary operator '&', or the
6359 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006360 break;
6361
6362 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006363 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006364 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006365 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006366
6367 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006368 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006369 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006370 } else {
6371 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6372 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6373 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006374 break;
6375
Chandler Carruth5184de02010-12-12 08:51:33 +00006376 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006377 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006378 OpBuilder.addUnaryStarPointerOverloads();
6379 else
6380 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6381 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006382
Chandler Carruth5184de02010-12-12 08:51:33 +00006383 case OO_Slash:
6384 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006385 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006386
6387 case OO_PlusPlus:
6388 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006389 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6390 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006391 break;
6392
Douglas Gregor84605ae2009-08-24 13:43:27 +00006393 case OO_EqualEqual:
6394 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006395 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006396 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006397
Douglas Gregora11693b2008-11-12 17:17:38 +00006398 case OO_Less:
6399 case OO_Greater:
6400 case OO_LessEqual:
6401 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006402 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006403 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6404 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006405
Douglas Gregora11693b2008-11-12 17:17:38 +00006406 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006407 case OO_Caret:
6408 case OO_Pipe:
6409 case OO_LessLess:
6410 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006411 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006412 break;
6413
Chandler Carruth5184de02010-12-12 08:51:33 +00006414 case OO_Amp: // '&' is either unary or binary
6415 if (NumArgs == 1)
6416 // C++ [over.match.oper]p3:
6417 // -- For the operator ',', the unary operator '&', or the
6418 // operator '->', the built-in candidates set is empty.
6419 break;
6420
6421 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6422 break;
6423
6424 case OO_Tilde:
6425 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6426 break;
6427
Douglas Gregora11693b2008-11-12 17:17:38 +00006428 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006429 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006430 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006431
6432 case OO_PlusEqual:
6433 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006434 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006435 // Fall through.
6436
6437 case OO_StarEqual:
6438 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006439 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006440 break;
6441
6442 case OO_PercentEqual:
6443 case OO_LessLessEqual:
6444 case OO_GreaterGreaterEqual:
6445 case OO_AmpEqual:
6446 case OO_CaretEqual:
6447 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006448 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006449 break;
6450
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006451 case OO_Exclaim:
6452 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006453 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006454
Douglas Gregora11693b2008-11-12 17:17:38 +00006455 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006456 case OO_PipePipe:
6457 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006458 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006459
6460 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006461 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006462 break;
6463
6464 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006465 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006466 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006467
6468 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006469 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006470 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6471 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006472 }
6473}
6474
Douglas Gregore254f902009-02-04 00:32:51 +00006475/// \brief Add function candidates found via argument-dependent lookup
6476/// to the set of overloading candidates.
6477///
6478/// This routine performs argument-dependent name lookup based on the
6479/// given function name (which may also be an operator name) and adds
6480/// all of the overload candidates found by ADL to the overload
6481/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006482void
Douglas Gregore254f902009-02-04 00:32:51 +00006483Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006484 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006485 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006486 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006487 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006488 bool PartialOverloading,
6489 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006490 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006491
John McCall91f61fc2010-01-26 06:04:06 +00006492 // FIXME: This approach for uniquing ADL results (and removing
6493 // redundant candidates from the set) relies on pointer-equality,
6494 // which means we need to key off the canonical decl. However,
6495 // always going back to the canonical decl might not get us the
6496 // right set of default arguments. What default arguments are
6497 // we supposed to consider on ADL candidates, anyway?
6498
Douglas Gregorcabea402009-09-22 15:41:20 +00006499 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006500 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6501 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006502
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006503 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006504 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6505 CandEnd = CandidateSet.end();
6506 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006507 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006508 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006509 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006510 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006511 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006512
6513 // For each of the ADL candidates we found, add it to the overload
6514 // set.
John McCall8fe68082010-01-26 07:16:45 +00006515 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006516 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006517 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006518 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006519 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006520
John McCalla0296f72010-03-19 07:35:19 +00006521 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006522 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006523 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006524 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006525 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006526 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006527 }
Douglas Gregore254f902009-02-04 00:32:51 +00006528}
6529
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006530/// isBetterOverloadCandidate - Determines whether the first overload
6531/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006532bool
John McCall5c32be02010-08-24 20:38:10 +00006533isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006534 const OverloadCandidate &Cand1,
6535 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006536 SourceLocation Loc,
6537 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006538 // Define viable functions to be better candidates than non-viable
6539 // functions.
6540 if (!Cand2.Viable)
6541 return Cand1.Viable;
6542 else if (!Cand1.Viable)
6543 return false;
6544
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006545 // C++ [over.match.best]p1:
6546 //
6547 // -- if F is a static member function, ICS1(F) is defined such
6548 // that ICS1(F) is neither better nor worse than ICS1(G) for
6549 // any function G, and, symmetrically, ICS1(G) is neither
6550 // better nor worse than ICS1(F).
6551 unsigned StartArg = 0;
6552 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6553 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006554
Douglas Gregord3cb3562009-07-07 23:38:56 +00006555 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006556 // A viable function F1 is defined to be a better function than another
6557 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006558 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006559 unsigned NumArgs = Cand1.Conversions.size();
6560 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6561 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006562 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006563 switch (CompareImplicitConversionSequences(S,
6564 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006565 Cand2.Conversions[ArgIdx])) {
6566 case ImplicitConversionSequence::Better:
6567 // Cand1 has a better conversion sequence.
6568 HasBetterConversion = true;
6569 break;
6570
6571 case ImplicitConversionSequence::Worse:
6572 // Cand1 can't be better than Cand2.
6573 return false;
6574
6575 case ImplicitConversionSequence::Indistinguishable:
6576 // Do nothing.
6577 break;
6578 }
6579 }
6580
Mike Stump11289f42009-09-09 15:08:12 +00006581 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006582 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006583 if (HasBetterConversion)
6584 return true;
6585
Mike Stump11289f42009-09-09 15:08:12 +00006586 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006587 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006588 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006589 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6590 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006591
6592 // -- F1 and F2 are function template specializations, and the function
6593 // template for F1 is more specialized than the template for F2
6594 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006595 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006596 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006597 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006598 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006599 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6600 Cand2.Function->getPrimaryTemplate(),
6601 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006603 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006604 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006605 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006607
Douglas Gregora1f013e2008-11-07 22:36:19 +00006608 // -- the context is an initialization by user-defined conversion
6609 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6610 // from the return type of F1 to the destination type (i.e.,
6611 // the type of the entity being initialized) is a better
6612 // conversion sequence than the standard conversion sequence
6613 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006614 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006615 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006616 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006617 switch (CompareStandardConversionSequences(S,
6618 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006619 Cand2.FinalConversion)) {
6620 case ImplicitConversionSequence::Better:
6621 // Cand1 has a better conversion sequence.
6622 return true;
6623
6624 case ImplicitConversionSequence::Worse:
6625 // Cand1 can't be better than Cand2.
6626 return false;
6627
6628 case ImplicitConversionSequence::Indistinguishable:
6629 // Do nothing
6630 break;
6631 }
6632 }
6633
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006634 return false;
6635}
6636
Mike Stump11289f42009-09-09 15:08:12 +00006637/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006638/// within an overload candidate set.
6639///
6640/// \param CandidateSet the set of candidate functions.
6641///
6642/// \param Loc the location of the function name (or operator symbol) for
6643/// which overload resolution occurs.
6644///
Mike Stump11289f42009-09-09 15:08:12 +00006645/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006646/// function, Best points to the candidate function found.
6647///
6648/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006649OverloadingResult
6650OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006651 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006652 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006653 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006654 Best = end();
6655 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6656 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006658 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006659 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006660 }
6661
6662 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006663 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006664 return OR_No_Viable_Function;
6665
6666 // Make sure that this function is better than every other viable
6667 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006668 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006669 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006670 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006671 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006672 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006673 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006674 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006675 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006676 }
Mike Stump11289f42009-09-09 15:08:12 +00006677
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006678 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006679 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006680 (Best->Function->isDeleted() ||
6681 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006682 return OR_Deleted;
6683
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006684 return OR_Success;
6685}
6686
John McCall53262c92010-01-12 02:15:36 +00006687namespace {
6688
6689enum OverloadCandidateKind {
6690 oc_function,
6691 oc_method,
6692 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006693 oc_function_template,
6694 oc_method_template,
6695 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006696 oc_implicit_default_constructor,
6697 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006698 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006699 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006700 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006701 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006702};
6703
John McCalle1ac8d12010-01-13 00:25:19 +00006704OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6705 FunctionDecl *Fn,
6706 std::string &Description) {
6707 bool isTemplate = false;
6708
6709 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6710 isTemplate = true;
6711 Description = S.getTemplateArgumentBindingsText(
6712 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6713 }
John McCallfd0b2f82010-01-06 09:43:14 +00006714
6715 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006716 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006717 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006718
Sebastian Redl08905022011-02-05 19:23:19 +00006719 if (Ctor->getInheritedConstructor())
6720 return oc_implicit_inherited_constructor;
6721
Alexis Hunt119c10e2011-05-25 23:16:36 +00006722 if (Ctor->isDefaultConstructor())
6723 return oc_implicit_default_constructor;
6724
6725 if (Ctor->isMoveConstructor())
6726 return oc_implicit_move_constructor;
6727
6728 assert(Ctor->isCopyConstructor() &&
6729 "unexpected sort of implicit constructor");
6730 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006731 }
6732
6733 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6734 // This actually gets spelled 'candidate function' for now, but
6735 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006736 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006737 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006738
Alexis Hunt119c10e2011-05-25 23:16:36 +00006739 if (Meth->isMoveAssignmentOperator())
6740 return oc_implicit_move_assignment;
6741
Douglas Gregorec3bec02010-09-27 22:37:28 +00006742 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006743 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006744 return oc_implicit_copy_assignment;
6745 }
6746
John McCalle1ac8d12010-01-13 00:25:19 +00006747 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006748}
6749
Sebastian Redl08905022011-02-05 19:23:19 +00006750void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6751 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6752 if (!Ctor) return;
6753
6754 Ctor = Ctor->getInheritedConstructor();
6755 if (!Ctor) return;
6756
6757 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6758}
6759
John McCall53262c92010-01-12 02:15:36 +00006760} // end anonymous namespace
6761
6762// Notes the location of an overload candidate.
6763void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006764 std::string FnDesc;
6765 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6766 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6767 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006768 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006769}
6770
Douglas Gregorb491ed32011-02-19 21:32:49 +00006771//Notes the location of all overload candidates designated through
6772// OverloadedExpr
6773void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6774 assert(OverloadedExpr->getType() == Context.OverloadTy);
6775
6776 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6777 OverloadExpr *OvlExpr = Ovl.Expression;
6778
6779 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6780 IEnd = OvlExpr->decls_end();
6781 I != IEnd; ++I) {
6782 if (FunctionTemplateDecl *FunTmpl =
6783 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6784 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6785 } else if (FunctionDecl *Fun
6786 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6787 NoteOverloadCandidate(Fun);
6788 }
6789 }
6790}
6791
John McCall0d1da222010-01-12 00:44:57 +00006792/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6793/// "lead" diagnostic; it will be given two arguments, the source and
6794/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006795void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6796 Sema &S,
6797 SourceLocation CaretLoc,
6798 const PartialDiagnostic &PDiag) const {
6799 S.Diag(CaretLoc, PDiag)
6800 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006801 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006802 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6803 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006804 }
John McCall12f97bc2010-01-08 04:41:39 +00006805}
6806
John McCall0d1da222010-01-12 00:44:57 +00006807namespace {
6808
John McCall6a61b522010-01-13 09:16:55 +00006809void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6810 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6811 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006812 assert(Cand->Function && "for now, candidate must be a function");
6813 FunctionDecl *Fn = Cand->Function;
6814
6815 // There's a conversion slot for the object argument if this is a
6816 // non-constructor method. Note that 'I' corresponds the
6817 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006818 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006819 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006820 if (I == 0)
6821 isObjectArgument = true;
6822 else
6823 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006824 }
6825
John McCalle1ac8d12010-01-13 00:25:19 +00006826 std::string FnDesc;
6827 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6828
John McCall6a61b522010-01-13 09:16:55 +00006829 Expr *FromExpr = Conv.Bad.FromExpr;
6830 QualType FromTy = Conv.Bad.getFromType();
6831 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006832
John McCallfb7ad0f2010-02-02 02:42:52 +00006833 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006834 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006835 Expr *E = FromExpr->IgnoreParens();
6836 if (isa<UnaryOperator>(E))
6837 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006838 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006839
6840 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6841 << (unsigned) FnKind << FnDesc
6842 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6843 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006844 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006845 return;
6846 }
6847
John McCall6d174642010-01-23 08:10:49 +00006848 // Do some hand-waving analysis to see if the non-viability is due
6849 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006850 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6851 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6852 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6853 CToTy = RT->getPointeeType();
6854 else {
6855 // TODO: detect and diagnose the full richness of const mismatches.
6856 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6857 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6858 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6859 }
6860
6861 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6862 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6863 // It is dumb that we have to do this here.
6864 while (isa<ArrayType>(CFromTy))
6865 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6866 while (isa<ArrayType>(CToTy))
6867 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6868
6869 Qualifiers FromQs = CFromTy.getQualifiers();
6870 Qualifiers ToQs = CToTy.getQualifiers();
6871
6872 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6873 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6874 << (unsigned) FnKind << FnDesc
6875 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6876 << FromTy
6877 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6878 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006879 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006880 return;
6881 }
6882
John McCall31168b02011-06-15 23:02:42 +00006883 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006884 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00006885 << (unsigned) FnKind << FnDesc
6886 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6887 << FromTy
6888 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6889 << (unsigned) isObjectArgument << I+1;
6890 MaybeEmitInheritedConstructorNote(S, Fn);
6891 return;
6892 }
6893
Douglas Gregoraec25842011-04-26 23:16:46 +00006894 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6895 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6896 << (unsigned) FnKind << FnDesc
6897 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6898 << FromTy
6899 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6900 << (unsigned) isObjectArgument << I+1;
6901 MaybeEmitInheritedConstructorNote(S, Fn);
6902 return;
6903 }
6904
John McCall47000992010-01-14 03:28:57 +00006905 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6906 assert(CVR && "unexpected qualifiers mismatch");
6907
6908 if (isObjectArgument) {
6909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6910 << (unsigned) FnKind << FnDesc
6911 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6912 << FromTy << (CVR - 1);
6913 } else {
6914 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6915 << (unsigned) FnKind << FnDesc
6916 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6917 << FromTy << (CVR - 1) << I+1;
6918 }
Sebastian Redl08905022011-02-05 19:23:19 +00006919 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006920 return;
6921 }
6922
Sebastian Redla72462c2011-09-24 17:48:32 +00006923 // Special diagnostic for failure to convert an initializer list, since
6924 // telling the user that it has type void is not useful.
6925 if (FromExpr && isa<InitListExpr>(FromExpr)) {
6926 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
6927 << (unsigned) FnKind << FnDesc
6928 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6929 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6930 MaybeEmitInheritedConstructorNote(S, Fn);
6931 return;
6932 }
6933
John McCall6d174642010-01-23 08:10:49 +00006934 // Diagnose references or pointers to incomplete types differently,
6935 // since it's far from impossible that the incompleteness triggered
6936 // the failure.
6937 QualType TempFromTy = FromTy.getNonReferenceType();
6938 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6939 TempFromTy = PTy->getPointeeType();
6940 if (TempFromTy->isIncompleteType()) {
6941 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6942 << (unsigned) FnKind << FnDesc
6943 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6944 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006945 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006946 return;
6947 }
6948
Douglas Gregor56f2e342010-06-30 23:01:39 +00006949 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006950 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006951 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6952 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6953 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6954 FromPtrTy->getPointeeType()) &&
6955 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6956 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006958 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006959 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006960 }
6961 } else if (const ObjCObjectPointerType *FromPtrTy
6962 = FromTy->getAs<ObjCObjectPointerType>()) {
6963 if (const ObjCObjectPointerType *ToPtrTy
6964 = ToTy->getAs<ObjCObjectPointerType>())
6965 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6966 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6967 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6968 FromPtrTy->getPointeeType()) &&
6969 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006970 BaseToDerivedConversion = 2;
6971 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6972 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6973 !FromTy->isIncompleteType() &&
6974 !ToRefTy->getPointeeType()->isIncompleteType() &&
6975 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6976 BaseToDerivedConversion = 3;
6977 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006978
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006979 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006980 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006981 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006982 << (unsigned) FnKind << FnDesc
6983 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006984 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006985 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006986 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006987 return;
6988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00006990 if (isa<ObjCObjectPointerType>(CFromTy) &&
6991 isa<PointerType>(CToTy)) {
6992 Qualifiers FromQs = CFromTy.getQualifiers();
6993 Qualifiers ToQs = CToTy.getQualifiers();
6994 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
6995 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
6996 << (unsigned) FnKind << FnDesc
6997 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6998 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6999 MaybeEmitInheritedConstructorNote(S, Fn);
7000 return;
7001 }
7002 }
7003
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007004 // Emit the generic diagnostic and, optionally, add the hints to it.
7005 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7006 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007007 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007008 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7009 << (unsigned) (Cand->Fix.Kind);
7010
7011 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007012 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007013 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7014 HI != HE; ++HI)
7015 FDiag << *HI;
7016 S.Diag(Fn->getLocation(), FDiag);
7017
Sebastian Redl08905022011-02-05 19:23:19 +00007018 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007019}
7020
7021void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7022 unsigned NumFormalArgs) {
7023 // TODO: treat calls to a missing default constructor as a special case
7024
7025 FunctionDecl *Fn = Cand->Function;
7026 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7027
7028 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007030 // With invalid overloaded operators, it's possible that we think we
7031 // have an arity mismatch when it fact it looks like we have the
7032 // right number of arguments, because only overloaded operators have
7033 // the weird behavior of overloading member and non-member functions.
7034 // Just don't report anything.
7035 if (Fn->isInvalidDecl() &&
7036 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7037 return;
7038
John McCall6a61b522010-01-13 09:16:55 +00007039 // at least / at most / exactly
7040 unsigned mode, modeCount;
7041 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007042 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7043 (Cand->FailureKind == ovl_fail_bad_deduction &&
7044 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007045 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007046 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007047 mode = 0; // "at least"
7048 else
7049 mode = 2; // "exactly"
7050 modeCount = MinParams;
7051 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007052 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7053 (Cand->FailureKind == ovl_fail_bad_deduction &&
7054 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007055 if (MinParams != FnTy->getNumArgs())
7056 mode = 1; // "at most"
7057 else
7058 mode = 2; // "exactly"
7059 modeCount = FnTy->getNumArgs();
7060 }
7061
7062 std::string Description;
7063 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7064
7065 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007066 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007067 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007068 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007069}
7070
John McCall8b9ed552010-02-01 18:53:26 +00007071/// Diagnose a failed template-argument deduction.
7072void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7073 Expr **Args, unsigned NumArgs) {
7074 FunctionDecl *Fn = Cand->Function; // pattern
7075
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007076 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007077 NamedDecl *ParamD;
7078 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7079 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7080 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007081 switch (Cand->DeductionFailure.Result) {
7082 case Sema::TDK_Success:
7083 llvm_unreachable("TDK_success while diagnosing bad deduction");
7084
7085 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007086 assert(ParamD && "no parameter found for incomplete deduction result");
7087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7088 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007089 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007090 return;
7091 }
7092
John McCall42d7d192010-08-05 09:05:08 +00007093 case Sema::TDK_Underqualified: {
7094 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7095 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7096
7097 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7098
7099 // Param will have been canonicalized, but it should just be a
7100 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007101 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007102 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007103 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007104 assert(S.Context.hasSameType(Param, NonCanonParam));
7105
7106 // Arg has also been canonicalized, but there's nothing we can do
7107 // about that. It also doesn't matter as much, because it won't
7108 // have any template parameters in it (because deduction isn't
7109 // done on dependent types).
7110 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7111
7112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7113 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007114 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007115 return;
7116 }
7117
7118 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007119 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007120 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007121 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007122 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007123 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007124 which = 1;
7125 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007126 which = 2;
7127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007129 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007130 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007131 << *Cand->DeductionFailure.getFirstArg()
7132 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007133 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007134 return;
7135 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007136
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007137 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007138 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007139 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007140 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007141 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7142 << ParamD->getDeclName();
7143 else {
7144 int index = 0;
7145 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7146 index = TTP->getIndex();
7147 else if (NonTypeTemplateParmDecl *NTTP
7148 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7149 index = NTTP->getIndex();
7150 else
7151 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007152 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007153 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7154 << (index + 1);
7155 }
Sebastian Redl08905022011-02-05 19:23:19 +00007156 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007157 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007158
Douglas Gregor02eb4832010-05-08 18:13:28 +00007159 case Sema::TDK_TooManyArguments:
7160 case Sema::TDK_TooFewArguments:
7161 DiagnoseArityMismatch(S, Cand, NumArgs);
7162 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007163
7164 case Sema::TDK_InstantiationDepth:
7165 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007166 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007167 return;
7168
7169 case Sema::TDK_SubstitutionFailure: {
7170 std::string ArgString;
7171 if (TemplateArgumentList *Args
7172 = Cand->DeductionFailure.getTemplateArgumentList())
7173 ArgString = S.getTemplateArgumentBindingsText(
7174 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7175 *Args);
7176 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7177 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007178 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007179 return;
7180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007181
John McCall8b9ed552010-02-01 18:53:26 +00007182 // TODO: diagnose these individually, then kill off
7183 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007184 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007185 case Sema::TDK_FailedOverloadResolution:
7186 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007187 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007188 return;
7189 }
7190}
7191
7192/// Generates a 'note' diagnostic for an overload candidate. We've
7193/// already generated a primary error at the call site.
7194///
7195/// It really does need to be a single diagnostic with its caret
7196/// pointed at the candidate declaration. Yes, this creates some
7197/// major challenges of technical writing. Yes, this makes pointing
7198/// out problems with specific arguments quite awkward. It's still
7199/// better than generating twenty screens of text for every failed
7200/// overload.
7201///
7202/// It would be great to be able to express per-candidate problems
7203/// more richly for those diagnostic clients that cared, but we'd
7204/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007205void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7206 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007207 FunctionDecl *Fn = Cand->Function;
7208
John McCall12f97bc2010-01-08 04:41:39 +00007209 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007210 if (Cand->Viable && (Fn->isDeleted() ||
7211 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007212 std::string FnDesc;
7213 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007214
7215 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007216 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007217 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007218 return;
John McCall12f97bc2010-01-08 04:41:39 +00007219 }
7220
John McCalle1ac8d12010-01-13 00:25:19 +00007221 // We don't really have anything else to say about viable candidates.
7222 if (Cand->Viable) {
7223 S.NoteOverloadCandidate(Fn);
7224 return;
7225 }
John McCall0d1da222010-01-12 00:44:57 +00007226
John McCall6a61b522010-01-13 09:16:55 +00007227 switch (Cand->FailureKind) {
7228 case ovl_fail_too_many_arguments:
7229 case ovl_fail_too_few_arguments:
7230 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007231
John McCall6a61b522010-01-13 09:16:55 +00007232 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007233 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7234
John McCallfe796dd2010-01-23 05:17:32 +00007235 case ovl_fail_trivial_conversion:
7236 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007237 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007238 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007239
John McCall65eb8792010-02-25 01:37:24 +00007240 case ovl_fail_bad_conversion: {
7241 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7242 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007243 if (Cand->Conversions[I].isBad())
7244 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007245
John McCall6a61b522010-01-13 09:16:55 +00007246 // FIXME: this currently happens when we're called from SemaInit
7247 // when user-conversion overload fails. Figure out how to handle
7248 // those conditions and diagnose them well.
7249 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007250 }
John McCall65eb8792010-02-25 01:37:24 +00007251 }
John McCalld3224162010-01-08 00:58:21 +00007252}
7253
7254void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7255 // Desugar the type of the surrogate down to a function type,
7256 // retaining as many typedefs as possible while still showing
7257 // the function type (and, therefore, its parameter types).
7258 QualType FnType = Cand->Surrogate->getConversionType();
7259 bool isLValueReference = false;
7260 bool isRValueReference = false;
7261 bool isPointer = false;
7262 if (const LValueReferenceType *FnTypeRef =
7263 FnType->getAs<LValueReferenceType>()) {
7264 FnType = FnTypeRef->getPointeeType();
7265 isLValueReference = true;
7266 } else if (const RValueReferenceType *FnTypeRef =
7267 FnType->getAs<RValueReferenceType>()) {
7268 FnType = FnTypeRef->getPointeeType();
7269 isRValueReference = true;
7270 }
7271 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7272 FnType = FnTypePtr->getPointeeType();
7273 isPointer = true;
7274 }
7275 // Desugar down to a function type.
7276 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7277 // Reconstruct the pointer/reference as appropriate.
7278 if (isPointer) FnType = S.Context.getPointerType(FnType);
7279 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7280 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7281
7282 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7283 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007284 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007285}
7286
7287void NoteBuiltinOperatorCandidate(Sema &S,
7288 const char *Opc,
7289 SourceLocation OpLoc,
7290 OverloadCandidate *Cand) {
7291 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7292 std::string TypeStr("operator");
7293 TypeStr += Opc;
7294 TypeStr += "(";
7295 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7296 if (Cand->Conversions.size() == 1) {
7297 TypeStr += ")";
7298 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7299 } else {
7300 TypeStr += ", ";
7301 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7302 TypeStr += ")";
7303 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7304 }
7305}
7306
7307void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7308 OverloadCandidate *Cand) {
7309 unsigned NoOperands = Cand->Conversions.size();
7310 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7311 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007312 if (ICS.isBad()) break; // all meaningless after first invalid
7313 if (!ICS.isAmbiguous()) continue;
7314
John McCall5c32be02010-08-24 20:38:10 +00007315 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007316 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007317 }
7318}
7319
John McCall3712d9e2010-01-15 23:32:50 +00007320SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7321 if (Cand->Function)
7322 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007323 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007324 return Cand->Surrogate->getLocation();
7325 return SourceLocation();
7326}
7327
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007328static unsigned
7329RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007330 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007331 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007332 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007333
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007334 case Sema::TDK_Incomplete:
7335 return 1;
7336
7337 case Sema::TDK_Underqualified:
7338 case Sema::TDK_Inconsistent:
7339 return 2;
7340
7341 case Sema::TDK_SubstitutionFailure:
7342 case Sema::TDK_NonDeducedMismatch:
7343 return 3;
7344
7345 case Sema::TDK_InstantiationDepth:
7346 case Sema::TDK_FailedOverloadResolution:
7347 return 4;
7348
7349 case Sema::TDK_InvalidExplicitArguments:
7350 return 5;
7351
7352 case Sema::TDK_TooManyArguments:
7353 case Sema::TDK_TooFewArguments:
7354 return 6;
7355 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007356 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007357}
7358
John McCallad2587a2010-01-12 00:48:53 +00007359struct CompareOverloadCandidatesForDisplay {
7360 Sema &S;
7361 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007362
7363 bool operator()(const OverloadCandidate *L,
7364 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007365 // Fast-path this check.
7366 if (L == R) return false;
7367
John McCall12f97bc2010-01-08 04:41:39 +00007368 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007369 if (L->Viable) {
7370 if (!R->Viable) return true;
7371
7372 // TODO: introduce a tri-valued comparison for overload
7373 // candidates. Would be more worthwhile if we had a sort
7374 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007375 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7376 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007377 } else if (R->Viable)
7378 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007379
John McCall3712d9e2010-01-15 23:32:50 +00007380 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007381
John McCall3712d9e2010-01-15 23:32:50 +00007382 // Criteria by which we can sort non-viable candidates:
7383 if (!L->Viable) {
7384 // 1. Arity mismatches come after other candidates.
7385 if (L->FailureKind == ovl_fail_too_many_arguments ||
7386 L->FailureKind == ovl_fail_too_few_arguments)
7387 return false;
7388 if (R->FailureKind == ovl_fail_too_many_arguments ||
7389 R->FailureKind == ovl_fail_too_few_arguments)
7390 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007391
John McCallfe796dd2010-01-23 05:17:32 +00007392 // 2. Bad conversions come first and are ordered by the number
7393 // of bad conversions and quality of good conversions.
7394 if (L->FailureKind == ovl_fail_bad_conversion) {
7395 if (R->FailureKind != ovl_fail_bad_conversion)
7396 return true;
7397
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007398 // The conversion that can be fixed with a smaller number of changes,
7399 // comes first.
7400 unsigned numLFixes = L->Fix.NumConversionsFixed;
7401 unsigned numRFixes = R->Fix.NumConversionsFixed;
7402 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7403 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007404 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007405 if (numLFixes < numRFixes)
7406 return true;
7407 else
7408 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007409 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007410
John McCallfe796dd2010-01-23 05:17:32 +00007411 // If there's any ordering between the defined conversions...
7412 // FIXME: this might not be transitive.
7413 assert(L->Conversions.size() == R->Conversions.size());
7414
7415 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007416 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7417 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007418 switch (CompareImplicitConversionSequences(S,
7419 L->Conversions[I],
7420 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007421 case ImplicitConversionSequence::Better:
7422 leftBetter++;
7423 break;
7424
7425 case ImplicitConversionSequence::Worse:
7426 leftBetter--;
7427 break;
7428
7429 case ImplicitConversionSequence::Indistinguishable:
7430 break;
7431 }
7432 }
7433 if (leftBetter > 0) return true;
7434 if (leftBetter < 0) return false;
7435
7436 } else if (R->FailureKind == ovl_fail_bad_conversion)
7437 return false;
7438
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007439 if (L->FailureKind == ovl_fail_bad_deduction) {
7440 if (R->FailureKind != ovl_fail_bad_deduction)
7441 return true;
7442
7443 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7444 return RankDeductionFailure(L->DeductionFailure)
7445 <= RankDeductionFailure(R->DeductionFailure);
7446 }
7447
John McCall3712d9e2010-01-15 23:32:50 +00007448 // TODO: others?
7449 }
7450
7451 // Sort everything else by location.
7452 SourceLocation LLoc = GetLocationForCandidate(L);
7453 SourceLocation RLoc = GetLocationForCandidate(R);
7454
7455 // Put candidates without locations (e.g. builtins) at the end.
7456 if (LLoc.isInvalid()) return false;
7457 if (RLoc.isInvalid()) return true;
7458
7459 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007460 }
7461};
7462
John McCallfe796dd2010-01-23 05:17:32 +00007463/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007464/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007465void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7466 Expr **Args, unsigned NumArgs) {
7467 assert(!Cand->Viable);
7468
7469 // Don't do anything on failures other than bad conversion.
7470 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7471
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007472 // We only want the FixIts if all the arguments can be corrected.
7473 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007474 // Use a implicit copy initialization to check conversion fixes.
7475 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007476
John McCallfe796dd2010-01-23 05:17:32 +00007477 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007478 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007479 unsigned ConvCount = Cand->Conversions.size();
7480 while (true) {
7481 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7482 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007483 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007484 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007485 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007486 }
John McCallfe796dd2010-01-23 05:17:32 +00007487 }
7488
7489 if (ConvIdx == ConvCount)
7490 return;
7491
John McCall65eb8792010-02-25 01:37:24 +00007492 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7493 "remaining conversion is initialized?");
7494
Douglas Gregoradc7a702010-04-16 17:45:54 +00007495 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007496 // operation somehow.
7497 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007498
7499 const FunctionProtoType* Proto;
7500 unsigned ArgIdx = ConvIdx;
7501
7502 if (Cand->IsSurrogate) {
7503 QualType ConvType
7504 = Cand->Surrogate->getConversionType().getNonReferenceType();
7505 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7506 ConvType = ConvPtrType->getPointeeType();
7507 Proto = ConvType->getAs<FunctionProtoType>();
7508 ArgIdx--;
7509 } else if (Cand->Function) {
7510 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7511 if (isa<CXXMethodDecl>(Cand->Function) &&
7512 !isa<CXXConstructorDecl>(Cand->Function))
7513 ArgIdx--;
7514 } else {
7515 // Builtin binary operator with a bad first conversion.
7516 assert(ConvCount <= 3);
7517 for (; ConvIdx != ConvCount; ++ConvIdx)
7518 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007519 = TryCopyInitialization(S, Args[ConvIdx],
7520 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007521 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007522 /*InOverloadResolution*/ true,
7523 /*AllowObjCWritebackConversion=*/
7524 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007525 return;
7526 }
7527
7528 // Fill in the rest of the conversions.
7529 unsigned NumArgsInProto = Proto->getNumArgs();
7530 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007531 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007532 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007533 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007534 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007535 /*InOverloadResolution=*/true,
7536 /*AllowObjCWritebackConversion=*/
7537 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007538 // Store the FixIt in the candidate if it exists.
7539 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007540 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007541 }
John McCallfe796dd2010-01-23 05:17:32 +00007542 else
7543 Cand->Conversions[ConvIdx].setEllipsis();
7544 }
7545}
7546
John McCalld3224162010-01-08 00:58:21 +00007547} // end anonymous namespace
7548
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007549/// PrintOverloadCandidates - When overload resolution fails, prints
7550/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007551/// set.
John McCall5c32be02010-08-24 20:38:10 +00007552void OverloadCandidateSet::NoteCandidates(Sema &S,
7553 OverloadCandidateDisplayKind OCD,
7554 Expr **Args, unsigned NumArgs,
7555 const char *Opc,
7556 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007557 // Sort the candidates by viability and position. Sorting directly would
7558 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007559 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007560 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7561 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007562 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007563 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007564 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007565 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007566 if (Cand->Function || Cand->IsSurrogate)
7567 Cands.push_back(Cand);
7568 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7569 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007570 }
7571 }
7572
John McCallad2587a2010-01-12 00:48:53 +00007573 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007574 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007575
John McCall0d1da222010-01-12 00:44:57 +00007576 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007577
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007578 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00007579 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7580 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007581 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007582 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7583 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007584
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007585 // Set an arbitrary limit on the number of candidate functions we'll spam
7586 // the user with. FIXME: This limit should depend on details of the
7587 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00007588 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007589 break;
7590 }
7591 ++CandsShown;
7592
John McCalld3224162010-01-08 00:58:21 +00007593 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007594 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007595 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007596 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007597 else {
7598 assert(Cand->Viable &&
7599 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007600 // Generally we only see ambiguities including viable builtin
7601 // operators if overload resolution got screwed up by an
7602 // ambiguous user-defined conversion.
7603 //
7604 // FIXME: It's quite possible for different conversions to see
7605 // different ambiguities, though.
7606 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007607 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007608 ReportedAmbiguousConversions = true;
7609 }
John McCalld3224162010-01-08 00:58:21 +00007610
John McCall0d1da222010-01-12 00:44:57 +00007611 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007612 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007613 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007614 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007615
7616 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007617 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007618}
7619
Douglas Gregorb491ed32011-02-19 21:32:49 +00007620// [PossiblyAFunctionType] --> [Return]
7621// NonFunctionType --> NonFunctionType
7622// R (A) --> R(A)
7623// R (*)(A) --> R (A)
7624// R (&)(A) --> R (A)
7625// R (S::*)(A) --> R (A)
7626QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7627 QualType Ret = PossiblyAFunctionType;
7628 if (const PointerType *ToTypePtr =
7629 PossiblyAFunctionType->getAs<PointerType>())
7630 Ret = ToTypePtr->getPointeeType();
7631 else if (const ReferenceType *ToTypeRef =
7632 PossiblyAFunctionType->getAs<ReferenceType>())
7633 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007634 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007635 PossiblyAFunctionType->getAs<MemberPointerType>())
7636 Ret = MemTypePtr->getPointeeType();
7637 Ret =
7638 Context.getCanonicalType(Ret).getUnqualifiedType();
7639 return Ret;
7640}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007641
Douglas Gregorb491ed32011-02-19 21:32:49 +00007642// A helper class to help with address of function resolution
7643// - allows us to avoid passing around all those ugly parameters
7644class AddressOfFunctionResolver
7645{
7646 Sema& S;
7647 Expr* SourceExpr;
7648 const QualType& TargetType;
7649 QualType TargetFunctionType; // Extracted function type from target type
7650
7651 bool Complain;
7652 //DeclAccessPair& ResultFunctionAccessPair;
7653 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007654
Douglas Gregorb491ed32011-02-19 21:32:49 +00007655 bool TargetTypeIsNonStaticMemberFunction;
7656 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007657
Douglas Gregorb491ed32011-02-19 21:32:49 +00007658 OverloadExpr::FindResult OvlExprInfo;
7659 OverloadExpr *OvlExpr;
7660 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007661 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007662
Douglas Gregorb491ed32011-02-19 21:32:49 +00007663public:
7664 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7665 const QualType& TargetType, bool Complain)
7666 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7667 Complain(Complain), Context(S.getASTContext()),
7668 TargetTypeIsNonStaticMemberFunction(
7669 !!TargetType->getAs<MemberPointerType>()),
7670 FoundNonTemplateFunction(false),
7671 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7672 OvlExpr(OvlExprInfo.Expression)
7673 {
7674 ExtractUnqualifiedFunctionTypeFromTargetType();
7675
7676 if (!TargetFunctionType->isFunctionType()) {
7677 if (OvlExpr->hasExplicitTemplateArgs()) {
7678 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007679 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007680 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007681
7682 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7683 if (!Method->isStatic()) {
7684 // If the target type is a non-function type and the function
7685 // found is a non-static member function, pretend as if that was
7686 // the target, it's the only possible type to end up with.
7687 TargetTypeIsNonStaticMemberFunction = true;
7688
7689 // And skip adding the function if its not in the proper form.
7690 // We'll diagnose this due to an empty set of functions.
7691 if (!OvlExprInfo.HasFormOfMemberPointer)
7692 return;
7693 }
7694 }
7695
Douglas Gregorb491ed32011-02-19 21:32:49 +00007696 Matches.push_back(std::make_pair(dap,Fn));
7697 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007698 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007699 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007700 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007701
7702 if (OvlExpr->hasExplicitTemplateArgs())
7703 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007704
Douglas Gregorb491ed32011-02-19 21:32:49 +00007705 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7706 // C++ [over.over]p4:
7707 // If more than one function is selected, [...]
7708 if (Matches.size() > 1) {
7709 if (FoundNonTemplateFunction)
7710 EliminateAllTemplateMatches();
7711 else
7712 EliminateAllExceptMostSpecializedTemplate();
7713 }
7714 }
7715 }
7716
7717private:
7718 bool isTargetTypeAFunction() const {
7719 return TargetFunctionType->isFunctionType();
7720 }
7721
7722 // [ToType] [Return]
7723
7724 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7725 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7726 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7727 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7728 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7729 }
7730
7731 // return true if any matching specializations were found
7732 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7733 const DeclAccessPair& CurAccessFunPair) {
7734 if (CXXMethodDecl *Method
7735 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7736 // Skip non-static function templates when converting to pointer, and
7737 // static when converting to member pointer.
7738 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7739 return false;
7740 }
7741 else if (TargetTypeIsNonStaticMemberFunction)
7742 return false;
7743
7744 // C++ [over.over]p2:
7745 // If the name is a function template, template argument deduction is
7746 // done (14.8.2.2), and if the argument deduction succeeds, the
7747 // resulting template argument list is used to generate a single
7748 // function template specialization, which is added to the set of
7749 // overloaded functions considered.
7750 FunctionDecl *Specialization = 0;
7751 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7752 if (Sema::TemplateDeductionResult Result
7753 = S.DeduceTemplateArguments(FunctionTemplate,
7754 &OvlExplicitTemplateArgs,
7755 TargetFunctionType, Specialization,
7756 Info)) {
7757 // FIXME: make a note of the failed deduction for diagnostics.
7758 (void)Result;
7759 return false;
7760 }
7761
7762 // Template argument deduction ensures that we have an exact match.
7763 // This function template specicalization works.
7764 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7765 assert(TargetFunctionType
7766 == Context.getCanonicalType(Specialization->getType()));
7767 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7768 return true;
7769 }
7770
7771 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7772 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007773 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007774 // Skip non-static functions when converting to pointer, and static
7775 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007776 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7777 return false;
7778 }
7779 else if (TargetTypeIsNonStaticMemberFunction)
7780 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007781
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007782 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007783 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007784 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7785 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00007786 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7787 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007788 Matches.push_back(std::make_pair(CurAccessFunPair,
7789 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007790 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007791 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007792 }
Mike Stump11289f42009-09-09 15:08:12 +00007793 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007794
7795 return false;
7796 }
7797
7798 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7799 bool Ret = false;
7800
7801 // If the overload expression doesn't have the form of a pointer to
7802 // member, don't try to convert it to a pointer-to-member type.
7803 if (IsInvalidFormOfPointerToMemberFunction())
7804 return false;
7805
7806 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7807 E = OvlExpr->decls_end();
7808 I != E; ++I) {
7809 // Look through any using declarations to find the underlying function.
7810 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7811
7812 // C++ [over.over]p3:
7813 // Non-member functions and static member functions match
7814 // targets of type "pointer-to-function" or "reference-to-function."
7815 // Nonstatic member functions match targets of
7816 // type "pointer-to-member-function."
7817 // Note that according to DR 247, the containing class does not matter.
7818 if (FunctionTemplateDecl *FunctionTemplate
7819 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7820 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7821 Ret = true;
7822 }
7823 // If we have explicit template arguments supplied, skip non-templates.
7824 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7825 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7826 Ret = true;
7827 }
7828 assert(Ret || Matches.empty());
7829 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007830 }
7831
Douglas Gregorb491ed32011-02-19 21:32:49 +00007832 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007833 // [...] and any given function template specialization F1 is
7834 // eliminated if the set contains a second function template
7835 // specialization whose function template is more specialized
7836 // than the function template of F1 according to the partial
7837 // ordering rules of 14.5.5.2.
7838
7839 // The algorithm specified above is quadratic. We instead use a
7840 // two-pass algorithm (similar to the one used to identify the
7841 // best viable function in an overload set) that identifies the
7842 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007843
7844 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7845 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7846 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007847
John McCall58cc69d2010-01-27 01:50:18 +00007848 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007849 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7850 TPOC_Other, 0, SourceExpr->getLocStart(),
7851 S.PDiag(),
7852 S.PDiag(diag::err_addr_ovl_ambiguous)
7853 << Matches[0].second->getDeclName(),
7854 S.PDiag(diag::note_ovl_candidate)
7855 << (unsigned) oc_function_template,
7856 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007857
Douglas Gregorb491ed32011-02-19 21:32:49 +00007858 if (Result != MatchesCopy.end()) {
7859 // Make it the first and only element
7860 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7861 Matches[0].second = cast<FunctionDecl>(*Result);
7862 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007863 }
7864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007865
Douglas Gregorb491ed32011-02-19 21:32:49 +00007866 void EliminateAllTemplateMatches() {
7867 // [...] any function template specializations in the set are
7868 // eliminated if the set also contains a non-template function, [...]
7869 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7870 if (Matches[I].second->getPrimaryTemplate() == 0)
7871 ++I;
7872 else {
7873 Matches[I] = Matches[--N];
7874 Matches.set_size(N);
7875 }
7876 }
7877 }
7878
7879public:
7880 void ComplainNoMatchesFound() const {
7881 assert(Matches.empty());
7882 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7883 << OvlExpr->getName() << TargetFunctionType
7884 << OvlExpr->getSourceRange();
7885 S.NoteAllOverloadCandidates(OvlExpr);
7886 }
7887
7888 bool IsInvalidFormOfPointerToMemberFunction() const {
7889 return TargetTypeIsNonStaticMemberFunction &&
7890 !OvlExprInfo.HasFormOfMemberPointer;
7891 }
7892
7893 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7894 // TODO: Should we condition this on whether any functions might
7895 // have matched, or is it more appropriate to do that in callers?
7896 // TODO: a fixit wouldn't hurt.
7897 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7898 << TargetType << OvlExpr->getSourceRange();
7899 }
7900
7901 void ComplainOfInvalidConversion() const {
7902 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7903 << OvlExpr->getName() << TargetType;
7904 }
7905
7906 void ComplainMultipleMatchesFound() const {
7907 assert(Matches.size() > 1);
7908 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7909 << OvlExpr->getName()
7910 << OvlExpr->getSourceRange();
7911 S.NoteAllOverloadCandidates(OvlExpr);
7912 }
7913
7914 int getNumMatches() const { return Matches.size(); }
7915
7916 FunctionDecl* getMatchingFunctionDecl() const {
7917 if (Matches.size() != 1) return 0;
7918 return Matches[0].second;
7919 }
7920
7921 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7922 if (Matches.size() != 1) return 0;
7923 return &Matches[0].first;
7924 }
7925};
7926
7927/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7928/// an overloaded function (C++ [over.over]), where @p From is an
7929/// expression with overloaded function type and @p ToType is the type
7930/// we're trying to resolve to. For example:
7931///
7932/// @code
7933/// int f(double);
7934/// int f(int);
7935///
7936/// int (*pfd)(double) = f; // selects f(double)
7937/// @endcode
7938///
7939/// This routine returns the resulting FunctionDecl if it could be
7940/// resolved, and NULL otherwise. When @p Complain is true, this
7941/// routine will emit diagnostics if there is an error.
7942FunctionDecl *
7943Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7944 bool Complain,
7945 DeclAccessPair &FoundResult) {
7946
7947 assert(AddressOfExpr->getType() == Context.OverloadTy);
7948
7949 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7950 int NumMatches = Resolver.getNumMatches();
7951 FunctionDecl* Fn = 0;
7952 if ( NumMatches == 0 && Complain) {
7953 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7954 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7955 else
7956 Resolver.ComplainNoMatchesFound();
7957 }
7958 else if (NumMatches > 1 && Complain)
7959 Resolver.ComplainMultipleMatchesFound();
7960 else if (NumMatches == 1) {
7961 Fn = Resolver.getMatchingFunctionDecl();
7962 assert(Fn);
7963 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7964 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007965 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007966 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007967 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007968
7969 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007970}
7971
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007972/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007973/// resolve that overloaded function expression down to a single function.
7974///
7975/// This routine can only resolve template-ids that refer to a single function
7976/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007977/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007978/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00007979FunctionDecl *
7980Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7981 bool Complain,
7982 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007983 // C++ [over.over]p1:
7984 // [...] [Note: any redundant set of parentheses surrounding the
7985 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007986 // C++ [over.over]p1:
7987 // [...] The overloaded function name can be preceded by the &
7988 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007989
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007990 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00007991 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007992 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007993
7994 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00007995 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007996
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007997 // Look through all of the overloaded functions, searching for one
7998 // whose type matches exactly.
7999 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008000 for (UnresolvedSetIterator I = ovl->decls_begin(),
8001 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008002 // C++0x [temp.arg.explicit]p3:
8003 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008004 // where deduction is not done, if a template argument list is
8005 // specified and it, along with any default template arguments,
8006 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008007 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008008 FunctionTemplateDecl *FunctionTemplate
8009 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008010
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008011 // C++ [over.over]p2:
8012 // If the name is a function template, template argument deduction is
8013 // done (14.8.2.2), and if the argument deduction succeeds, the
8014 // resulting template argument list is used to generate a single
8015 // function template specialization, which is added to the set of
8016 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008017 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008018 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008019 if (TemplateDeductionResult Result
8020 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8021 Specialization, Info)) {
8022 // FIXME: make a note of the failed deduction for diagnostics.
8023 (void)Result;
8024 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025 }
8026
John McCall0009fcc2011-04-26 20:42:42 +00008027 assert(Specialization && "no specialization and no error?");
8028
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008029 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008030 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008031 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008032 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8033 << ovl->getName();
8034 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008035 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008036 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008037 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008038
John McCall0009fcc2011-04-26 20:42:42 +00008039 Matched = Specialization;
8040 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008042
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008043 return Matched;
8044}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008045
Douglas Gregor1beec452011-03-12 01:48:56 +00008046
8047
8048
8049// Resolve and fix an overloaded expression that
8050// can be resolved because it identifies a single function
8051// template specialization
8052// Last three arguments should only be supplied if Complain = true
8053ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00008054 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00008055 const SourceRange& OpRangeForComplaining,
8056 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008057 unsigned DiagIDForComplaining) {
8058 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008059
John McCall0009fcc2011-04-26 20:42:42 +00008060 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00008061
John McCall0009fcc2011-04-26 20:42:42 +00008062 DeclAccessPair found;
8063 ExprResult SingleFunctionExpression;
8064 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8065 ovl.Expression, /*complain*/ false, &found)) {
8066 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
8067 return ExprError();
8068
8069 // It is only correct to resolve to an instance method if we're
8070 // resolving a form that's permitted to be a pointer to member.
8071 // Otherwise we'll end up making a bound member expression, which
8072 // is illegal in all the contexts we resolve like this.
8073 if (!ovl.HasFormOfMemberPointer &&
8074 isa<CXXMethodDecl>(fn) &&
8075 cast<CXXMethodDecl>(fn)->isInstance()) {
8076 if (complain) {
8077 Diag(ovl.Expression->getExprLoc(),
8078 diag::err_invalid_use_of_bound_member_func)
8079 << ovl.Expression->getSourceRange();
8080 // TODO: I believe we only end up here if there's a mix of
8081 // static and non-static candidates (otherwise the expression
8082 // would have 'bound member' type, not 'overload' type).
8083 // Ideally we would note which candidate was chosen and why
8084 // the static candidates were rejected.
8085 }
8086
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008087 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00008088 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008089
John McCall0009fcc2011-04-26 20:42:42 +00008090 // Fix the expresion to refer to 'fn'.
8091 SingleFunctionExpression =
8092 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
8093
8094 // If desired, do function-to-pointer decay.
8095 if (doFunctionPointerConverion)
8096 SingleFunctionExpression =
8097 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
8098 }
8099
8100 if (!SingleFunctionExpression.isUsable()) {
8101 if (complain) {
8102 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8103 << ovl.Expression->getName()
8104 << DestTypeForComplaining
8105 << OpRangeForComplaining
8106 << ovl.Expression->getQualifierLoc().getSourceRange();
8107 NoteAllOverloadCandidates(SrcExpr);
8108 }
8109 return ExprError();
8110 }
8111
8112 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00008113}
8114
Douglas Gregorcabea402009-09-22 15:41:20 +00008115/// \brief Add a single candidate to the overload set.
8116static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008117 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008118 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008119 Expr **Args, unsigned NumArgs,
8120 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008121 bool PartialOverloading,
8122 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008123 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008124 if (isa<UsingShadowDecl>(Callee))
8125 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8126
Douglas Gregorcabea402009-09-22 15:41:20 +00008127 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008128 if (ExplicitTemplateArgs) {
8129 assert(!KnownValid && "Explicit template arguments?");
8130 return;
8131 }
John McCalla0296f72010-03-19 07:35:19 +00008132 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008133 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008134 return;
John McCalld14a8642009-11-21 08:51:07 +00008135 }
8136
8137 if (FunctionTemplateDecl *FuncTemplate
8138 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008139 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8140 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008141 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008142 return;
8143 }
8144
Richard Smith95ce4f62011-06-26 22:19:54 +00008145 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008146}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008147
Douglas Gregorcabea402009-09-22 15:41:20 +00008148/// \brief Add the overload candidates named by callee and/or found by argument
8149/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008150void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008151 Expr **Args, unsigned NumArgs,
8152 OverloadCandidateSet &CandidateSet,
8153 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008154
8155#ifndef NDEBUG
8156 // Verify that ArgumentDependentLookup is consistent with the rules
8157 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008158 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008159 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8160 // and let Y be the lookup set produced by argument dependent
8161 // lookup (defined as follows). If X contains
8162 //
8163 // -- a declaration of a class member, or
8164 //
8165 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008166 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008167 //
8168 // -- a declaration that is neither a function or a function
8169 // template
8170 //
8171 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008172
John McCall57500772009-12-16 12:17:52 +00008173 if (ULE->requiresADL()) {
8174 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8175 E = ULE->decls_end(); I != E; ++I) {
8176 assert(!(*I)->getDeclContext()->isRecord());
8177 assert(isa<UsingShadowDecl>(*I) ||
8178 !(*I)->getDeclContext()->isFunctionOrMethod());
8179 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008180 }
8181 }
8182#endif
8183
John McCall57500772009-12-16 12:17:52 +00008184 // It would be nice to avoid this copy.
8185 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008186 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008187 if (ULE->hasExplicitTemplateArgs()) {
8188 ULE->copyTemplateArgumentsInto(TABuffer);
8189 ExplicitTemplateArgs = &TABuffer;
8190 }
8191
8192 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8193 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008194 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008195 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008196 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008197
John McCall57500772009-12-16 12:17:52 +00008198 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008199 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8200 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008201 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008202 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008203 PartialOverloading,
8204 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008205}
John McCalld681c392009-12-16 08:11:27 +00008206
Richard Smith998a5912011-06-05 22:42:48 +00008207/// Attempt to recover from an ill-formed use of a non-dependent name in a
8208/// template, where the non-dependent name was declared after the template
8209/// was defined. This is common in code written for a compilers which do not
8210/// correctly implement two-stage name lookup.
8211///
8212/// Returns true if a viable candidate was found and a diagnostic was issued.
8213static bool
8214DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8215 const CXXScopeSpec &SS, LookupResult &R,
8216 TemplateArgumentListInfo *ExplicitTemplateArgs,
8217 Expr **Args, unsigned NumArgs) {
8218 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8219 return false;
8220
8221 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8222 SemaRef.LookupQualifiedName(R, DC);
8223
8224 if (!R.empty()) {
8225 R.suppressDiagnostics();
8226
8227 if (isa<CXXRecordDecl>(DC)) {
8228 // Don't diagnose names we find in classes; we get much better
8229 // diagnostics for these from DiagnoseEmptyLookup.
8230 R.clear();
8231 return false;
8232 }
8233
8234 OverloadCandidateSet Candidates(FnLoc);
8235 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8236 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8237 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008238 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008239
8240 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008241 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008242 // No viable functions. Don't bother the user with notes for functions
8243 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008244 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008245 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008246 }
Richard Smith998a5912011-06-05 22:42:48 +00008247
8248 // Find the namespaces where ADL would have looked, and suggest
8249 // declaring the function there instead.
8250 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8251 Sema::AssociatedClassSet AssociatedClasses;
8252 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8253 AssociatedNamespaces,
8254 AssociatedClasses);
8255 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008256 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008257 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008258 for (Sema::AssociatedNamespaceSet::iterator
8259 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008260 end = AssociatedNamespaces.end(); it != end; ++it) {
8261 if (!Std->Encloses(*it))
8262 SuggestedNamespaces.insert(*it);
8263 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008264 } else {
8265 // Lacking the 'std::' namespace, use all of the associated namespaces.
8266 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008267 }
8268
8269 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8270 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008271 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008272 SemaRef.Diag(Best->Function->getLocation(),
8273 diag::note_not_found_by_two_phase_lookup)
8274 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008275 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008276 SemaRef.Diag(Best->Function->getLocation(),
8277 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008278 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008279 } else {
8280 // FIXME: It would be useful to list the associated namespaces here,
8281 // but the diagnostics infrastructure doesn't provide a way to produce
8282 // a localized representation of a list of items.
8283 SemaRef.Diag(Best->Function->getLocation(),
8284 diag::note_not_found_by_two_phase_lookup)
8285 << R.getLookupName() << 2;
8286 }
8287
8288 // Try to recover by calling this function.
8289 return true;
8290 }
8291
8292 R.clear();
8293 }
8294
8295 return false;
8296}
8297
8298/// Attempt to recover from ill-formed use of a non-dependent operator in a
8299/// template, where the non-dependent operator was declared after the template
8300/// was defined.
8301///
8302/// Returns true if a viable candidate was found and a diagnostic was issued.
8303static bool
8304DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8305 SourceLocation OpLoc,
8306 Expr **Args, unsigned NumArgs) {
8307 DeclarationName OpName =
8308 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8309 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8310 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8311 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8312}
8313
John McCalld681c392009-12-16 08:11:27 +00008314/// Attempts to recover from a call where no functions were found.
8315///
8316/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008317static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008318BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008319 UnresolvedLookupExpr *ULE,
8320 SourceLocation LParenLoc,
8321 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008322 SourceLocation RParenLoc,
8323 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008324
8325 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008326 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008327
John McCall57500772009-12-16 12:17:52 +00008328 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008329 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008330 if (ULE->hasExplicitTemplateArgs()) {
8331 ULE->copyTemplateArgumentsInto(TABuffer);
8332 ExplicitTemplateArgs = &TABuffer;
8333 }
8334
John McCalld681c392009-12-16 08:11:27 +00008335 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8336 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008337 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8338 ExplicitTemplateArgs, Args, NumArgs) &&
8339 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008340 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008341 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008342 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008343
John McCall57500772009-12-16 12:17:52 +00008344 assert(!R.empty() && "lookup results empty despite recovery");
8345
8346 // Build an implicit member call if appropriate. Just drop the
8347 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008348 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008349 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008350 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8351 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008352 else if (ExplicitTemplateArgs)
8353 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8354 else
8355 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8356
8357 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008358 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008359
8360 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008361 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008362 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008363 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008364 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008365}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008366
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008367/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008368/// (which eventually refers to the declaration Func) and the call
8369/// arguments Args/NumArgs, attempt to resolve the function call down
8370/// to a specific function. If overload resolution succeeds, returns
8371/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008372/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008373/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008374ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008375Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008376 SourceLocation LParenLoc,
8377 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008378 SourceLocation RParenLoc,
8379 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008380#ifndef NDEBUG
8381 if (ULE->requiresADL()) {
8382 // To do ADL, we must have found an unqualified name.
8383 assert(!ULE->getQualifier() && "qualified name with ADL");
8384
8385 // We don't perform ADL for implicit declarations of builtins.
8386 // Verify that this was correctly set up.
8387 FunctionDecl *F;
8388 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8389 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8390 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008391 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008392
John McCall57500772009-12-16 12:17:52 +00008393 // We don't perform ADL in C.
8394 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008395 } else
8396 assert(!ULE->isStdAssociatedNamespace() &&
8397 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008398#endif
8399
John McCallbc077cf2010-02-08 23:07:23 +00008400 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008401
John McCall57500772009-12-16 12:17:52 +00008402 // Add the functions denoted by the callee to the set of candidate
8403 // functions, including those from argument-dependent lookup.
8404 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008405
8406 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008407 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8408 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008409 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008410 // In Microsoft mode, if we are inside a template class member function then
8411 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008412 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008413 // classes.
8414 if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() &&
8415 isa<CXXMethodDecl>(CurContext)) {
8416 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8417 Context.DependentTy, VK_RValue,
8418 RParenLoc);
8419 CE->setTypeDependent(true);
8420 return Owned(CE);
8421 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008422 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008423 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008424 }
John McCalld681c392009-12-16 08:11:27 +00008425
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008426 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008427 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008428 case OR_Success: {
8429 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008430 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008431 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008432 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8433 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008434 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008435 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8436 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008437 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008438
Richard Smith998a5912011-06-05 22:42:48 +00008439 case OR_No_Viable_Function: {
8440 // Try to recover by looking for viable functions which the user might
8441 // have meant to call.
8442 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8443 Args, NumArgs, RParenLoc,
8444 /*EmptyLookup=*/false);
8445 if (!Recovery.isInvalid())
8446 return Recovery;
8447
Chris Lattner45d9d602009-02-17 07:29:20 +00008448 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008449 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008450 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008451 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008452 break;
Richard Smith998a5912011-06-05 22:42:48 +00008453 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008454
8455 case OR_Ambiguous:
8456 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008457 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008458 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008459 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008460
8461 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008462 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008463 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8464 << Best->Function->isDeleted()
8465 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008466 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008467 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008468 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8469 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008470 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008471 }
8472
Douglas Gregorb412e172010-07-25 18:17:45 +00008473 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008474 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008475}
8476
John McCall4c4c1df2010-01-26 03:27:55 +00008477static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008478 return Functions.size() > 1 ||
8479 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8480}
8481
Douglas Gregor084d8552009-03-13 23:49:33 +00008482/// \brief Create a unary operation that may resolve to an overloaded
8483/// operator.
8484///
8485/// \param OpLoc The location of the operator itself (e.g., '*').
8486///
8487/// \param OpcIn The UnaryOperator::Opcode that describes this
8488/// operator.
8489///
8490/// \param Functions The set of non-member functions that will be
8491/// considered by overload resolution. The caller needs to build this
8492/// set based on the context using, e.g.,
8493/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8494/// set should not contain any member functions; those will be added
8495/// by CreateOverloadedUnaryOp().
8496///
8497/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008498ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008499Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8500 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008501 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008502 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008503
8504 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8505 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8506 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008507 // TODO: provide better source location info.
8508 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008509
John Wiegley01296292011-04-08 18:41:53 +00008510 if (Input->getObjectKind() == OK_ObjCProperty) {
8511 ExprResult Result = ConvertPropertyForRValue(Input);
8512 if (Result.isInvalid())
8513 return ExprError();
8514 Input = Result.take();
8515 }
John McCalle26a8722010-12-04 08:14:53 +00008516
Douglas Gregor084d8552009-03-13 23:49:33 +00008517 Expr *Args[2] = { Input, 0 };
8518 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008519
Douglas Gregor084d8552009-03-13 23:49:33 +00008520 // For post-increment and post-decrement, add the implicit '0' as
8521 // the second argument, so that we know this is a post-increment or
8522 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008523 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008524 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008525 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8526 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008527 NumArgs = 2;
8528 }
8529
8530 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008531 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008532 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008533 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008534 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008535 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008536 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008537
John McCall58cc69d2010-01-27 01:50:18 +00008538 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008539 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008540 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008541 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008542 /*ADL*/ true, IsOverloaded(Fns),
8543 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008544 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008545 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008546 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008547 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008548 OpLoc));
8549 }
8550
8551 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008552 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008553
8554 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008555 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008556
8557 // Add operator candidates that are member functions.
8558 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8559
John McCall4c4c1df2010-01-26 03:27:55 +00008560 // Add candidates from ADL.
8561 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008562 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008563 /*ExplicitTemplateArgs*/ 0,
8564 CandidateSet);
8565
Douglas Gregor084d8552009-03-13 23:49:33 +00008566 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008567 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008568
8569 // Perform overload resolution.
8570 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008571 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008572 case OR_Success: {
8573 // We found a built-in operator or an overloaded operator.
8574 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008575
Douglas Gregor084d8552009-03-13 23:49:33 +00008576 if (FnDecl) {
8577 // We matched an overloaded operator. Build a call to that
8578 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008579
Chandler Carruth30141632011-02-25 19:41:05 +00008580 MarkDeclarationReferenced(OpLoc, FnDecl);
8581
Douglas Gregor084d8552009-03-13 23:49:33 +00008582 // Convert the arguments.
8583 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008584 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008585
John Wiegley01296292011-04-08 18:41:53 +00008586 ExprResult InputRes =
8587 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8588 Best->FoundDecl, Method);
8589 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008590 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008591 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008592 } else {
8593 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008594 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008595 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008596 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008597 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008598 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008599 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008600 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008601 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008602 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008603 }
8604
John McCall4fa0d5f2010-05-06 18:15:07 +00008605 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8606
John McCall7decc9e2010-11-18 06:31:45 +00008607 // Determine the result type.
8608 QualType ResultTy = FnDecl->getResultType();
8609 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8610 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008611
Douglas Gregor084d8552009-03-13 23:49:33 +00008612 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008613 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8614 if (FnExpr.isInvalid())
8615 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008616
Eli Friedman030eee42009-11-18 03:58:17 +00008617 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008618 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008619 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008620 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008622 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008623 FnDecl))
8624 return ExprError();
8625
John McCallb268a282010-08-23 23:25:46 +00008626 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008627 } else {
8628 // We matched a built-in operator. Convert the arguments, then
8629 // break out so that we will build the appropriate built-in
8630 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008631 ExprResult InputRes =
8632 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8633 Best->Conversions[0], AA_Passing);
8634 if (InputRes.isInvalid())
8635 return ExprError();
8636 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008637 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008638 }
John Wiegley01296292011-04-08 18:41:53 +00008639 }
8640
8641 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008642 // This is an erroneous use of an operator which can be overloaded by
8643 // a non-member function. Check for non-member operators which were
8644 // defined too late to be candidates.
8645 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8646 // FIXME: Recover by calling the found function.
8647 return ExprError();
8648
John Wiegley01296292011-04-08 18:41:53 +00008649 // No viable function; fall through to handling this as a
8650 // built-in operator, which will produce an error message for us.
8651 break;
8652
8653 case OR_Ambiguous:
8654 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8655 << UnaryOperator::getOpcodeStr(Opc)
8656 << Input->getType()
8657 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008658 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00008659 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8660 return ExprError();
8661
8662 case OR_Deleted:
8663 Diag(OpLoc, diag::err_ovl_deleted_oper)
8664 << Best->Function->isDeleted()
8665 << UnaryOperator::getOpcodeStr(Opc)
8666 << getDeletedOrUnavailableSuffix(Best->Function)
8667 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008668 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8669 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008670 return ExprError();
8671 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008672
8673 // Either we found no viable overloaded operator or we matched a
8674 // built-in operator. In either case, fall through to trying to
8675 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008676 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008677}
8678
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008679/// \brief Create a binary operation that may resolve to an overloaded
8680/// operator.
8681///
8682/// \param OpLoc The location of the operator itself (e.g., '+').
8683///
8684/// \param OpcIn The BinaryOperator::Opcode that describes this
8685/// operator.
8686///
8687/// \param Functions The set of non-member functions that will be
8688/// considered by overload resolution. The caller needs to build this
8689/// set based on the context using, e.g.,
8690/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8691/// set should not contain any member functions; those will be added
8692/// by CreateOverloadedBinOp().
8693///
8694/// \param LHS Left-hand argument.
8695/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008696ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008697Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008698 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008699 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008700 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008701 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008702 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008703
8704 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8705 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8706 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8707
8708 // If either side is type-dependent, create an appropriate dependent
8709 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008710 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008711 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008712 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008713 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008714 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008715 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008716 Context.DependentTy,
8717 VK_RValue, OK_Ordinary,
8718 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008719
Douglas Gregor5287f092009-11-05 00:51:44 +00008720 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8721 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008722 VK_LValue,
8723 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008724 Context.DependentTy,
8725 Context.DependentTy,
8726 OpLoc));
8727 }
John McCall4c4c1df2010-01-26 03:27:55 +00008728
8729 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008730 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008731 // TODO: provide better source location info in DNLoc component.
8732 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008733 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008734 = UnresolvedLookupExpr::Create(Context, NamingClass,
8735 NestedNameSpecifierLoc(), OpNameInfo,
8736 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008737 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008738 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008739 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008740 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008741 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008742 OpLoc));
8743 }
8744
John McCalle26a8722010-12-04 08:14:53 +00008745 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008746 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8747 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8748 if (Result.isInvalid())
8749 return ExprError();
8750 Args[1] = Result.take();
8751 }
John McCalle26a8722010-12-04 08:14:53 +00008752
8753 // The LHS is more complicated.
8754 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8755
8756 // There's a tension for assignment operators between primitive
8757 // property assignment and the overloaded operators.
8758 if (BinaryOperator::isAssignmentOp(Opc)) {
8759 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8760
8761 // Is the property "logically" settable?
8762 bool Settable = (PRE->isExplicitProperty() ||
8763 PRE->getImplicitPropertySetter());
8764
8765 // To avoid gratuitously inventing semantics, use the primitive
8766 // unless it isn't. Thoughts in case we ever really care:
8767 // - If the property isn't logically settable, we have to
8768 // load and hope.
8769 // - If the property is settable and this is simple assignment,
8770 // we really should use the primitive.
8771 // - If the property is settable, then we could try overloading
8772 // on a generic lvalue of the appropriate type; if it works
8773 // out to a builtin candidate, we would do that same operation
8774 // on the property, and otherwise just error.
8775 if (Settable)
8776 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8777 }
8778
John Wiegley01296292011-04-08 18:41:53 +00008779 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8780 if (Result.isInvalid())
8781 return ExprError();
8782 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008783 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008784
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008785 // If this is the assignment operator, we only perform overload resolution
8786 // if the left-hand side is a class or enumeration type. This is actually
8787 // a hack. The standard requires that we do overload resolution between the
8788 // various built-in candidates, but as DR507 points out, this can lead to
8789 // problems. So we do it this way, which pretty much follows what GCC does.
8790 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008791 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008792 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008793
John McCalle26a8722010-12-04 08:14:53 +00008794 // If this is the .* operator, which is not overloadable, just
8795 // create a built-in binary operator.
8796 if (Opc == BO_PtrMemD)
8797 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8798
Douglas Gregor084d8552009-03-13 23:49:33 +00008799 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008800 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008801
8802 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008803 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008804
8805 // Add operator candidates that are member functions.
8806 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8807
John McCall4c4c1df2010-01-26 03:27:55 +00008808 // Add candidates from ADL.
8809 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8810 Args, 2,
8811 /*ExplicitTemplateArgs*/ 0,
8812 CandidateSet);
8813
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008814 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008815 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008816
8817 // Perform overload resolution.
8818 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008819 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008820 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008821 // We found a built-in operator or an overloaded operator.
8822 FunctionDecl *FnDecl = Best->Function;
8823
8824 if (FnDecl) {
8825 // We matched an overloaded operator. Build a call to that
8826 // operator.
8827
Chandler Carruth30141632011-02-25 19:41:05 +00008828 MarkDeclarationReferenced(OpLoc, FnDecl);
8829
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008830 // Convert the arguments.
8831 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008832 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008833 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008834
Chandler Carruth8e543b32010-12-12 08:17:55 +00008835 ExprResult Arg1 =
8836 PerformCopyInitialization(
8837 InitializedEntity::InitializeParameter(Context,
8838 FnDecl->getParamDecl(0)),
8839 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008840 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008841 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008842
John Wiegley01296292011-04-08 18:41:53 +00008843 ExprResult Arg0 =
8844 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8845 Best->FoundDecl, Method);
8846 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008847 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008848 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008849 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008850 } else {
8851 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008852 ExprResult Arg0 = PerformCopyInitialization(
8853 InitializedEntity::InitializeParameter(Context,
8854 FnDecl->getParamDecl(0)),
8855 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008856 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008857 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008858
Chandler Carruth8e543b32010-12-12 08:17:55 +00008859 ExprResult Arg1 =
8860 PerformCopyInitialization(
8861 InitializedEntity::InitializeParameter(Context,
8862 FnDecl->getParamDecl(1)),
8863 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008864 if (Arg1.isInvalid())
8865 return ExprError();
8866 Args[0] = LHS = Arg0.takeAs<Expr>();
8867 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008868 }
8869
John McCall4fa0d5f2010-05-06 18:15:07 +00008870 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8871
John McCall7decc9e2010-11-18 06:31:45 +00008872 // Determine the result type.
8873 QualType ResultTy = FnDecl->getResultType();
8874 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8875 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008876
8877 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008878 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8879 if (FnExpr.isInvalid())
8880 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008881
John McCallb268a282010-08-23 23:25:46 +00008882 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008883 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008884 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008885
8886 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008887 FnDecl))
8888 return ExprError();
8889
John McCallb268a282010-08-23 23:25:46 +00008890 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008891 } else {
8892 // We matched a built-in operator. Convert the arguments, then
8893 // break out so that we will build the appropriate built-in
8894 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008895 ExprResult ArgsRes0 =
8896 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8897 Best->Conversions[0], AA_Passing);
8898 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008899 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008900 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008901
John Wiegley01296292011-04-08 18:41:53 +00008902 ExprResult ArgsRes1 =
8903 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8904 Best->Conversions[1], AA_Passing);
8905 if (ArgsRes1.isInvalid())
8906 return ExprError();
8907 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008908 break;
8909 }
8910 }
8911
Douglas Gregor66950a32009-09-30 21:46:01 +00008912 case OR_No_Viable_Function: {
8913 // C++ [over.match.oper]p9:
8914 // If the operator is the operator , [...] and there are no
8915 // viable functions, then the operator is assumed to be the
8916 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008917 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008918 break;
8919
Chandler Carruth8e543b32010-12-12 08:17:55 +00008920 // For class as left operand for assignment or compound assigment
8921 // operator do not fall through to handling in built-in, but report that
8922 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008923 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008924 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008925 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008926 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8927 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008928 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008929 } else {
Richard Smith998a5912011-06-05 22:42:48 +00008930 // This is an erroneous use of an operator which can be overloaded by
8931 // a non-member function. Check for non-member operators which were
8932 // defined too late to be candidates.
8933 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8934 // FIXME: Recover by calling the found function.
8935 return ExprError();
8936
Douglas Gregor66950a32009-09-30 21:46:01 +00008937 // No viable function; try to create a built-in operation, which will
8938 // produce an error. Then, show the non-viable candidates.
8939 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008941 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008942 "C++ binary operator overloading is missing candidates!");
8943 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008944 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8945 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008946 return move(Result);
8947 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008948
8949 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008950 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008951 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008952 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008953 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008954 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8955 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008956 return ExprError();
8957
8958 case OR_Deleted:
8959 Diag(OpLoc, diag::err_ovl_deleted_oper)
8960 << Best->Function->isDeleted()
8961 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008962 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008963 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008964 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8965 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008966 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008967 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008968
Douglas Gregor66950a32009-09-30 21:46:01 +00008969 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008970 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008971}
8972
John McCalldadc5752010-08-24 06:29:42 +00008973ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008974Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8975 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008976 Expr *Base, Expr *Idx) {
8977 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008978 DeclarationName OpName =
8979 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8980
8981 // If either side is type-dependent, create an appropriate dependent
8982 // expression.
8983 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8984
John McCall58cc69d2010-01-27 01:50:18 +00008985 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008986 // CHECKME: no 'operator' keyword?
8987 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8988 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008989 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008990 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008991 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008992 /*ADL*/ true, /*Overloaded*/ false,
8993 UnresolvedSetIterator(),
8994 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008995 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008996
Sebastian Redladba46e2009-10-29 20:17:01 +00008997 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8998 Args, 2,
8999 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009000 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009001 RLoc));
9002 }
9003
John Wiegley01296292011-04-08 18:41:53 +00009004 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
9005 ExprResult Result = ConvertPropertyForRValue(Args[0]);
9006 if (Result.isInvalid())
9007 return ExprError();
9008 Args[0] = Result.take();
9009 }
9010 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
9011 ExprResult Result = ConvertPropertyForRValue(Args[1]);
9012 if (Result.isInvalid())
9013 return ExprError();
9014 Args[1] = Result.take();
9015 }
John McCalle26a8722010-12-04 08:14:53 +00009016
Sebastian Redladba46e2009-10-29 20:17:01 +00009017 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009018 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009019
9020 // Subscript can only be overloaded as a member function.
9021
9022 // Add operator candidates that are member functions.
9023 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9024
9025 // Add builtin operator candidates.
9026 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9027
9028 // Perform overload resolution.
9029 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009030 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009031 case OR_Success: {
9032 // We found a built-in operator or an overloaded operator.
9033 FunctionDecl *FnDecl = Best->Function;
9034
9035 if (FnDecl) {
9036 // We matched an overloaded operator. Build a call to that
9037 // operator.
9038
Chandler Carruth30141632011-02-25 19:41:05 +00009039 MarkDeclarationReferenced(LLoc, FnDecl);
9040
John McCalla0296f72010-03-19 07:35:19 +00009041 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009042 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009043
Sebastian Redladba46e2009-10-29 20:17:01 +00009044 // Convert the arguments.
9045 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009046 ExprResult Arg0 =
9047 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9048 Best->FoundDecl, Method);
9049 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009050 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009051 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009052
Anders Carlssona68e51e2010-01-29 18:37:50 +00009053 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009054 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009055 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009056 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009057 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009058 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009059 Owned(Args[1]));
9060 if (InputInit.isInvalid())
9061 return ExprError();
9062
9063 Args[1] = InputInit.takeAs<Expr>();
9064
Sebastian Redladba46e2009-10-29 20:17:01 +00009065 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009066 QualType ResultTy = FnDecl->getResultType();
9067 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9068 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009069
9070 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009071 DeclarationNameLoc LocInfo;
9072 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9073 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
9074 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009075 if (FnExpr.isInvalid())
9076 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009077
John McCallb268a282010-08-23 23:25:46 +00009078 CXXOperatorCallExpr *TheCall =
9079 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009080 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009081 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009082
John McCallb268a282010-08-23 23:25:46 +00009083 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009084 FnDecl))
9085 return ExprError();
9086
John McCallb268a282010-08-23 23:25:46 +00009087 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009088 } else {
9089 // We matched a built-in operator. Convert the arguments, then
9090 // break out so that we will build the appropriate built-in
9091 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009092 ExprResult ArgsRes0 =
9093 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9094 Best->Conversions[0], AA_Passing);
9095 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009096 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009097 Args[0] = ArgsRes0.take();
9098
9099 ExprResult ArgsRes1 =
9100 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9101 Best->Conversions[1], AA_Passing);
9102 if (ArgsRes1.isInvalid())
9103 return ExprError();
9104 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009105
9106 break;
9107 }
9108 }
9109
9110 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009111 if (CandidateSet.empty())
9112 Diag(LLoc, diag::err_ovl_no_oper)
9113 << Args[0]->getType() << /*subscript*/ 0
9114 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9115 else
9116 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9117 << Args[0]->getType()
9118 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009119 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9120 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009121 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009122 }
9123
9124 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009125 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009126 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009127 << Args[0]->getType() << Args[1]->getType()
9128 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009129 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9130 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009131 return ExprError();
9132
9133 case OR_Deleted:
9134 Diag(LLoc, diag::err_ovl_deleted_oper)
9135 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009136 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009137 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009138 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9139 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009140 return ExprError();
9141 }
9142
9143 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009144 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009145}
9146
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009147/// BuildCallToMemberFunction - Build a call to a member
9148/// function. MemExpr is the expression that refers to the member
9149/// function (and includes the object parameter), Args/NumArgs are the
9150/// arguments to the function call (not including the object
9151/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009152/// expression refers to a non-static member function or an overloaded
9153/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009154ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009155Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9156 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009157 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009158 assert(MemExprE->getType() == Context.BoundMemberTy ||
9159 MemExprE->getType() == Context.OverloadTy);
9160
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009161 // Dig out the member expression. This holds both the object
9162 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009163 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009164
John McCall0009fcc2011-04-26 20:42:42 +00009165 // Determine whether this is a call to a pointer-to-member function.
9166 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9167 assert(op->getType() == Context.BoundMemberTy);
9168 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9169
9170 QualType fnType =
9171 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9172
9173 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9174 QualType resultType = proto->getCallResultType(Context);
9175 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9176
9177 // Check that the object type isn't more qualified than the
9178 // member function we're calling.
9179 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9180
9181 QualType objectType = op->getLHS()->getType();
9182 if (op->getOpcode() == BO_PtrMemI)
9183 objectType = objectType->castAs<PointerType>()->getPointeeType();
9184 Qualifiers objectQuals = objectType.getQualifiers();
9185
9186 Qualifiers difference = objectQuals - funcQuals;
9187 difference.removeObjCGCAttr();
9188 difference.removeAddressSpace();
9189 if (difference) {
9190 std::string qualsString = difference.getAsString();
9191 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9192 << fnType.getUnqualifiedType()
9193 << qualsString
9194 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9195 }
9196
9197 CXXMemberCallExpr *call
9198 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9199 resultType, valueKind, RParenLoc);
9200
9201 if (CheckCallReturnType(proto->getResultType(),
9202 op->getRHS()->getSourceRange().getBegin(),
9203 call, 0))
9204 return ExprError();
9205
9206 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9207 return ExprError();
9208
9209 return MaybeBindToTemporary(call);
9210 }
9211
John McCall10eae182009-11-30 22:42:35 +00009212 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009213 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009214 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009215 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009216 if (isa<MemberExpr>(NakedMemExpr)) {
9217 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009218 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009219 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009220 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00009221 } else {
9222 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009223 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009224
John McCall6e9f8f62009-12-03 04:06:58 +00009225 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009226 Expr::Classification ObjectClassification
9227 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9228 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009229
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009230 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009231 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009232
John McCall2d74de92009-12-01 22:10:20 +00009233 // FIXME: avoid copy.
9234 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9235 if (UnresExpr->hasExplicitTemplateArgs()) {
9236 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9237 TemplateArgs = &TemplateArgsBuffer;
9238 }
9239
John McCall10eae182009-11-30 22:42:35 +00009240 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9241 E = UnresExpr->decls_end(); I != E; ++I) {
9242
John McCall6e9f8f62009-12-03 04:06:58 +00009243 NamedDecl *Func = *I;
9244 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9245 if (isa<UsingShadowDecl>(Func))
9246 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9247
Douglas Gregor02824322011-01-26 19:30:28 +00009248
Francois Pichet64225792011-01-18 05:04:39 +00009249 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009250 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009251 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9252 CandidateSet);
9253 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009254 // If explicit template arguments were provided, we can't call a
9255 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009256 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009257 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009258
John McCalla0296f72010-03-19 07:35:19 +00009259 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009260 ObjectClassification,
9261 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009262 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009263 } else {
John McCall10eae182009-11-30 22:42:35 +00009264 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009265 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009266 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009267 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009268 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009269 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009270 }
Mike Stump11289f42009-09-09 15:08:12 +00009271
John McCall10eae182009-11-30 22:42:35 +00009272 DeclarationName DeclName = UnresExpr->getMemberName();
9273
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009274 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009275 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009276 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009277 case OR_Success:
9278 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009279 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009280 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009281 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009282 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009283 break;
9284
9285 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009286 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009287 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009288 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009289 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009290 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009291 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009292
9293 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009294 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009295 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009296 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009297 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009298 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009299
9300 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009301 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009302 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009303 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009304 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009305 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009306 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009307 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009308 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009309 }
9310
John McCall16df1e52010-03-30 21:47:33 +00009311 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009312
John McCall2d74de92009-12-01 22:10:20 +00009313 // If overload resolution picked a static member, build a
9314 // non-member call based on that function.
9315 if (Method->isStatic()) {
9316 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9317 Args, NumArgs, RParenLoc);
9318 }
9319
John McCall10eae182009-11-30 22:42:35 +00009320 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009321 }
9322
John McCall7decc9e2010-11-18 06:31:45 +00009323 QualType ResultType = Method->getResultType();
9324 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9325 ResultType = ResultType.getNonLValueExprType(Context);
9326
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009327 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009328 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009329 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009330 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009331
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009332 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009333 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009334 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009335 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009336
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009337 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009338 // We only need to do this if there was actually an overload; otherwise
9339 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009340 if (!Method->isStatic()) {
9341 ExprResult ObjectArg =
9342 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9343 FoundDecl, Method);
9344 if (ObjectArg.isInvalid())
9345 return ExprError();
9346 MemExpr->setBase(ObjectArg.take());
9347 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009348
9349 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009350 const FunctionProtoType *Proto =
9351 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009352 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009353 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009354 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009355
John McCallb268a282010-08-23 23:25:46 +00009356 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009357 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009358
Anders Carlsson47061ee2011-05-06 14:25:31 +00009359 if ((isa<CXXConstructorDecl>(CurContext) ||
9360 isa<CXXDestructorDecl>(CurContext)) &&
9361 TheCall->getMethodDecl()->isPure()) {
9362 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9363
Chandler Carruth59259262011-06-27 08:31:58 +00009364 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009365 Diag(MemExpr->getLocStart(),
9366 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9367 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9368 << MD->getParent()->getDeclName();
9369
9370 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009371 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009372 }
John McCallb268a282010-08-23 23:25:46 +00009373 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009374}
9375
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009376/// BuildCallToObjectOfClassType - Build a call to an object of class
9377/// type (C++ [over.call.object]), which can end up invoking an
9378/// overloaded function call operator (@c operator()) or performing a
9379/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009380ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009381Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009382 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009383 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009384 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00009385 ExprResult Object = Owned(Obj);
9386 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9387 Object = ConvertPropertyForRValue(Object.take());
9388 if (Object.isInvalid())
9389 return ExprError();
9390 }
John McCalle26a8722010-12-04 08:14:53 +00009391
John Wiegley01296292011-04-08 18:41:53 +00009392 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9393 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009394
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009395 // C++ [over.call.object]p1:
9396 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009397 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009398 // candidate functions includes at least the function call
9399 // operators of T. The function call operators of T are obtained by
9400 // ordinary lookup of the name operator() in the context of
9401 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009402 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009403 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009404
John Wiegley01296292011-04-08 18:41:53 +00009405 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009406 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009407 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009408 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009409
John McCall27b18f82009-11-17 02:14:36 +00009410 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9411 LookupQualifiedName(R, Record->getDecl());
9412 R.suppressDiagnostics();
9413
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009414 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009415 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009416 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9417 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009418 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009420
Douglas Gregorab7897a2008-11-19 22:57:39 +00009421 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009422 // In addition, for each (non-explicit in C++0x) conversion function
9423 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009424 //
9425 // operator conversion-type-id () cv-qualifier;
9426 //
9427 // where cv-qualifier is the same cv-qualification as, or a
9428 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009429 // denotes the type "pointer to function of (P1,...,Pn) returning
9430 // R", or the type "reference to pointer to function of
9431 // (P1,...,Pn) returning R", or the type "reference to function
9432 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009433 // is also considered as a candidate function. Similarly,
9434 // surrogate call functions are added to the set of candidate
9435 // functions for each conversion function declared in an
9436 // accessible base class provided the function is not hidden
9437 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009438 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009439 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009440 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009441 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009442 NamedDecl *D = *I;
9443 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9444 if (isa<UsingShadowDecl>(D))
9445 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009446
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009447 // Skip over templated conversion functions; they aren't
9448 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009449 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009450 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009451
John McCall6e9f8f62009-12-03 04:06:58 +00009452 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009453 if (!Conv->isExplicit()) {
9454 // Strip the reference type (if any) and then the pointer type (if
9455 // any) to get down to what might be a function type.
9456 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9457 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9458 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009459
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009460 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9461 {
9462 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9463 Object.get(), Args, NumArgs, CandidateSet);
9464 }
9465 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009466 }
Mike Stump11289f42009-09-09 15:08:12 +00009467
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009468 // Perform overload resolution.
9469 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009470 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009471 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009472 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009473 // Overload resolution succeeded; we'll build the appropriate call
9474 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009475 break;
9476
9477 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009478 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009479 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9480 << Object.get()->getType() << /*call*/ 1
9481 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009482 else
John Wiegley01296292011-04-08 18:41:53 +00009483 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009484 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009485 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009486 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009487 break;
9488
9489 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009490 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009491 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009492 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009493 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009494 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009495
9496 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009497 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009498 diag::err_ovl_deleted_object_call)
9499 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009500 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009501 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009502 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009503 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009504 break;
Mike Stump11289f42009-09-09 15:08:12 +00009505 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009506
Douglas Gregorb412e172010-07-25 18:17:45 +00009507 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009508 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009509
Douglas Gregorab7897a2008-11-19 22:57:39 +00009510 if (Best->Function == 0) {
9511 // Since there is no function declaration, this is one of the
9512 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009513 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009514 = cast<CXXConversionDecl>(
9515 Best->Conversions[0].UserDefined.ConversionFunction);
9516
John Wiegley01296292011-04-08 18:41:53 +00009517 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009518 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009519
Douglas Gregorab7897a2008-11-19 22:57:39 +00009520 // We selected one of the surrogate functions that converts the
9521 // object parameter to a function pointer. Perform the conversion
9522 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009523
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009524 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009525 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00009526 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00009527 if (Call.isInvalid())
9528 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009529
Douglas Gregor668443e2011-01-20 00:18:04 +00009530 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009531 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009532 }
9533
Chandler Carruth30141632011-02-25 19:41:05 +00009534 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009535 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009536 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009537
Douglas Gregorab7897a2008-11-19 22:57:39 +00009538 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9539 // that calls this method, using Object for the implicit object
9540 // parameter and passing along the remaining arguments.
9541 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009542 const FunctionProtoType *Proto =
9543 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009544
9545 unsigned NumArgsInProto = Proto->getNumArgs();
9546 unsigned NumArgsToCheck = NumArgs;
9547
9548 // Build the full argument list for the method call (the
9549 // implicit object parameter is placed at the beginning of the
9550 // list).
9551 Expr **MethodArgs;
9552 if (NumArgs < NumArgsInProto) {
9553 NumArgsToCheck = NumArgsInProto;
9554 MethodArgs = new Expr*[NumArgsInProto + 1];
9555 } else {
9556 MethodArgs = new Expr*[NumArgs + 1];
9557 }
John Wiegley01296292011-04-08 18:41:53 +00009558 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009559 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9560 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009561
John Wiegley01296292011-04-08 18:41:53 +00009562 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9563 if (NewFn.isInvalid())
9564 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009565
9566 // Once we've built TheCall, all of the expressions are properly
9567 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009568 QualType ResultTy = Method->getResultType();
9569 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9570 ResultTy = ResultTy.getNonLValueExprType(Context);
9571
John McCallb268a282010-08-23 23:25:46 +00009572 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009573 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009574 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009575 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009576 delete [] MethodArgs;
9577
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009578 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009579 Method))
9580 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009581
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009582 // We may have default arguments. If so, we need to allocate more
9583 // slots in the call for them.
9584 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009585 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009586 else if (NumArgs > NumArgsInProto)
9587 NumArgsToCheck = NumArgsInProto;
9588
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009589 bool IsError = false;
9590
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009591 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009592 ExprResult ObjRes =
9593 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9594 Best->FoundDecl, Method);
9595 if (ObjRes.isInvalid())
9596 IsError = true;
9597 else
9598 Object = move(ObjRes);
9599 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009600
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009601 // Check the argument types.
9602 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009603 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009604 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009605 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009606
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009607 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009608
John McCalldadc5752010-08-24 06:29:42 +00009609 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009610 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009611 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009612 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009613 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009614
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009615 IsError |= InputInit.isInvalid();
9616 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009617 } else {
John McCalldadc5752010-08-24 06:29:42 +00009618 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009619 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9620 if (DefArg.isInvalid()) {
9621 IsError = true;
9622 break;
9623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009624
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009625 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009626 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009627
9628 TheCall->setArg(i + 1, Arg);
9629 }
9630
9631 // If this is a variadic call, handle args passed through "...".
9632 if (Proto->isVariadic()) {
9633 // Promote the arguments (C99 6.5.2.2p7).
9634 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009635 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9636 IsError |= Arg.isInvalid();
9637 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009638 }
9639 }
9640
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009641 if (IsError) return true;
9642
John McCallb268a282010-08-23 23:25:46 +00009643 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009644 return true;
9645
John McCalle172be52010-08-24 06:09:16 +00009646 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009647}
9648
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009649/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009650/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009651/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009652ExprResult
John McCallb268a282010-08-23 23:25:46 +00009653Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009654 assert(Base->getType()->isRecordType() &&
9655 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009656
John Wiegley01296292011-04-08 18:41:53 +00009657 if (Base->getObjectKind() == OK_ObjCProperty) {
9658 ExprResult Result = ConvertPropertyForRValue(Base);
9659 if (Result.isInvalid())
9660 return ExprError();
9661 Base = Result.take();
9662 }
John McCalle26a8722010-12-04 08:14:53 +00009663
John McCallbc077cf2010-02-08 23:07:23 +00009664 SourceLocation Loc = Base->getExprLoc();
9665
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009666 // C++ [over.ref]p1:
9667 //
9668 // [...] An expression x->m is interpreted as (x.operator->())->m
9669 // for a class object x of type T if T::operator->() exists and if
9670 // the operator is selected as the best match function by the
9671 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009672 DeclarationName OpName =
9673 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009674 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009675 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009676
John McCallbc077cf2010-02-08 23:07:23 +00009677 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009678 PDiag(diag::err_typecheck_incomplete_tag)
9679 << Base->getSourceRange()))
9680 return ExprError();
9681
John McCall27b18f82009-11-17 02:14:36 +00009682 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9683 LookupQualifiedName(R, BaseRecord->getDecl());
9684 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009685
9686 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009687 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009688 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9689 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009690 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009691
9692 // Perform overload resolution.
9693 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009694 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009695 case OR_Success:
9696 // Overload resolution succeeded; we'll build the call below.
9697 break;
9698
9699 case OR_No_Viable_Function:
9700 if (CandidateSet.empty())
9701 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009702 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009703 else
9704 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009705 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009706 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009707 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009708
9709 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009710 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9711 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009712 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009713 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009714
9715 case OR_Deleted:
9716 Diag(OpLoc, diag::err_ovl_deleted_oper)
9717 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009718 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009719 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009720 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009721 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009722 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009723 }
9724
Chandler Carruth30141632011-02-25 19:41:05 +00009725 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009726 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009727 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009728
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009729 // Convert the object parameter.
9730 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009731 ExprResult BaseResult =
9732 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9733 Best->FoundDecl, Method);
9734 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009735 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009736 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009737
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009738 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009739 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9740 if (FnExpr.isInvalid())
9741 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009742
John McCall7decc9e2010-11-18 06:31:45 +00009743 QualType ResultTy = Method->getResultType();
9744 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9745 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009746 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009747 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009748 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009749
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009750 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009751 Method))
9752 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009753
9754 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009755}
9756
Douglas Gregorcd695e52008-11-10 20:40:00 +00009757/// FixOverloadedFunctionReference - E is an expression that refers to
9758/// a C++ overloaded function (possibly with some parentheses and
9759/// perhaps a '&' around it). We have resolved the overloaded function
9760/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009761/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009762Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009763 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009764 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009765 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9766 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009767 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009768 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009769
Douglas Gregor51c538b2009-11-20 19:42:02 +00009770 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009771 }
9772
Douglas Gregor51c538b2009-11-20 19:42:02 +00009773 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009774 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9775 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009776 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009777 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009778 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009779 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009780 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009781 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009782
9783 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009784 ICE->getCastKind(),
9785 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009786 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009787 }
9788
Douglas Gregor51c538b2009-11-20 19:42:02 +00009789 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009790 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009791 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9793 if (Method->isStatic()) {
9794 // Do nothing: static member functions aren't any different
9795 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009796 } else {
John McCalle66edc12009-11-24 19:00:30 +00009797 // Fix the sub expression, which really has to be an
9798 // UnresolvedLookupExpr holding an overloaded member function
9799 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009800 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9801 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009802 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009803 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009804
John McCalld14a8642009-11-21 08:51:07 +00009805 assert(isa<DeclRefExpr>(SubExpr)
9806 && "fixed to something other than a decl ref");
9807 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9808 && "fixed to a member ref with no nested name qualifier");
9809
9810 // We have taken the address of a pointer to member
9811 // function. Perform the computation here so that we get the
9812 // appropriate pointer to member type.
9813 QualType ClassType
9814 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9815 QualType MemPtrType
9816 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9817
John McCall7decc9e2010-11-18 06:31:45 +00009818 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9819 VK_RValue, OK_Ordinary,
9820 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009821 }
9822 }
John McCall16df1e52010-03-30 21:47:33 +00009823 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9824 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009825 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009826 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009827
John McCalle3027922010-08-25 11:45:40 +00009828 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009829 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009830 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009831 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009832 }
John McCalld14a8642009-11-21 08:51:07 +00009833
9834 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009835 // FIXME: avoid copy.
9836 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009837 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009838 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9839 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009840 }
9841
John McCalld14a8642009-11-21 08:51:07 +00009842 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009843 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009844 Fn,
9845 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009846 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009847 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009848 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009849 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009850 }
9851
John McCall10eae182009-11-30 22:42:35 +00009852 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009853 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009854 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9855 if (MemExpr->hasExplicitTemplateArgs()) {
9856 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9857 TemplateArgs = &TemplateArgsBuffer;
9858 }
John McCall6b51f282009-11-23 01:53:49 +00009859
John McCall2d74de92009-12-01 22:10:20 +00009860 Expr *Base;
9861
John McCall7decc9e2010-11-18 06:31:45 +00009862 // If we're filling in a static method where we used to have an
9863 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009864 if (MemExpr->isImplicitAccess()) {
9865 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9866 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009867 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009868 Fn,
9869 MemExpr->getMemberLoc(),
9870 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009871 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009872 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009873 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009874 } else {
9875 SourceLocation Loc = MemExpr->getMemberLoc();
9876 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009877 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009878 Base = new (Context) CXXThisExpr(Loc,
9879 MemExpr->getBaseType(),
9880 /*isImplicit=*/true);
9881 }
John McCall2d74de92009-12-01 22:10:20 +00009882 } else
John McCallc3007a22010-10-26 07:05:15 +00009883 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009884
John McCall4adb38c2011-04-27 00:36:17 +00009885 ExprValueKind valueKind;
9886 QualType type;
9887 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9888 valueKind = VK_LValue;
9889 type = Fn->getType();
9890 } else {
9891 valueKind = VK_RValue;
9892 type = Context.BoundMemberTy;
9893 }
9894
John McCall2d74de92009-12-01 22:10:20 +00009895 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009896 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009897 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009898 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009899 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009900 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009901 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009902 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009904
John McCallc3007a22010-10-26 07:05:15 +00009905 llvm_unreachable("Invalid reference to overloaded function");
9906 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009907}
9908
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009909ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009910 DeclAccessPair Found,
9911 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009912 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009913}
9914
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009915} // end namespace clang