blob: 437b2b5c6d43381618433454ca2822c9f332dd43 [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 {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000261 llvm::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 {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000300 llvm::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 {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000315 llvm::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,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000912 AssignmentAction Action, bool AllowExplicit) {
913 ImplicitConversionSequence ICS;
914 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
915}
916
John Wiegley01296292011-04-08 18:41:53 +0000917ExprResult
918Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000919 AssignmentAction Action, bool AllowExplicit,
920 ImplicitConversionSequence& ICS) {
John McCall31168b02011-06-15 23:02:42 +0000921 // Objective-C ARC: Determine whether we will allow the writeback conversion.
922 bool AllowObjCWritebackConversion
923 = getLangOptions().ObjCAutoRefCount &&
924 (Action == AA_Passing || Action == AA_Sending);
925
926
John McCall5c32be02010-08-24 20:38:10 +0000927 ICS = clang::TryImplicitConversion(*this, From, ToType,
928 /*SuppressUserConversions=*/false,
929 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000930 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +0000931 /*CStyle=*/false,
932 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000933 return PerformImplicitConversion(From, ToType, ICS, Action);
934}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935
936/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000937/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +0000938bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
939 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000940 if (Context.hasSameUnqualifiedType(FromType, ToType))
941 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000942
John McCall991eb4b2010-12-21 00:44:39 +0000943 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
944 // where F adds one of the following at most once:
945 // - a pointer
946 // - a member pointer
947 // - a block pointer
948 CanQualType CanTo = Context.getCanonicalType(ToType);
949 CanQualType CanFrom = Context.getCanonicalType(FromType);
950 Type::TypeClass TyClass = CanTo->getTypeClass();
951 if (TyClass != CanFrom->getTypeClass()) return false;
952 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
953 if (TyClass == Type::Pointer) {
954 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
955 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
956 } else if (TyClass == Type::BlockPointer) {
957 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
958 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
959 } else if (TyClass == Type::MemberPointer) {
960 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
961 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
962 } else {
963 return false;
964 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000965
John McCall991eb4b2010-12-21 00:44:39 +0000966 TyClass = CanTo->getTypeClass();
967 if (TyClass != CanFrom->getTypeClass()) return false;
968 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
969 return false;
970 }
971
972 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
973 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
974 if (!EInfo.getNoReturn()) return false;
975
976 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
977 assert(QualType(FromFn, 0).isCanonical());
978 if (QualType(FromFn, 0) != CanTo) return false;
979
980 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000981 return true;
982}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor46188682010-05-18 22:42:18 +0000984/// \brief Determine whether the conversion from FromType to ToType is a valid
985/// vector conversion.
986///
987/// \param ICK Will be set to the vector conversion kind, if this is a vector
988/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989static bool IsVectorConversion(ASTContext &Context, QualType FromType,
990 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000991 // We need at least one of these types to be a vector type to have a vector
992 // conversion.
993 if (!ToType->isVectorType() && !FromType->isVectorType())
994 return false;
995
996 // Identical types require no conversions.
997 if (Context.hasSameUnqualifiedType(FromType, ToType))
998 return false;
999
1000 // There are no conversions between extended vector types, only identity.
1001 if (ToType->isExtVectorType()) {
1002 // There are no conversions between extended vector types other than the
1003 // identity conversion.
1004 if (FromType->isExtVectorType())
1005 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Douglas Gregor46188682010-05-18 22:42:18 +00001007 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001008 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001009 ICK = ICK_Vector_Splat;
1010 return true;
1011 }
1012 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001013
1014 // We can perform the conversion between vector types in the following cases:
1015 // 1)vector types are equivalent AltiVec and GCC vector types
1016 // 2)lax vector conversions are permitted and the vector types are of the
1017 // same size
1018 if (ToType->isVectorType() && FromType->isVectorType()) {
1019 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001020 (Context.getLangOptions().LaxVectorConversions &&
1021 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001022 ICK = ICK_Vector_Conversion;
1023 return true;
1024 }
Douglas Gregor46188682010-05-18 22:42:18 +00001025 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001026
Douglas Gregor46188682010-05-18 22:42:18 +00001027 return false;
1028}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001029
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001030/// IsStandardConversion - Determines whether there is a standard
1031/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1032/// expression From to the type ToType. Standard conversion sequences
1033/// only consider non-class types; for conversions that involve class
1034/// types, use TryImplicitConversion. If a conversion exists, SCS will
1035/// contain the standard conversion sequence required to perform this
1036/// conversion and this routine will return true. Otherwise, this
1037/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001038static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1039 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001040 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001041 bool CStyle,
1042 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001043 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001045 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001046 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001047 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001048 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001049 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001050 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001051
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001052 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001053 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001054 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001055 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 return false;
1057
Mike Stump11289f42009-09-09 15:08:12 +00001058 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001059 }
1060
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061 // The first conversion can be an lvalue-to-rvalue conversion,
1062 // array-to-pointer conversion, or function-to-pointer conversion
1063 // (C++ 4p1).
1064
John McCall5c32be02010-08-24 20:38:10 +00001065 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001066 DeclAccessPair AccessPair;
1067 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001069 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001070 // We were able to resolve the address of the overloaded function,
1071 // so we can convert to the type of that function.
1072 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001073
1074 // we can sometimes resolve &foo<int> regardless of ToType, so check
1075 // if the type matches (identity) or we are converting to bool
1076 if (!S.Context.hasSameUnqualifiedType(
1077 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1078 QualType resultTy;
1079 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001080 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001081 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1082 // otherwise, only a boolean conversion is standard
1083 if (!ToType->isBooleanType())
1084 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
Chandler Carruthffce2452011-03-29 08:08:18 +00001087 // Check if the "from" expression is taking the address of an overloaded
1088 // function and recompute the FromType accordingly. Take advantage of the
1089 // fact that non-static member functions *must* have such an address-of
1090 // expression.
1091 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1092 if (Method && !Method->isStatic()) {
1093 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1094 "Non-unary operator on non-static member address");
1095 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1096 == UO_AddrOf &&
1097 "Non-address-of operator on non-static member address");
1098 const Type *ClassType
1099 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1100 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001101 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1102 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1103 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001104 "Non-address-of operator for overloaded function expression");
1105 FromType = S.Context.getPointerType(FromType);
1106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
Douglas Gregor980fb162010-04-29 18:24:40 +00001108 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001109 assert(S.Context.hasSameType(
1110 FromType,
1111 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001112 } else {
1113 return false;
1114 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001115 }
Mike Stump11289f42009-09-09 15:08:12 +00001116 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001117 // An lvalue (3.10) of a non-function, non-array type T can be
1118 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001119 bool argIsLValue = From->isLValue();
1120 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001121 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001122 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001123 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124
1125 // If T is a non-class type, the type of the rvalue is the
1126 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001127 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1128 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001129 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001130 } else if (FromType->isArrayType()) {
1131 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001132 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001133
1134 // An lvalue or rvalue of type "array of N T" or "array of unknown
1135 // bound of T" can be converted to an rvalue of type "pointer to
1136 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001137 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001138
John McCall5c32be02010-08-24 20:38:10 +00001139 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001141 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142
1143 // For the purpose of ranking in overload resolution
1144 // (13.3.3.1.1), this conversion is considered an
1145 // array-to-pointer conversion followed by a qualification
1146 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147 SCS.Second = ICK_Identity;
1148 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001149 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001150 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001151 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 }
John McCall086a4642010-11-24 05:12:34 +00001153 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001154 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001156
1157 // An lvalue of function type T can be converted to an rvalue of
1158 // type "pointer to T." The result is a pointer to the
1159 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001160 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001161 } else {
1162 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001163 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001164 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001165 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166
1167 // The second conversion can be an integral promotion, floating
1168 // point promotion, integral conversion, floating point conversion,
1169 // floating-integral conversion, pointer conversion,
1170 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001171 // For overloading in C, this can also be a "compatible-type"
1172 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001173 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001174 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001175 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001176 // The unqualified versions of the types are the same: there's no
1177 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001178 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001179 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001180 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001181 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001182 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001183 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001184 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001185 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001186 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001187 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001188 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001189 SCS.Second = ICK_Complex_Promotion;
1190 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001191 } else if (ToType->isBooleanType() &&
1192 (FromType->isArithmeticType() ||
1193 FromType->isAnyPointerType() ||
1194 FromType->isBlockPointerType() ||
1195 FromType->isMemberPointerType() ||
1196 FromType->isNullPtrType())) {
1197 // Boolean conversions (C++ 4.12).
1198 SCS.Second = ICK_Boolean_Conversion;
1199 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001200 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001201 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001202 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001203 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001204 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001205 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001206 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001207 SCS.Second = ICK_Complex_Conversion;
1208 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001209 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1210 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001211 // Complex-real conversions (C99 6.3.1.7)
1212 SCS.Second = ICK_Complex_Real;
1213 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001214 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001215 // Floating point conversions (C++ 4.8).
1216 SCS.Second = ICK_Floating_Conversion;
1217 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001219 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001220 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001221 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001222 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001223 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001224 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001225 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001226 SCS.Second = ICK_Block_Pointer_Conversion;
1227 } else if (AllowObjCWritebackConversion &&
1228 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1229 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001230 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1231 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001232 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001233 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001234 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001235 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001237 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001238 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001239 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001240 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001241 SCS.Second = SecondICK;
1242 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001243 } else if (!S.getLangOptions().CPlusPlus &&
1244 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001245 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001246 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001247 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001248 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001249 // Treat a conversion that strips "noreturn" as an identity conversion.
1250 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001251 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1252 InOverloadResolution,
1253 SCS, CStyle)) {
1254 SCS.Second = ICK_TransparentUnionConversion;
1255 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001256 } else {
1257 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001258 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001260 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001261
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001262 QualType CanonFrom;
1263 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001264 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001265 bool ObjCLifetimeConversion;
1266 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1267 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001268 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001269 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001270 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001271 CanonFrom = S.Context.getCanonicalType(FromType);
1272 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001273 } else {
1274 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001275 SCS.Third = ICK_Identity;
1276
Mike Stump11289f42009-09-09 15:08:12 +00001277 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001278 // [...] Any difference in top-level cv-qualification is
1279 // subsumed by the initialization itself and does not constitute
1280 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001281 CanonFrom = S.Context.getCanonicalType(FromType);
1282 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001283 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001284 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001285 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001286 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1287 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001288 FromType = ToType;
1289 CanonFrom = CanonTo;
1290 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001291 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001292 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001293
1294 // If we have not converted the argument type to the parameter type,
1295 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001296 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001297 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001298
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001299 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001300}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001301
1302static bool
1303IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1304 QualType &ToType,
1305 bool InOverloadResolution,
1306 StandardConversionSequence &SCS,
1307 bool CStyle) {
1308
1309 const RecordType *UT = ToType->getAsUnionType();
1310 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1311 return false;
1312 // The field to initialize within the transparent union.
1313 RecordDecl *UD = UT->getDecl();
1314 // It's compatible if the expression matches any of the fields.
1315 for (RecordDecl::field_iterator it = UD->field_begin(),
1316 itend = UD->field_end();
1317 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001318 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1319 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001320 ToType = it->getType();
1321 return true;
1322 }
1323 }
1324 return false;
1325}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001326
1327/// IsIntegralPromotion - Determines whether the conversion from the
1328/// expression From (whose potentially-adjusted type is FromType) to
1329/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1330/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001331bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001332 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001333 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001334 if (!To) {
1335 return false;
1336 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001337
1338 // An rvalue of type char, signed char, unsigned char, short int, or
1339 // unsigned short int can be converted to an rvalue of type int if
1340 // int can represent all the values of the source type; otherwise,
1341 // the source rvalue can be converted to an rvalue of type unsigned
1342 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001343 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1344 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001345 if (// We can promote any signed, promotable integer type to an int
1346 (FromType->isSignedIntegerType() ||
1347 // We can promote any unsigned integer type whose size is
1348 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001349 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001350 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001351 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001352 }
1353
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001354 return To->getKind() == BuiltinType::UInt;
1355 }
1356
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357 // C++0x [conv.prom]p3:
1358 // A prvalue of an unscoped enumeration type whose underlying type is not
1359 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1360 // following types that can represent all the values of the enumeration
1361 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1362 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001363 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001365 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366 // with lowest integer conversion rank (4.13) greater than the rank of long
1367 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001368 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001369 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1370 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1371 // provided for a scoped enumeration.
1372 if (FromEnumType->getDecl()->isScoped())
1373 return false;
1374
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001375 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001376 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001377 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001378 return Context.hasSameUnqualifiedType(ToType,
1379 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001380 }
John McCall56774992009-12-09 09:09:27 +00001381
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001382 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1384 // to an rvalue a prvalue of the first of the following types that can
1385 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001386 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001388 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001390 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001392 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001393 // Determine whether the type we're converting from is signed or
1394 // unsigned.
1395 bool FromIsSigned;
1396 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001397
John McCall56774992009-12-09 09:09:27 +00001398 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1399 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400
1401 // The types we'll try to promote to, in the appropriate
1402 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001403 QualType PromoteTypes[6] = {
1404 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001405 Context.LongTy, Context.UnsignedLongTy ,
1406 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001407 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001408 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1410 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001411 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001412 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1413 // We found the type that we can promote to. If this is the
1414 // type we wanted, we have a promotion. Otherwise, no
1415 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001416 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001417 }
1418 }
1419 }
1420
1421 // An rvalue for an integral bit-field (9.6) can be converted to an
1422 // rvalue of type int if int can represent all the values of the
1423 // bit-field; otherwise, it can be converted to unsigned int if
1424 // unsigned int can represent all the values of the bit-field. If
1425 // the bit-field is larger yet, no integral promotion applies to
1426 // it. If the bit-field has an enumerated type, it is treated as any
1427 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001428 // FIXME: We should delay checking of bit-fields until we actually perform the
1429 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001430 using llvm::APSInt;
1431 if (From)
1432 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001433 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001434 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001435 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1436 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1437 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001438
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001439 // Are we promoting to an int from a bitfield that fits in an int?
1440 if (BitWidth < ToSize ||
1441 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1442 return To->getKind() == BuiltinType::Int;
1443 }
Mike Stump11289f42009-09-09 15:08:12 +00001444
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001445 // Are we promoting to an unsigned int from an unsigned bitfield
1446 // that fits into an unsigned int?
1447 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1448 return To->getKind() == BuiltinType::UInt;
1449 }
Mike Stump11289f42009-09-09 15:08:12 +00001450
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001451 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001452 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453 }
Mike Stump11289f42009-09-09 15:08:12 +00001454
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001455 // An rvalue of type bool can be converted to an rvalue of type int,
1456 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001457 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001458 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001459 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001460
1461 return false;
1462}
1463
1464/// IsFloatingPointPromotion - Determines whether the conversion from
1465/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1466/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001467bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001468 /// An rvalue of type float can be converted to an rvalue of type
1469 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001470 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1471 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001472 if (FromBuiltin->getKind() == BuiltinType::Float &&
1473 ToBuiltin->getKind() == BuiltinType::Double)
1474 return true;
1475
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001476 // C99 6.3.1.5p1:
1477 // When a float is promoted to double or long double, or a
1478 // double is promoted to long double [...].
1479 if (!getLangOptions().CPlusPlus &&
1480 (FromBuiltin->getKind() == BuiltinType::Float ||
1481 FromBuiltin->getKind() == BuiltinType::Double) &&
1482 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1483 return true;
1484 }
1485
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001486 return false;
1487}
1488
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001489/// \brief Determine if a conversion is a complex promotion.
1490///
1491/// A complex promotion is defined as a complex -> complex conversion
1492/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001493/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001494bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001495 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001496 if (!FromComplex)
1497 return false;
1498
John McCall9dd450b2009-09-21 23:43:11 +00001499 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001500 if (!ToComplex)
1501 return false;
1502
1503 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001504 ToComplex->getElementType()) ||
1505 IsIntegralPromotion(0, FromComplex->getElementType(),
1506 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001507}
1508
Douglas Gregor237f96c2008-11-26 23:31:11 +00001509/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1510/// the pointer type FromPtr to a pointer to type ToPointee, with the
1511/// same type qualifiers as FromPtr has on its pointee type. ToType,
1512/// if non-empty, will be a pointer to ToType that may or may not have
1513/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001514///
Mike Stump11289f42009-09-09 15:08:12 +00001515static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001516BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001517 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001518 ASTContext &Context,
1519 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001520 assert((FromPtr->getTypeClass() == Type::Pointer ||
1521 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1522 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001523
John McCall31168b02011-06-15 23:02:42 +00001524 /// Conversions to 'id' subsume cv-qualifier conversions.
1525 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001526 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527
1528 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001529 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001530 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001531 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001532
John McCall31168b02011-06-15 23:02:42 +00001533 if (StripObjCLifetime)
1534 Quals.removeObjCLifetime();
1535
Mike Stump11289f42009-09-09 15:08:12 +00001536 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001537 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001538 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001539 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001540 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001541
1542 // Build a pointer to ToPointee. It has the right qualifiers
1543 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001544 if (isa<ObjCObjectPointerType>(ToType))
1545 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001546 return Context.getPointerType(ToPointee);
1547 }
1548
1549 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001550 QualType QualifiedCanonToPointee
1551 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001553 if (isa<ObjCObjectPointerType>(ToType))
1554 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1555 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001556}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557
Mike Stump11289f42009-09-09 15:08:12 +00001558static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001559 bool InOverloadResolution,
1560 ASTContext &Context) {
1561 // Handle value-dependent integral null pointer constants correctly.
1562 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1563 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001564 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001565 return !InOverloadResolution;
1566
Douglas Gregor56751b52009-09-25 04:25:58 +00001567 return Expr->isNullPointerConstant(Context,
1568 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1569 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001570}
Mike Stump11289f42009-09-09 15:08:12 +00001571
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572/// IsPointerConversion - Determines whether the conversion of the
1573/// expression From, which has the (possibly adjusted) type FromType,
1574/// can be converted to the type ToType via a pointer conversion (C++
1575/// 4.10). If so, returns true and places the converted type (that
1576/// might differ from ToType in its cv-qualifiers at some level) into
1577/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001578///
Douglas Gregora29dc052008-11-27 01:19:21 +00001579/// This routine also supports conversions to and from block pointers
1580/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1581/// pointers to interfaces. FIXME: Once we've determined the
1582/// appropriate overloading rules for Objective-C, we may want to
1583/// split the Objective-C checks into a different routine; however,
1584/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001585/// conversions, so for now they live here. IncompatibleObjC will be
1586/// set if the conversion is an allowed Objective-C conversion that
1587/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001588bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001589 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001590 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001591 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001592 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001593 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1594 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001595 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001596
Mike Stump11289f42009-09-09 15:08:12 +00001597 // Conversion from a null pointer constant to any Objective-C pointer type.
1598 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001599 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001600 ConvertedType = ToType;
1601 return true;
1602 }
1603
Douglas Gregor231d1c62008-11-27 00:15:41 +00001604 // Blocks: Block pointers can be converted to void*.
1605 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001606 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001607 ConvertedType = ToType;
1608 return true;
1609 }
1610 // Blocks: A null pointer constant can be converted to a block
1611 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001612 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001613 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001614 ConvertedType = ToType;
1615 return true;
1616 }
1617
Sebastian Redl576fd422009-05-10 18:38:11 +00001618 // If the left-hand-side is nullptr_t, the right side can be a null
1619 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001620 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001621 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001622 ConvertedType = ToType;
1623 return true;
1624 }
1625
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001626 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001627 if (!ToTypePtr)
1628 return false;
1629
1630 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001631 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001632 ConvertedType = ToType;
1633 return true;
1634 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001635
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001636 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001637 // , including objective-c pointers.
1638 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001639 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1640 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001641 ConvertedType = BuildSimilarlyQualifiedPointerType(
1642 FromType->getAs<ObjCObjectPointerType>(),
1643 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001644 ToType, Context);
1645 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001646 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001647 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001648 if (!FromTypePtr)
1649 return false;
1650
1651 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001652
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001653 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001654 // pointer conversion, so don't do all of the work below.
1655 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1656 return false;
1657
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001658 // An rvalue of type "pointer to cv T," where T is an object type,
1659 // can be converted to an rvalue of type "pointer to cv void" (C++
1660 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001661 if (FromPointeeType->isIncompleteOrObjectType() &&
1662 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001663 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001664 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001665 ToType, Context,
1666 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667 return true;
1668 }
1669
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001670 // MSVC allows implicit function to void* type conversion.
1671 if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() &&
1672 ToPointeeType->isVoidType()) {
1673 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1674 ToPointeeType,
1675 ToType, Context);
1676 return true;
1677 }
1678
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001679 // When we're overloading in C, we allow a special kind of pointer
1680 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001681 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001682 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001683 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001684 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001685 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001686 return true;
1687 }
1688
Douglas Gregor5c407d92008-10-23 00:40:37 +00001689 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001690 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001691 // An rvalue of type "pointer to cv D," where D is a class type,
1692 // can be converted to an rvalue of type "pointer to cv B," where
1693 // B is a base class (clause 10) of D. If B is an inaccessible
1694 // (clause 11) or ambiguous (10.2) base class of D, a program that
1695 // necessitates this conversion is ill-formed. The result of the
1696 // conversion is a pointer to the base class sub-object of the
1697 // derived class object. The null pointer value is converted to
1698 // the null pointer value of the destination type.
1699 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001700 // Note that we do not check for ambiguity or inaccessibility
1701 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001702 if (getLangOptions().CPlusPlus &&
1703 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001704 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001705 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001706 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001707 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001708 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001709 ToType, Context);
1710 return true;
1711 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001712
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001713 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1714 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1715 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1716 ToPointeeType,
1717 ToType, Context);
1718 return true;
1719 }
1720
Douglas Gregora119f102008-12-19 19:13:09 +00001721 return false;
1722}
Douglas Gregoraec25842011-04-26 23:16:46 +00001723
1724/// \brief Adopt the given qualifiers for the given type.
1725static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1726 Qualifiers TQs = T.getQualifiers();
1727
1728 // Check whether qualifiers already match.
1729 if (TQs == Qs)
1730 return T;
1731
1732 if (Qs.compatiblyIncludes(TQs))
1733 return Context.getQualifiedType(T, Qs);
1734
1735 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1736}
Douglas Gregora119f102008-12-19 19:13:09 +00001737
1738/// isObjCPointerConversion - Determines whether this is an
1739/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1740/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001741bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001742 QualType& ConvertedType,
1743 bool &IncompatibleObjC) {
1744 if (!getLangOptions().ObjC1)
1745 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
Douglas Gregoraec25842011-04-26 23:16:46 +00001747 // The set of qualifiers on the type we're converting from.
1748 Qualifiers FromQualifiers = FromType.getQualifiers();
1749
Steve Naroff7cae42b2009-07-10 23:34:53 +00001750 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001751 const ObjCObjectPointerType* ToObjCPtr =
1752 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001753 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001754 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001755
Steve Naroff7cae42b2009-07-10 23:34:53 +00001756 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001757 // If the pointee types are the same (ignoring qualifications),
1758 // then this is not a pointer conversion.
1759 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1760 FromObjCPtr->getPointeeType()))
1761 return false;
1762
Douglas Gregoraec25842011-04-26 23:16:46 +00001763 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001764 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001765 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001766 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001767 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001768 return true;
1769 }
1770 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001771 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001772 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001773 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001774 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001775 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001776 return true;
1777 }
1778 // Objective C++: We're able to convert from a pointer to an
1779 // interface to a pointer to a different interface.
1780 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001781 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1782 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1783 if (getLangOptions().CPlusPlus && LHS && RHS &&
1784 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1785 FromObjCPtr->getPointeeType()))
1786 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001787 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001788 ToObjCPtr->getPointeeType(),
1789 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001790 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001791 return true;
1792 }
1793
1794 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1795 // Okay: this is some kind of implicit downcast of Objective-C
1796 // interfaces, which is permitted. However, we're going to
1797 // complain about it.
1798 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001799 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001800 ToObjCPtr->getPointeeType(),
1801 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001802 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001803 return true;
1804 }
Mike Stump11289f42009-09-09 15:08:12 +00001805 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001806 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001807 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001808 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001809 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001811 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001812 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001813 // to a block pointer type.
1814 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001815 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001816 return true;
1817 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001818 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001821 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001822 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001823 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001824 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001825 return true;
1826 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001827 else
Douglas Gregora119f102008-12-19 19:13:09 +00001828 return false;
1829
Douglas Gregor033f56d2008-12-23 00:53:59 +00001830 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001831 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001832 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001833 else if (const BlockPointerType *FromBlockPtr =
1834 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001835 FromPointeeType = FromBlockPtr->getPointeeType();
1836 else
Douglas Gregora119f102008-12-19 19:13:09 +00001837 return false;
1838
Douglas Gregora119f102008-12-19 19:13:09 +00001839 // If we have pointers to pointers, recursively check whether this
1840 // is an Objective-C conversion.
1841 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1842 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1843 IncompatibleObjC)) {
1844 // We always complain about this conversion.
1845 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001846 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001847 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001848 return true;
1849 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001850 // Allow conversion of pointee being objective-c pointer to another one;
1851 // as in I* to id.
1852 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1853 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1854 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1855 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001856
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001857 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001858 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001859 return true;
1860 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861
Douglas Gregor033f56d2008-12-23 00:53:59 +00001862 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001863 // differences in the argument and result types are in Objective-C
1864 // pointer conversions. If so, we permit the conversion (but
1865 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001866 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001867 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001868 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001869 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001870 if (FromFunctionType && ToFunctionType) {
1871 // If the function types are exactly the same, this isn't an
1872 // Objective-C pointer conversion.
1873 if (Context.getCanonicalType(FromPointeeType)
1874 == Context.getCanonicalType(ToPointeeType))
1875 return false;
1876
1877 // Perform the quick checks that will tell us whether these
1878 // function types are obviously different.
1879 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1880 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1881 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1882 return false;
1883
1884 bool HasObjCConversion = false;
1885 if (Context.getCanonicalType(FromFunctionType->getResultType())
1886 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1887 // Okay, the types match exactly. Nothing to do.
1888 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1889 ToFunctionType->getResultType(),
1890 ConvertedType, IncompatibleObjC)) {
1891 // Okay, we have an Objective-C pointer conversion.
1892 HasObjCConversion = true;
1893 } else {
1894 // Function types are too different. Abort.
1895 return false;
1896 }
Mike Stump11289f42009-09-09 15:08:12 +00001897
Douglas Gregora119f102008-12-19 19:13:09 +00001898 // Check argument types.
1899 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1900 ArgIdx != NumArgs; ++ArgIdx) {
1901 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1902 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1903 if (Context.getCanonicalType(FromArgType)
1904 == Context.getCanonicalType(ToArgType)) {
1905 // Okay, the types match exactly. Nothing to do.
1906 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1907 ConvertedType, IncompatibleObjC)) {
1908 // Okay, we have an Objective-C pointer conversion.
1909 HasObjCConversion = true;
1910 } else {
1911 // Argument types are too different. Abort.
1912 return false;
1913 }
1914 }
1915
1916 if (HasObjCConversion) {
1917 // We had an Objective-C conversion. Allow this pointer
1918 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001919 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001920 IncompatibleObjC = true;
1921 return true;
1922 }
1923 }
1924
Sebastian Redl72b597d2009-01-25 19:43:20 +00001925 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001926}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927
John McCall31168b02011-06-15 23:02:42 +00001928/// \brief Determine whether this is an Objective-C writeback conversion,
1929/// used for parameter passing when performing automatic reference counting.
1930///
1931/// \param FromType The type we're converting form.
1932///
1933/// \param ToType The type we're converting to.
1934///
1935/// \param ConvertedType The type that will be produced after applying
1936/// this conversion.
1937bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1938 QualType &ConvertedType) {
1939 if (!getLangOptions().ObjCAutoRefCount ||
1940 Context.hasSameUnqualifiedType(FromType, ToType))
1941 return false;
1942
1943 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1944 QualType ToPointee;
1945 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1946 ToPointee = ToPointer->getPointeeType();
1947 else
1948 return false;
1949
1950 Qualifiers ToQuals = ToPointee.getQualifiers();
1951 if (!ToPointee->isObjCLifetimeType() ||
1952 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1953 !ToQuals.withoutObjCGLifetime().empty())
1954 return false;
1955
1956 // Argument must be a pointer to __strong to __weak.
1957 QualType FromPointee;
1958 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1959 FromPointee = FromPointer->getPointeeType();
1960 else
1961 return false;
1962
1963 Qualifiers FromQuals = FromPointee.getQualifiers();
1964 if (!FromPointee->isObjCLifetimeType() ||
1965 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1966 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1967 return false;
1968
1969 // Make sure that we have compatible qualifiers.
1970 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1971 if (!ToQuals.compatiblyIncludes(FromQuals))
1972 return false;
1973
1974 // Remove qualifiers from the pointee type we're converting from; they
1975 // aren't used in the compatibility check belong, and we'll be adding back
1976 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1977 FromPointee = FromPointee.getUnqualifiedType();
1978
1979 // The unqualified form of the pointee types must be compatible.
1980 ToPointee = ToPointee.getUnqualifiedType();
1981 bool IncompatibleObjC;
1982 if (Context.typesAreCompatible(FromPointee, ToPointee))
1983 FromPointee = ToPointee;
1984 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1985 IncompatibleObjC))
1986 return false;
1987
1988 /// \brief Construct the type we're converting to, which is a pointer to
1989 /// __autoreleasing pointee.
1990 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1991 ConvertedType = Context.getPointerType(FromPointee);
1992 return true;
1993}
1994
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001995bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1996 QualType& ConvertedType) {
1997 QualType ToPointeeType;
1998 if (const BlockPointerType *ToBlockPtr =
1999 ToType->getAs<BlockPointerType>())
2000 ToPointeeType = ToBlockPtr->getPointeeType();
2001 else
2002 return false;
2003
2004 QualType FromPointeeType;
2005 if (const BlockPointerType *FromBlockPtr =
2006 FromType->getAs<BlockPointerType>())
2007 FromPointeeType = FromBlockPtr->getPointeeType();
2008 else
2009 return false;
2010 // We have pointer to blocks, check whether the only
2011 // differences in the argument and result types are in Objective-C
2012 // pointer conversions. If so, we permit the conversion.
2013
2014 const FunctionProtoType *FromFunctionType
2015 = FromPointeeType->getAs<FunctionProtoType>();
2016 const FunctionProtoType *ToFunctionType
2017 = ToPointeeType->getAs<FunctionProtoType>();
2018
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002019 if (!FromFunctionType || !ToFunctionType)
2020 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002021
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002022 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002023 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002024
2025 // Perform the quick checks that will tell us whether these
2026 // function types are obviously different.
2027 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2028 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2029 return false;
2030
2031 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2032 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2033 if (FromEInfo != ToEInfo)
2034 return false;
2035
2036 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002037 if (Context.hasSameType(FromFunctionType->getResultType(),
2038 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002039 // Okay, the types match exactly. Nothing to do.
2040 } else {
2041 QualType RHS = FromFunctionType->getResultType();
2042 QualType LHS = ToFunctionType->getResultType();
2043 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2044 !RHS.hasQualifiers() && LHS.hasQualifiers())
2045 LHS = LHS.getUnqualifiedType();
2046
2047 if (Context.hasSameType(RHS,LHS)) {
2048 // OK exact match.
2049 } else if (isObjCPointerConversion(RHS, LHS,
2050 ConvertedType, IncompatibleObjC)) {
2051 if (IncompatibleObjC)
2052 return false;
2053 // Okay, we have an Objective-C pointer conversion.
2054 }
2055 else
2056 return false;
2057 }
2058
2059 // Check argument types.
2060 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2061 ArgIdx != NumArgs; ++ArgIdx) {
2062 IncompatibleObjC = false;
2063 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2064 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2065 if (Context.hasSameType(FromArgType, ToArgType)) {
2066 // Okay, the types match exactly. Nothing to do.
2067 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2068 ConvertedType, IncompatibleObjC)) {
2069 if (IncompatibleObjC)
2070 return false;
2071 // Okay, we have an Objective-C pointer conversion.
2072 } else
2073 // Argument types are too different. Abort.
2074 return false;
2075 }
2076 ConvertedType = ToType;
2077 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002078}
2079
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002080/// FunctionArgTypesAreEqual - This routine checks two function proto types
2081/// for equlity of their argument types. Caller has already checked that
2082/// they have same number of arguments. This routine assumes that Objective-C
2083/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002084bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002085 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002086 if (!getLangOptions().ObjC1)
2087 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2088 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002090 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2091 N = NewType->arg_type_begin(),
2092 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2093 QualType ToType = (*O);
2094 QualType FromType = (*N);
2095 if (ToType != FromType) {
2096 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2097 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002098 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2099 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2100 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2101 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002102 continue;
2103 }
John McCall8b07ec22010-05-15 11:32:37 +00002104 else if (const ObjCObjectPointerType *PTTo =
2105 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002106 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002107 FromType->getAs<ObjCObjectPointerType>())
2108 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2109 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002111 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002112 }
2113 }
2114 return true;
2115}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002116
Douglas Gregor39c16d42008-10-24 04:54:22 +00002117/// CheckPointerConversion - Check the pointer conversion from the
2118/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002119/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002120/// conversions for which IsPointerConversion has already returned
2121/// true. It returns true and produces a diagnostic if there was an
2122/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002123bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002124 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002125 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002126 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002127 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002128 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002129
John McCall8cb679e2010-11-15 09:13:47 +00002130 Kind = CK_BitCast;
2131
Chandler Carruthffab8732011-04-09 07:32:05 +00002132 if (!IsCStyleOrFunctionalCast &&
2133 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2134 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2135 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002136 PDiag(diag::warn_impcast_bool_to_null_pointer)
2137 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002138
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002139 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2140 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002141 QualType FromPointeeType = FromPtrType->getPointeeType(),
2142 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002143
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002144 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2145 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002146 // We must have a derived-to-base conversion. Check an
2147 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002148 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2149 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002150 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002151 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002152 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002153
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002154 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002155 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002156 }
2157 }
Mike Stump11289f42009-09-09 15:08:12 +00002158 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00002159 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002160 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00002161 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002162 // Objective-C++ conversions are always okay.
2163 // FIXME: We should have a different class of conversions for the
2164 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002165 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002166 return false;
John McCall8cb679e2010-11-15 09:13:47 +00002167 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002168 }
John McCall8cb679e2010-11-15 09:13:47 +00002169
2170 // We shouldn't fall into this case unless it's valid for other
2171 // reasons.
2172 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2173 Kind = CK_NullToPointer;
2174
Douglas Gregor39c16d42008-10-24 04:54:22 +00002175 return false;
2176}
2177
Sebastian Redl72b597d2009-01-25 19:43:20 +00002178/// IsMemberPointerConversion - Determines whether the conversion of the
2179/// expression From, which has the (possibly adjusted) type FromType, can be
2180/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2181/// If so, returns true and places the converted type (that might differ from
2182/// ToType in its cv-qualifiers at some level) into ConvertedType.
2183bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002185 bool InOverloadResolution,
2186 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002187 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002188 if (!ToTypePtr)
2189 return false;
2190
2191 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002192 if (From->isNullPointerConstant(Context,
2193 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2194 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002195 ConvertedType = ToType;
2196 return true;
2197 }
2198
2199 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002200 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002201 if (!FromTypePtr)
2202 return false;
2203
2204 // A pointer to member of B can be converted to a pointer to member of D,
2205 // where D is derived from B (C++ 4.11p2).
2206 QualType FromClass(FromTypePtr->getClass(), 0);
2207 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002208
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002209 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2210 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2211 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002212 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2213 ToClass.getTypePtr());
2214 return true;
2215 }
2216
2217 return false;
2218}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002219
Sebastian Redl72b597d2009-01-25 19:43:20 +00002220/// CheckMemberPointerConversion - Check the member pointer conversion from the
2221/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002222/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002223/// for which IsMemberPointerConversion has already returned true. It returns
2224/// true and produces a diagnostic if there was an error, or returns false
2225/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002226bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002227 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002228 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002229 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002230 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002231 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002232 if (!FromPtrType) {
2233 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002234 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002235 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002236 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002237 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002238 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002239 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002240
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002241 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002242 assert(ToPtrType && "No member pointer cast has a target type "
2243 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002244
Sebastian Redled8f2002009-01-28 18:33:18 +00002245 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2246 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002247
Sebastian Redled8f2002009-01-28 18:33:18 +00002248 // FIXME: What about dependent types?
2249 assert(FromClass->isRecordType() && "Pointer into non-class.");
2250 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002251
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002252 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002253 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002254 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2255 assert(DerivationOkay &&
2256 "Should not have been called if derivation isn't OK.");
2257 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002258
Sebastian Redled8f2002009-01-28 18:33:18 +00002259 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2260 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002261 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2262 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2263 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2264 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002265 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002266
Douglas Gregor89ee6822009-02-28 01:32:25 +00002267 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002268 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2269 << FromClass << ToClass << QualType(VBase, 0)
2270 << From->getSourceRange();
2271 return true;
2272 }
2273
John McCall5b0829a2010-02-10 09:31:12 +00002274 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002275 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2276 Paths.front(),
2277 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002278
Anders Carlssond7923c62009-08-22 23:33:40 +00002279 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002280 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002281 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002282 return false;
2283}
2284
Douglas Gregor9a657932008-10-21 23:43:52 +00002285/// IsQualificationConversion - Determines whether the conversion from
2286/// an rvalue of type FromType to ToType is a qualification conversion
2287/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002288///
2289/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2290/// when the qualification conversion involves a change in the Objective-C
2291/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002292bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002293Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002294 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002295 FromType = Context.getCanonicalType(FromType);
2296 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002297 ObjCLifetimeConversion = false;
2298
Douglas Gregor9a657932008-10-21 23:43:52 +00002299 // If FromType and ToType are the same type, this is not a
2300 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002301 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002302 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002303
Douglas Gregor9a657932008-10-21 23:43:52 +00002304 // (C++ 4.4p4):
2305 // A conversion can add cv-qualifiers at levels other than the first
2306 // in multi-level pointers, subject to the following rules: [...]
2307 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002308 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002309 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002310 // Within each iteration of the loop, we check the qualifiers to
2311 // determine if this still looks like a qualification
2312 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002313 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002314 // until there are no more pointers or pointers-to-members left to
2315 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002316 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002317
Douglas Gregor90609aa2011-04-25 18:40:17 +00002318 Qualifiers FromQuals = FromType.getQualifiers();
2319 Qualifiers ToQuals = ToType.getQualifiers();
2320
John McCall31168b02011-06-15 23:02:42 +00002321 // Objective-C ARC:
2322 // Check Objective-C lifetime conversions.
2323 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2324 UnwrappedAnyPointer) {
2325 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2326 ObjCLifetimeConversion = true;
2327 FromQuals.removeObjCLifetime();
2328 ToQuals.removeObjCLifetime();
2329 } else {
2330 // Qualification conversions cannot cast between different
2331 // Objective-C lifetime qualifiers.
2332 return false;
2333 }
2334 }
2335
Douglas Gregorf30053d2011-05-08 06:09:53 +00002336 // Allow addition/removal of GC attributes but not changing GC attributes.
2337 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2338 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2339 FromQuals.removeObjCGCAttr();
2340 ToQuals.removeObjCGCAttr();
2341 }
2342
Douglas Gregor9a657932008-10-21 23:43:52 +00002343 // -- for every j > 0, if const is in cv 1,j then const is in cv
2344 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002345 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002346 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002347
Douglas Gregor9a657932008-10-21 23:43:52 +00002348 // -- if the cv 1,j and cv 2,j are different, then const is in
2349 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002350 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002351 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002352 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002353
Douglas Gregor9a657932008-10-21 23:43:52 +00002354 // Keep track of whether all prior cv-qualifiers in the "to" type
2355 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002356 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002357 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002358 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002359
2360 // We are left with FromType and ToType being the pointee types
2361 // after unwrapping the original FromType and ToType the same number
2362 // of types. If we unwrapped any pointers, and if FromType and
2363 // ToType have the same unqualified type (since we checked
2364 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002365 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002366}
2367
Douglas Gregor576e98c2009-01-30 23:27:23 +00002368/// Determines whether there is a user-defined conversion sequence
2369/// (C++ [over.ics.user]) that converts expression From to the type
2370/// ToType. If such a conversion exists, User will contain the
2371/// user-defined conversion sequence that performs such a conversion
2372/// and this routine will return true. Otherwise, this routine returns
2373/// false and User is unspecified.
2374///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002375/// \param AllowExplicit true if the conversion should consider C++0x
2376/// "explicit" conversion functions as well as non-explicit conversion
2377/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002378static OverloadingResult
2379IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2380 UserDefinedConversionSequence& User,
2381 OverloadCandidateSet& CandidateSet,
2382 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002383 // Whether we will only visit constructors.
2384 bool ConstructorsOnly = false;
2385
2386 // If the type we are conversion to is a class type, enumerate its
2387 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002388 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002389 // C++ [over.match.ctor]p1:
2390 // When objects of class type are direct-initialized (8.5), or
2391 // copy-initialized from an expression of the same or a
2392 // derived class type (8.5), overload resolution selects the
2393 // constructor. [...] For copy-initialization, the candidate
2394 // functions are all the converting constructors (12.3.1) of
2395 // that class. The argument list is the expression-list within
2396 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002397 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002398 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002399 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002400 ConstructorsOnly = true;
2401
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002402 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2403 // RequireCompleteType may have returned true due to some invalid decl
2404 // during template instantiation, but ToType may be complete enough now
2405 // to try to recover.
2406 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002407 // We're not going to find any constructors.
2408 } else if (CXXRecordDecl *ToRecordDecl
2409 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002410 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002411 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002412 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002413 NamedDecl *D = *Con;
2414 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2415
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002416 // Find the constructor (which may be a template).
2417 CXXConstructorDecl *Constructor = 0;
2418 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002419 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002420 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002421 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002422 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2423 else
John McCalla0296f72010-03-19 07:35:19 +00002424 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002425
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002426 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002427 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002428 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002429 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2430 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002431 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002432 /*SuppressUserConversions=*/
2433 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002434 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002435 // Allow one user-defined conversion when user specifies a
2436 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002437 S.AddOverloadCandidate(Constructor, FoundDecl,
2438 &From, 1, CandidateSet,
2439 /*SuppressUserConversions=*/
2440 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002441 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002442 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002443 }
2444 }
2445
Douglas Gregor5ab11652010-04-17 22:01:05 +00002446 // Enumerate conversion functions, if we're allowed to.
2447 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002448 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2449 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002450 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002451 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002452 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002453 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002454 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2455 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002456 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002457 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002458 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002459 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002460 DeclAccessPair FoundDecl = I.getPair();
2461 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002462 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2463 if (isa<UsingShadowDecl>(D))
2464 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2465
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002466 CXXConversionDecl *Conv;
2467 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002468 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2469 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002470 else
John McCallda4458e2010-03-31 01:36:47 +00002471 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002472
2473 if (AllowExplicit || !Conv->isExplicit()) {
2474 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002475 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2476 ActingContext, From, ToType,
2477 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002478 else
John McCall5c32be02010-08-24 20:38:10 +00002479 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2480 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002481 }
2482 }
2483 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002484 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002485
2486 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002487 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002488 case OR_Success:
2489 // Record the standard conversion we used and the conversion function.
2490 if (CXXConstructorDecl *Constructor
2491 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002492 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2493
John McCall5c32be02010-08-24 20:38:10 +00002494 // C++ [over.ics.user]p1:
2495 // If the user-defined conversion is specified by a
2496 // constructor (12.3.1), the initial standard conversion
2497 // sequence converts the source type to the type required by
2498 // the argument of the constructor.
2499 //
2500 QualType ThisType = Constructor->getThisType(S.Context);
2501 if (Best->Conversions[0].isEllipsis())
2502 User.EllipsisConversion = true;
2503 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002504 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002505 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002506 }
John McCall5c32be02010-08-24 20:38:10 +00002507 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002508 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002509 User.After.setAsIdentityConversion();
2510 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2511 User.After.setAllToTypes(ToType);
2512 return OR_Success;
2513 } else if (CXXConversionDecl *Conversion
2514 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002515 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2516
John McCall5c32be02010-08-24 20:38:10 +00002517 // C++ [over.ics.user]p1:
2518 //
2519 // [...] If the user-defined conversion is specified by a
2520 // conversion function (12.3.2), the initial standard
2521 // conversion sequence converts the source type to the
2522 // implicit object parameter of the conversion function.
2523 User.Before = Best->Conversions[0].Standard;
2524 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002525 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002526 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002527
John McCall5c32be02010-08-24 20:38:10 +00002528 // C++ [over.ics.user]p2:
2529 // The second standard conversion sequence converts the
2530 // result of the user-defined conversion to the target type
2531 // for the sequence. Since an implicit conversion sequence
2532 // is an initialization, the special rules for
2533 // initialization by user-defined conversion apply when
2534 // selecting the best user-defined conversion for a
2535 // user-defined conversion sequence (see 13.3.3 and
2536 // 13.3.3.1).
2537 User.After = Best->FinalConversion;
2538 return OR_Success;
2539 } else {
2540 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002541 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002542 }
2543
John McCall5c32be02010-08-24 20:38:10 +00002544 case OR_No_Viable_Function:
2545 return OR_No_Viable_Function;
2546 case OR_Deleted:
2547 // No conversion here! We're done.
2548 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002549
John McCall5c32be02010-08-24 20:38:10 +00002550 case OR_Ambiguous:
2551 return OR_Ambiguous;
2552 }
2553
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002554 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002555}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002557bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002558Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002559 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002560 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002561 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002562 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002563 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002564 if (OvResult == OR_Ambiguous)
2565 Diag(From->getSourceRange().getBegin(),
2566 diag::err_typecheck_ambiguous_condition)
2567 << From->getType() << ToType << From->getSourceRange();
2568 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2569 Diag(From->getSourceRange().getBegin(),
2570 diag::err_typecheck_nonviable_condition)
2571 << From->getType() << ToType << From->getSourceRange();
2572 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002573 return false;
John McCall5c32be02010-08-24 20:38:10 +00002574 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002575 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002576}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002577
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002578/// CompareImplicitConversionSequences - Compare two implicit
2579/// conversion sequences to determine whether one is better than the
2580/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002581static ImplicitConversionSequence::CompareKind
2582CompareImplicitConversionSequences(Sema &S,
2583 const ImplicitConversionSequence& ICS1,
2584 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002585{
2586 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2587 // conversion sequences (as defined in 13.3.3.1)
2588 // -- a standard conversion sequence (13.3.3.1.1) is a better
2589 // conversion sequence than a user-defined conversion sequence or
2590 // an ellipsis conversion sequence, and
2591 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2592 // conversion sequence than an ellipsis conversion sequence
2593 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002594 //
John McCall0d1da222010-01-12 00:44:57 +00002595 // C++0x [over.best.ics]p10:
2596 // For the purpose of ranking implicit conversion sequences as
2597 // described in 13.3.3.2, the ambiguous conversion sequence is
2598 // treated as a user-defined sequence that is indistinguishable
2599 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002600 if (ICS1.getKindRank() < ICS2.getKindRank())
2601 return ImplicitConversionSequence::Better;
2602 else if (ICS2.getKindRank() < ICS1.getKindRank())
2603 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002604
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002605 // The following checks require both conversion sequences to be of
2606 // the same kind.
2607 if (ICS1.getKind() != ICS2.getKind())
2608 return ImplicitConversionSequence::Indistinguishable;
2609
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002610 // Two implicit conversion sequences of the same form are
2611 // indistinguishable conversion sequences unless one of the
2612 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002613 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002614 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002615 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002616 // User-defined conversion sequence U1 is a better conversion
2617 // sequence than another user-defined conversion sequence U2 if
2618 // they contain the same user-defined conversion function or
2619 // constructor and if the second standard conversion sequence of
2620 // U1 is better than the second standard conversion sequence of
2621 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002622 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002623 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002624 return CompareStandardConversionSequences(S,
2625 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002626 ICS2.UserDefined.After);
2627 }
2628
2629 return ImplicitConversionSequence::Indistinguishable;
2630}
2631
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002632static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2633 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2634 Qualifiers Quals;
2635 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002636 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002639 return Context.hasSameUnqualifiedType(T1, T2);
2640}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002641
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002642// Per 13.3.3.2p3, compare the given standard conversion sequences to
2643// determine if one is a proper subset of the other.
2644static ImplicitConversionSequence::CompareKind
2645compareStandardConversionSubsets(ASTContext &Context,
2646 const StandardConversionSequence& SCS1,
2647 const StandardConversionSequence& SCS2) {
2648 ImplicitConversionSequence::CompareKind Result
2649 = ImplicitConversionSequence::Indistinguishable;
2650
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002651 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002652 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002653 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2654 return ImplicitConversionSequence::Better;
2655 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2656 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002657
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002658 if (SCS1.Second != SCS2.Second) {
2659 if (SCS1.Second == ICK_Identity)
2660 Result = ImplicitConversionSequence::Better;
2661 else if (SCS2.Second == ICK_Identity)
2662 Result = ImplicitConversionSequence::Worse;
2663 else
2664 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002665 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002666 return ImplicitConversionSequence::Indistinguishable;
2667
2668 if (SCS1.Third == SCS2.Third) {
2669 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2670 : ImplicitConversionSequence::Indistinguishable;
2671 }
2672
2673 if (SCS1.Third == ICK_Identity)
2674 return Result == ImplicitConversionSequence::Worse
2675 ? ImplicitConversionSequence::Indistinguishable
2676 : ImplicitConversionSequence::Better;
2677
2678 if (SCS2.Third == ICK_Identity)
2679 return Result == ImplicitConversionSequence::Better
2680 ? ImplicitConversionSequence::Indistinguishable
2681 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002682
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002683 return ImplicitConversionSequence::Indistinguishable;
2684}
2685
Douglas Gregore696ebb2011-01-26 14:52:12 +00002686/// \brief Determine whether one of the given reference bindings is better
2687/// than the other based on what kind of bindings they are.
2688static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2689 const StandardConversionSequence &SCS2) {
2690 // C++0x [over.ics.rank]p3b4:
2691 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2692 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002694 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002696 // reference*.
2697 //
2698 // FIXME: Rvalue references. We're going rogue with the above edits,
2699 // because the semantics in the current C++0x working paper (N3225 at the
2700 // time of this writing) break the standard definition of std::forward
2701 // and std::reference_wrapper when dealing with references to functions.
2702 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002703 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2704 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2705 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706
Douglas Gregore696ebb2011-01-26 14:52:12 +00002707 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2708 SCS2.IsLvalueReference) ||
2709 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2710 !SCS2.IsLvalueReference);
2711}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002712
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002713/// CompareStandardConversionSequences - Compare two standard
2714/// conversion sequences to determine whether one is better than the
2715/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002716static ImplicitConversionSequence::CompareKind
2717CompareStandardConversionSequences(Sema &S,
2718 const StandardConversionSequence& SCS1,
2719 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002720{
2721 // Standard conversion sequence S1 is a better conversion sequence
2722 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2723
2724 // -- S1 is a proper subsequence of S2 (comparing the conversion
2725 // sequences in the canonical form defined by 13.3.3.1.1,
2726 // excluding any Lvalue Transformation; the identity conversion
2727 // sequence is considered to be a subsequence of any
2728 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002729 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002730 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002731 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002732
2733 // -- the rank of S1 is better than the rank of S2 (by the rules
2734 // defined below), or, if not that,
2735 ImplicitConversionRank Rank1 = SCS1.getRank();
2736 ImplicitConversionRank Rank2 = SCS2.getRank();
2737 if (Rank1 < Rank2)
2738 return ImplicitConversionSequence::Better;
2739 else if (Rank2 < Rank1)
2740 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002741
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002742 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2743 // are indistinguishable unless one of the following rules
2744 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002745
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002746 // A conversion that is not a conversion of a pointer, or
2747 // pointer to member, to bool is better than another conversion
2748 // that is such a conversion.
2749 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2750 return SCS2.isPointerConversionToBool()
2751 ? ImplicitConversionSequence::Better
2752 : ImplicitConversionSequence::Worse;
2753
Douglas Gregor5c407d92008-10-23 00:40:37 +00002754 // C++ [over.ics.rank]p4b2:
2755 //
2756 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002757 // conversion of B* to A* is better than conversion of B* to
2758 // void*, and conversion of A* to void* is better than conversion
2759 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002760 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002761 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002762 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002763 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002764 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2765 // Exactly one of the conversion sequences is a conversion to
2766 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002767 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2768 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002769 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2770 // Neither conversion sequence converts to a void pointer; compare
2771 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002772 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002773 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002774 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002775 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2776 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002777 // Both conversion sequences are conversions to void
2778 // pointers. Compare the source types to determine if there's an
2779 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002780 QualType FromType1 = SCS1.getFromType();
2781 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002782
2783 // Adjust the types we're converting from via the array-to-pointer
2784 // conversion, if we need to.
2785 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002786 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002787 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002788 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002789
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002790 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2791 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002792
John McCall5c32be02010-08-24 20:38:10 +00002793 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002794 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002795 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002796 return ImplicitConversionSequence::Worse;
2797
2798 // Objective-C++: If one interface is more specific than the
2799 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002800 const ObjCObjectPointerType* FromObjCPtr1
2801 = FromType1->getAs<ObjCObjectPointerType>();
2802 const ObjCObjectPointerType* FromObjCPtr2
2803 = FromType2->getAs<ObjCObjectPointerType>();
2804 if (FromObjCPtr1 && FromObjCPtr2) {
2805 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2806 FromObjCPtr2);
2807 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2808 FromObjCPtr1);
2809 if (AssignLeft != AssignRight) {
2810 return AssignLeft? ImplicitConversionSequence::Better
2811 : ImplicitConversionSequence::Worse;
2812 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002813 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002814 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002815
2816 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2817 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002818 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002819 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002820 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002821
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002822 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002823 // Check for a better reference binding based on the kind of bindings.
2824 if (isBetterReferenceBindingKind(SCS1, SCS2))
2825 return ImplicitConversionSequence::Better;
2826 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2827 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002828
Sebastian Redlb28b4072009-03-22 23:49:27 +00002829 // C++ [over.ics.rank]p3b4:
2830 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2831 // which the references refer are the same type except for
2832 // top-level cv-qualifiers, and the type to which the reference
2833 // initialized by S2 refers is more cv-qualified than the type
2834 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002835 QualType T1 = SCS1.getToType(2);
2836 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002837 T1 = S.Context.getCanonicalType(T1);
2838 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002839 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002840 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2841 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002842 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002843 // Objective-C++ ARC: If the references refer to objects with different
2844 // lifetimes, prefer bindings that don't change lifetime.
2845 if (SCS1.ObjCLifetimeConversionBinding !=
2846 SCS2.ObjCLifetimeConversionBinding) {
2847 return SCS1.ObjCLifetimeConversionBinding
2848 ? ImplicitConversionSequence::Worse
2849 : ImplicitConversionSequence::Better;
2850 }
2851
Chandler Carruth8e543b32010-12-12 08:17:55 +00002852 // If the type is an array type, promote the element qualifiers to the
2853 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002854 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002855 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002856 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002857 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002858 if (T2.isMoreQualifiedThan(T1))
2859 return ImplicitConversionSequence::Better;
2860 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002861 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002862 }
2863 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002864
2865 return ImplicitConversionSequence::Indistinguishable;
2866}
2867
2868/// CompareQualificationConversions - Compares two standard conversion
2869/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002870/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2871ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002872CompareQualificationConversions(Sema &S,
2873 const StandardConversionSequence& SCS1,
2874 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002875 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002876 // -- S1 and S2 differ only in their qualification conversion and
2877 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2878 // cv-qualification signature of type T1 is a proper subset of
2879 // the cv-qualification signature of type T2, and S1 is not the
2880 // deprecated string literal array-to-pointer conversion (4.2).
2881 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2882 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2883 return ImplicitConversionSequence::Indistinguishable;
2884
2885 // FIXME: the example in the standard doesn't use a qualification
2886 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002887 QualType T1 = SCS1.getToType(2);
2888 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002889 T1 = S.Context.getCanonicalType(T1);
2890 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002891 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002892 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2893 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002894
2895 // If the types are the same, we won't learn anything by unwrapped
2896 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002897 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002898 return ImplicitConversionSequence::Indistinguishable;
2899
Chandler Carruth607f38e2009-12-29 07:16:59 +00002900 // If the type is an array type, promote the element qualifiers to the type
2901 // for comparison.
2902 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002903 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002904 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002905 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002906
Mike Stump11289f42009-09-09 15:08:12 +00002907 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002908 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00002909
2910 // Objective-C++ ARC:
2911 // Prefer qualification conversions not involving a change in lifetime
2912 // to qualification conversions that do not change lifetime.
2913 if (SCS1.QualificationIncludesObjCLifetime !=
2914 SCS2.QualificationIncludesObjCLifetime) {
2915 Result = SCS1.QualificationIncludesObjCLifetime
2916 ? ImplicitConversionSequence::Worse
2917 : ImplicitConversionSequence::Better;
2918 }
2919
John McCall5c32be02010-08-24 20:38:10 +00002920 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002921 // Within each iteration of the loop, we check the qualifiers to
2922 // determine if this still looks like a qualification
2923 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002924 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002925 // until there are no more pointers or pointers-to-members left
2926 // to unwrap. This essentially mimics what
2927 // IsQualificationConversion does, but here we're checking for a
2928 // strict subset of qualifiers.
2929 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2930 // The qualifiers are the same, so this doesn't tell us anything
2931 // about how the sequences rank.
2932 ;
2933 else if (T2.isMoreQualifiedThan(T1)) {
2934 // T1 has fewer qualifiers, so it could be the better sequence.
2935 if (Result == ImplicitConversionSequence::Worse)
2936 // Neither has qualifiers that are a subset of the other's
2937 // qualifiers.
2938 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002939
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002940 Result = ImplicitConversionSequence::Better;
2941 } else if (T1.isMoreQualifiedThan(T2)) {
2942 // T2 has fewer qualifiers, so it could be the better sequence.
2943 if (Result == ImplicitConversionSequence::Better)
2944 // Neither has qualifiers that are a subset of the other's
2945 // qualifiers.
2946 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002947
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002948 Result = ImplicitConversionSequence::Worse;
2949 } else {
2950 // Qualifiers are disjoint.
2951 return ImplicitConversionSequence::Indistinguishable;
2952 }
2953
2954 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002955 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002956 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002957 }
2958
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002959 // Check that the winning standard conversion sequence isn't using
2960 // the deprecated string literal array to pointer conversion.
2961 switch (Result) {
2962 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002963 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002964 Result = ImplicitConversionSequence::Indistinguishable;
2965 break;
2966
2967 case ImplicitConversionSequence::Indistinguishable:
2968 break;
2969
2970 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002971 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002972 Result = ImplicitConversionSequence::Indistinguishable;
2973 break;
2974 }
2975
2976 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002977}
2978
Douglas Gregor5c407d92008-10-23 00:40:37 +00002979/// CompareDerivedToBaseConversions - Compares two standard conversion
2980/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002981/// various kinds of derived-to-base conversions (C++
2982/// [over.ics.rank]p4b3). As part of these checks, we also look at
2983/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002984ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002985CompareDerivedToBaseConversions(Sema &S,
2986 const StandardConversionSequence& SCS1,
2987 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002988 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002989 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002990 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002991 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002992
2993 // Adjust the types we're converting from via the array-to-pointer
2994 // conversion, if we need to.
2995 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002996 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002997 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002998 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002999
3000 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003001 FromType1 = S.Context.getCanonicalType(FromType1);
3002 ToType1 = S.Context.getCanonicalType(ToType1);
3003 FromType2 = S.Context.getCanonicalType(FromType2);
3004 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003005
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003006 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003007 //
3008 // If class B is derived directly or indirectly from class A and
3009 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003010 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003011 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003012 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003013 SCS2.Second == ICK_Pointer_Conversion &&
3014 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3015 FromType1->isPointerType() && FromType2->isPointerType() &&
3016 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003017 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003018 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003019 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003020 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003021 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003022 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003023 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003024 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003025
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003026 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003027 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003028 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003029 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003030 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003031 return ImplicitConversionSequence::Worse;
3032 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003033
3034 // -- conversion of B* to A* is better than conversion of C* to A*,
3035 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003036 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003037 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003038 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003039 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003040 }
3041 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3042 SCS2.Second == ICK_Pointer_Conversion) {
3043 const ObjCObjectPointerType *FromPtr1
3044 = FromType1->getAs<ObjCObjectPointerType>();
3045 const ObjCObjectPointerType *FromPtr2
3046 = FromType2->getAs<ObjCObjectPointerType>();
3047 const ObjCObjectPointerType *ToPtr1
3048 = ToType1->getAs<ObjCObjectPointerType>();
3049 const ObjCObjectPointerType *ToPtr2
3050 = ToType2->getAs<ObjCObjectPointerType>();
3051
3052 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3053 // Apply the same conversion ranking rules for Objective-C pointer types
3054 // that we do for C++ pointers to class types. However, we employ the
3055 // Objective-C pseudo-subtyping relationship used for assignment of
3056 // Objective-C pointer types.
3057 bool FromAssignLeft
3058 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3059 bool FromAssignRight
3060 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3061 bool ToAssignLeft
3062 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3063 bool ToAssignRight
3064 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3065
3066 // A conversion to an a non-id object pointer type or qualified 'id'
3067 // type is better than a conversion to 'id'.
3068 if (ToPtr1->isObjCIdType() &&
3069 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3070 return ImplicitConversionSequence::Worse;
3071 if (ToPtr2->isObjCIdType() &&
3072 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3073 return ImplicitConversionSequence::Better;
3074
3075 // A conversion to a non-id object pointer type is better than a
3076 // conversion to a qualified 'id' type
3077 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3078 return ImplicitConversionSequence::Worse;
3079 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3080 return ImplicitConversionSequence::Better;
3081
3082 // A conversion to an a non-Class object pointer type or qualified 'Class'
3083 // type is better than a conversion to 'Class'.
3084 if (ToPtr1->isObjCClassType() &&
3085 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3086 return ImplicitConversionSequence::Worse;
3087 if (ToPtr2->isObjCClassType() &&
3088 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3089 return ImplicitConversionSequence::Better;
3090
3091 // A conversion to a non-Class object pointer type is better than a
3092 // conversion to a qualified 'Class' type.
3093 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3094 return ImplicitConversionSequence::Worse;
3095 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3096 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003097
Douglas Gregor058d3de2011-01-31 18:51:41 +00003098 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3099 if (S.Context.hasSameType(FromType1, FromType2) &&
3100 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3101 (ToAssignLeft != ToAssignRight))
3102 return ToAssignLeft? ImplicitConversionSequence::Worse
3103 : ImplicitConversionSequence::Better;
3104
3105 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3106 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3107 (FromAssignLeft != FromAssignRight))
3108 return FromAssignLeft? ImplicitConversionSequence::Better
3109 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003110 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003111 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003112
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003113 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003114 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3115 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3116 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003117 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003118 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003119 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003120 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003122 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003124 ToType2->getAs<MemberPointerType>();
3125 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3126 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3127 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3128 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3129 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3130 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3131 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3132 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003133 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003134 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003135 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003136 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003137 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003138 return ImplicitConversionSequence::Better;
3139 }
3140 // conversion of B::* to C::* is better than conversion of A::* to C::*
3141 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003142 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003143 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003144 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003145 return ImplicitConversionSequence::Worse;
3146 }
3147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148
Douglas Gregor5ab11652010-04-17 22:01:05 +00003149 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003150 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003151 // -- binding of an expression of type C to a reference of type
3152 // B& is better than binding an expression of type C to a
3153 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003154 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3155 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3156 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003157 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003158 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003159 return ImplicitConversionSequence::Worse;
3160 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003161
Douglas Gregor2fe98832008-11-03 19:09:14 +00003162 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003163 // -- binding of an expression of type B to a reference of type
3164 // A& is better than binding an expression of type C to a
3165 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003166 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3167 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3168 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003169 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003170 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003171 return ImplicitConversionSequence::Worse;
3172 }
3173 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003174
Douglas Gregor5c407d92008-10-23 00:40:37 +00003175 return ImplicitConversionSequence::Indistinguishable;
3176}
3177
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003178/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3179/// determine whether they are reference-related,
3180/// reference-compatible, reference-compatible with added
3181/// qualification, or incompatible, for use in C++ initialization by
3182/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3183/// type, and the first type (T1) is the pointee type of the reference
3184/// type being initialized.
3185Sema::ReferenceCompareResult
3186Sema::CompareReferenceRelationship(SourceLocation Loc,
3187 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003188 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003189 bool &ObjCConversion,
3190 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003191 assert(!OrigT1->isReferenceType() &&
3192 "T1 must be the pointee type of the reference type");
3193 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3194
3195 QualType T1 = Context.getCanonicalType(OrigT1);
3196 QualType T2 = Context.getCanonicalType(OrigT2);
3197 Qualifiers T1Quals, T2Quals;
3198 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3199 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3200
3201 // C++ [dcl.init.ref]p4:
3202 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3203 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3204 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003205 DerivedToBase = false;
3206 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003207 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003208 if (UnqualT1 == UnqualT2) {
3209 // Nothing to do.
3210 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003211 IsDerivedFrom(UnqualT2, UnqualT1))
3212 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003213 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3214 UnqualT2->isObjCObjectOrInterfaceType() &&
3215 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3216 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003217 else
3218 return Ref_Incompatible;
3219
3220 // At this point, we know that T1 and T2 are reference-related (at
3221 // least).
3222
3223 // If the type is an array type, promote the element qualifiers to the type
3224 // for comparison.
3225 if (isa<ArrayType>(T1) && T1Quals)
3226 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3227 if (isa<ArrayType>(T2) && T2Quals)
3228 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3229
3230 // C++ [dcl.init.ref]p4:
3231 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3232 // reference-related to T2 and cv1 is the same cv-qualification
3233 // as, or greater cv-qualification than, cv2. For purposes of
3234 // overload resolution, cases for which cv1 is greater
3235 // cv-qualification than cv2 are identified as
3236 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003237 //
3238 // Note that we also require equivalence of Objective-C GC and address-space
3239 // qualifiers when performing these computations, so that e.g., an int in
3240 // address space 1 is not reference-compatible with an int in address
3241 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003242 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3243 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3244 T1Quals.removeObjCLifetime();
3245 T2Quals.removeObjCLifetime();
3246 ObjCLifetimeConversion = true;
3247 }
3248
Douglas Gregord517d552011-04-28 17:56:11 +00003249 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003250 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003251 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003252 return Ref_Compatible_With_Added_Qualification;
3253 else
3254 return Ref_Related;
3255}
3256
Douglas Gregor836a7e82010-08-11 02:15:33 +00003257/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003258/// with DeclType. Return true if something definite is found.
3259static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003260FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3261 QualType DeclType, SourceLocation DeclLoc,
3262 Expr *Init, QualType T2, bool AllowRvalues,
3263 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003264 assert(T2->isRecordType() && "Can only find conversions of record types.");
3265 CXXRecordDecl *T2RecordDecl
3266 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3267
3268 OverloadCandidateSet CandidateSet(DeclLoc);
3269 const UnresolvedSetImpl *Conversions
3270 = T2RecordDecl->getVisibleConversionFunctions();
3271 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3272 E = Conversions->end(); I != E; ++I) {
3273 NamedDecl *D = *I;
3274 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3275 if (isa<UsingShadowDecl>(D))
3276 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3277
3278 FunctionTemplateDecl *ConvTemplate
3279 = dyn_cast<FunctionTemplateDecl>(D);
3280 CXXConversionDecl *Conv;
3281 if (ConvTemplate)
3282 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3283 else
3284 Conv = cast<CXXConversionDecl>(D);
3285
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003287 // explicit conversions, skip it.
3288 if (!AllowExplicit && Conv->isExplicit())
3289 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290
Douglas Gregor836a7e82010-08-11 02:15:33 +00003291 if (AllowRvalues) {
3292 bool DerivedToBase = false;
3293 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003294 bool ObjCLifetimeConversion = false;
Douglas Gregor836a7e82010-08-11 02:15:33 +00003295 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003296 S.CompareReferenceRelationship(
3297 DeclLoc,
3298 Conv->getConversionType().getNonReferenceType()
3299 .getUnqualifiedType(),
3300 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003301 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003302 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003303 continue;
3304 } else {
3305 // If the conversion function doesn't return a reference type,
3306 // it can't be considered for this conversion. An rvalue reference
3307 // is only acceptable if its referencee is a function type.
3308
3309 const ReferenceType *RefType =
3310 Conv->getConversionType()->getAs<ReferenceType>();
3311 if (!RefType ||
3312 (!RefType->isLValueReferenceType() &&
3313 !RefType->getPointeeType()->isFunctionType()))
3314 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003315 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316
Douglas Gregor836a7e82010-08-11 02:15:33 +00003317 if (ConvTemplate)
3318 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003319 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003320 else
3321 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003322 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003323 }
3324
3325 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003326 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003327 case OR_Success:
3328 // C++ [over.ics.ref]p1:
3329 //
3330 // [...] If the parameter binds directly to the result of
3331 // applying a conversion function to the argument
3332 // expression, the implicit conversion sequence is a
3333 // user-defined conversion sequence (13.3.3.1.2), with the
3334 // second standard conversion sequence either an identity
3335 // conversion or, if the conversion function returns an
3336 // entity of a type that is a derived class of the parameter
3337 // type, a derived-to-base Conversion.
3338 if (!Best->FinalConversion.DirectBinding)
3339 return false;
3340
Chandler Carruth30141632011-02-25 19:41:05 +00003341 if (Best->Function)
3342 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003343 ICS.setUserDefined();
3344 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3345 ICS.UserDefined.After = Best->FinalConversion;
3346 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003347 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003348 ICS.UserDefined.EllipsisConversion = false;
3349 assert(ICS.UserDefined.After.ReferenceBinding &&
3350 ICS.UserDefined.After.DirectBinding &&
3351 "Expected a direct reference binding!");
3352 return true;
3353
3354 case OR_Ambiguous:
3355 ICS.setAmbiguous();
3356 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3357 Cand != CandidateSet.end(); ++Cand)
3358 if (Cand->Viable)
3359 ICS.Ambiguous.addConversion(Cand->Function);
3360 return true;
3361
3362 case OR_No_Viable_Function:
3363 case OR_Deleted:
3364 // There was no suitable conversion, or we found a deleted
3365 // conversion; continue with other checks.
3366 return false;
3367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368
Eric Christopheraba9fb22010-06-30 18:36:32 +00003369 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003370}
3371
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003372/// \brief Compute an implicit conversion sequence for reference
3373/// initialization.
3374static ImplicitConversionSequence
3375TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3376 SourceLocation DeclLoc,
3377 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003378 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003379 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3380
3381 // Most paths end in a failed conversion.
3382 ImplicitConversionSequence ICS;
3383 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3384
3385 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3386 QualType T2 = Init->getType();
3387
3388 // If the initializer is the address of an overloaded function, try
3389 // to resolve the overloaded function. If all goes well, T2 is the
3390 // type of the resulting function.
3391 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3392 DeclAccessPair Found;
3393 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3394 false, Found))
3395 T2 = Fn->getType();
3396 }
3397
3398 // Compute some basic properties of the types and the initializer.
3399 bool isRValRef = DeclType->isRValueReferenceType();
3400 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003401 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003402 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003403 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003404 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003405 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003406 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003407
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003408
Sebastian Redld92badf2010-06-30 18:13:39 +00003409 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003410 // A reference to type "cv1 T1" is initialized by an expression
3411 // of type "cv2 T2" as follows:
3412
Sebastian Redld92badf2010-06-30 18:13:39 +00003413 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003414 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003415 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3416 // reference-compatible with "cv2 T2," or
3417 //
3418 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3419 if (InitCategory.isLValue() &&
3420 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003421 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003422 // When a parameter of reference type binds directly (8.5.3)
3423 // to an argument expression, the implicit conversion sequence
3424 // is the identity conversion, unless the argument expression
3425 // has a type that is a derived class of the parameter type,
3426 // in which case the implicit conversion sequence is a
3427 // derived-to-base Conversion (13.3.3.1).
3428 ICS.setStandard();
3429 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003430 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3431 : ObjCConversion? ICK_Compatible_Conversion
3432 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003433 ICS.Standard.Third = ICK_Identity;
3434 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3435 ICS.Standard.setToType(0, T2);
3436 ICS.Standard.setToType(1, T1);
3437 ICS.Standard.setToType(2, T1);
3438 ICS.Standard.ReferenceBinding = true;
3439 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003440 ICS.Standard.IsLvalueReference = !isRValRef;
3441 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3442 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003443 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003444 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003445 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003446
Sebastian Redld92badf2010-06-30 18:13:39 +00003447 // Nothing more to do: the inaccessibility/ambiguity check for
3448 // derived-to-base conversions is suppressed when we're
3449 // computing the implicit conversion sequence (C++
3450 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003451 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003452 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003453
Sebastian Redld92badf2010-06-30 18:13:39 +00003454 // -- has a class type (i.e., T2 is a class type), where T1 is
3455 // not reference-related to T2, and can be implicitly
3456 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3457 // is reference-compatible with "cv3 T3" 92) (this
3458 // conversion is selected by enumerating the applicable
3459 // conversion functions (13.3.1.6) and choosing the best
3460 // one through overload resolution (13.3)),
3461 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003462 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003463 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003464 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3465 Init, T2, /*AllowRvalues=*/false,
3466 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003467 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003468 }
3469 }
3470
Sebastian Redld92badf2010-06-30 18:13:39 +00003471 // -- Otherwise, the reference shall be an lvalue reference to a
3472 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003473 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003474 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003475 // We actually handle one oddity of C++ [over.ics.ref] at this
3476 // point, which is that, due to p2 (which short-circuits reference
3477 // binding by only attempting a simple conversion for non-direct
3478 // bindings) and p3's strange wording, we allow a const volatile
3479 // reference to bind to an rvalue. Hence the check for the presence
3480 // of "const" rather than checking for "const" being the only
3481 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003482 // This is also the point where rvalue references and lvalue inits no longer
3483 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003484 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003485 return ICS;
3486
Douglas Gregorf143cd52011-01-24 16:14:37 +00003487 // -- If the initializer expression
3488 //
3489 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003490 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003491 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3492 (InitCategory.isXValue() ||
3493 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3494 (InitCategory.isLValue() && T2->isFunctionType()))) {
3495 ICS.setStandard();
3496 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003498 : ObjCConversion? ICK_Compatible_Conversion
3499 : ICK_Identity;
3500 ICS.Standard.Third = ICK_Identity;
3501 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3502 ICS.Standard.setToType(0, T2);
3503 ICS.Standard.setToType(1, T1);
3504 ICS.Standard.setToType(2, T1);
3505 ICS.Standard.ReferenceBinding = true;
3506 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3507 // binding unless we're binding to a class prvalue.
3508 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3509 // allow the use of rvalue references in C++98/03 for the benefit of
3510 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511 ICS.Standard.DirectBinding =
3512 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003513 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003514 ICS.Standard.IsLvalueReference = !isRValRef;
3515 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003517 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003518 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003519 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522
Douglas Gregorf143cd52011-01-24 16:14:37 +00003523 // -- has a class type (i.e., T2 is a class type), where T1 is not
3524 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525 // an xvalue, class prvalue, or function lvalue of type
3526 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003527 // "cv3 T3",
3528 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003530 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003532 // class subobject).
3533 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003535 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3536 Init, T2, /*AllowRvalues=*/true,
3537 AllowExplicit)) {
3538 // In the second case, if the reference is an rvalue reference
3539 // and the second standard conversion sequence of the
3540 // user-defined conversion sequence includes an lvalue-to-rvalue
3541 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003543 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3544 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3545
Douglas Gregor95273c32011-01-21 16:36:05 +00003546 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003549 // -- Otherwise, a temporary of type "cv1 T1" is created and
3550 // initialized from the initializer expression using the
3551 // rules for a non-reference copy initialization (8.5). The
3552 // reference is then bound to the temporary. If T1 is
3553 // reference-related to T2, cv1 must be the same
3554 // cv-qualification as, or greater cv-qualification than,
3555 // cv2; otherwise, the program is ill-formed.
3556 if (RefRelationship == Sema::Ref_Related) {
3557 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3558 // we would be reference-compatible or reference-compatible with
3559 // added qualification. But that wasn't the case, so the reference
3560 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003561 //
3562 // Note that we only want to check address spaces and cvr-qualifiers here.
3563 // ObjC GC and lifetime qualifiers aren't important.
3564 Qualifiers T1Quals = T1.getQualifiers();
3565 Qualifiers T2Quals = T2.getQualifiers();
3566 T1Quals.removeObjCGCAttr();
3567 T1Quals.removeObjCLifetime();
3568 T2Quals.removeObjCGCAttr();
3569 T2Quals.removeObjCLifetime();
3570 if (!T1Quals.compatiblyIncludes(T2Quals))
3571 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003572 }
3573
3574 // If at least one of the types is a class type, the types are not
3575 // related, and we aren't allowed any user conversions, the
3576 // reference binding fails. This case is important for breaking
3577 // recursion, since TryImplicitConversion below will attempt to
3578 // create a temporary through the use of a copy constructor.
3579 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3580 (T1->isRecordType() || T2->isRecordType()))
3581 return ICS;
3582
Douglas Gregorcba72b12011-01-21 05:18:22 +00003583 // If T1 is reference-related to T2 and the reference is an rvalue
3584 // reference, the initializer expression shall not be an lvalue.
3585 if (RefRelationship >= Sema::Ref_Related &&
3586 isRValRef && Init->Classify(S.Context).isLValue())
3587 return ICS;
3588
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003589 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003590 // When a parameter of reference type is not bound directly to
3591 // an argument expression, the conversion sequence is the one
3592 // required to convert the argument expression to the
3593 // underlying type of the reference according to
3594 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3595 // to copy-initializing a temporary of the underlying type with
3596 // the argument expression. Any difference in top-level
3597 // cv-qualification is subsumed by the initialization itself
3598 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003599 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3600 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003601 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003602 /*CStyle=*/false,
3603 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003604
3605 // Of course, that's still a reference binding.
3606 if (ICS.isStandard()) {
3607 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003608 ICS.Standard.IsLvalueReference = !isRValRef;
3609 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3610 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003611 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003612 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003613 } else if (ICS.isUserDefined()) {
3614 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003615 ICS.Standard.IsLvalueReference = !isRValRef;
3616 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3617 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003618 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003619 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003620 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003621
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003622 return ICS;
3623}
3624
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003625/// TryCopyInitialization - Try to copy-initialize a value of type
3626/// ToType from the expression From. Return the implicit conversion
3627/// sequence required to pass this argument, which may be a bad
3628/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003629/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003630/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003631static ImplicitConversionSequence
3632TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003633 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003634 bool InOverloadResolution,
3635 bool AllowObjCWritebackConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003636 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003637 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003638 /*FIXME:*/From->getLocStart(),
3639 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003640 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003641
John McCall5c32be02010-08-24 20:38:10 +00003642 return TryImplicitConversion(S, From, ToType,
3643 SuppressUserConversions,
3644 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003645 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003646 /*CStyle=*/false,
3647 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003648}
3649
Douglas Gregor436424c2008-11-18 23:14:02 +00003650/// TryObjectArgumentInitialization - Try to initialize the object
3651/// parameter of the given member function (@c Method) from the
3652/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003653static ImplicitConversionSequence
3654TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003655 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003656 CXXMethodDecl *Method,
3657 CXXRecordDecl *ActingContext) {
3658 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003659 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3660 // const volatile object.
3661 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3662 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003663 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003664
3665 // Set up the conversion sequence as a "bad" conversion, to allow us
3666 // to exit early.
3667 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003668
3669 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003670 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003671 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003672 FromType = PT->getPointeeType();
3673
Douglas Gregor02824322011-01-26 19:30:28 +00003674 // When we had a pointer, it's implicitly dereferenced, so we
3675 // better have an lvalue.
3676 assert(FromClassification.isLValue());
3677 }
3678
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003679 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003680
Douglas Gregor02824322011-01-26 19:30:28 +00003681 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003683 // parameter is
3684 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003685 // - "lvalue reference to cv X" for functions declared without a
3686 // ref-qualifier or with the & ref-qualifier
3687 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003688 // ref-qualifier
3689 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003690 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003691 // cv-qualification on the member function declaration.
3692 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003693 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003694 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003695 // (C++ [over.match.funcs]p5). We perform a simplified version of
3696 // reference binding here, that allows class rvalues to bind to
3697 // non-constant references.
3698
Douglas Gregor02824322011-01-26 19:30:28 +00003699 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003700 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003702 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003703 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003704 ICS.setBad(BadConversionSequence::bad_qualifiers,
3705 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003706 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003707 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003708
3709 // Check that we have either the same type or a derived type. It
3710 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003711 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003712 ImplicitConversionKind SecondKind;
3713 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3714 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003715 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003716 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003717 else {
John McCall65eb8792010-02-25 01:37:24 +00003718 ICS.setBad(BadConversionSequence::unrelated_class,
3719 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003720 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003721 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003722
Douglas Gregor02824322011-01-26 19:30:28 +00003723 // Check the ref-qualifier.
3724 switch (Method->getRefQualifier()) {
3725 case RQ_None:
3726 // Do nothing; we don't care about lvalueness or rvalueness.
3727 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003728
Douglas Gregor02824322011-01-26 19:30:28 +00003729 case RQ_LValue:
3730 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3731 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003733 ImplicitParamType);
3734 return ICS;
3735 }
3736 break;
3737
3738 case RQ_RValue:
3739 if (!FromClassification.isRValue()) {
3740 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003742 ImplicitParamType);
3743 return ICS;
3744 }
3745 break;
3746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747
Douglas Gregor436424c2008-11-18 23:14:02 +00003748 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003749 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003750 ICS.Standard.setAsIdentityConversion();
3751 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003752 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003753 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003754 ICS.Standard.ReferenceBinding = true;
3755 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003757 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003758 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3759 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3760 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003761 return ICS;
3762}
3763
3764/// PerformObjectArgumentInitialization - Perform initialization of
3765/// the implicit object parameter for the given Method with the given
3766/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003767ExprResult
3768Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003770 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003771 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003772 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003773 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003774 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003775
Douglas Gregor02824322011-01-26 19:30:28 +00003776 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003777 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003778 FromRecordType = PT->getPointeeType();
3779 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003780 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003781 } else {
3782 FromRecordType = From->getType();
3783 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003784 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003785 }
3786
John McCall6e9f8f62009-12-03 04:06:58 +00003787 // Note that we always use the true parent context when performing
3788 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003789 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003790 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3791 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003792 if (ICS.isBad()) {
3793 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3794 Qualifiers FromQs = FromRecordType.getQualifiers();
3795 Qualifiers ToQs = DestType.getQualifiers();
3796 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3797 if (CVR) {
3798 Diag(From->getSourceRange().getBegin(),
3799 diag::err_member_function_call_bad_cvr)
3800 << Method->getDeclName() << FromRecordType << (CVR - 1)
3801 << From->getSourceRange();
3802 Diag(Method->getLocation(), diag::note_previous_decl)
3803 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003804 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003805 }
3806 }
3807
Douglas Gregor436424c2008-11-18 23:14:02 +00003808 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003809 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003810 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003811 }
Mike Stump11289f42009-09-09 15:08:12 +00003812
John Wiegley01296292011-04-08 18:41:53 +00003813 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3814 ExprResult FromRes =
3815 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3816 if (FromRes.isInvalid())
3817 return ExprError();
3818 From = FromRes.take();
3819 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003820
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003821 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003822 From = ImpCastExprToType(From, DestType, CK_NoOp,
3823 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3824 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003825}
3826
Douglas Gregor5fb53972009-01-14 15:45:31 +00003827/// TryContextuallyConvertToBool - Attempt to contextually convert the
3828/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003829static ImplicitConversionSequence
3830TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003831 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003832 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003833 // FIXME: Are these flags correct?
3834 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003835 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003836 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003837 /*CStyle=*/false,
3838 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003839}
3840
3841/// PerformContextuallyConvertToBool - Perform a contextual conversion
3842/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003843ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003844 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003845 if (!ICS.isBad())
3846 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847
Fariborz Jahanian76197412009-11-18 18:26:29 +00003848 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003849 return Diag(From->getSourceRange().getBegin(),
3850 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003851 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003852 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003853}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003855/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3856/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003857static ImplicitConversionSequence
3858TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3859 QualType Ty = S.Context.getObjCIdType();
3860 return TryImplicitConversion(S, From, Ty,
3861 // FIXME: Are these flags correct?
3862 /*SuppressUserConversions=*/false,
3863 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003864 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003865 /*CStyle=*/false,
3866 /*AllowObjCWritebackConversion=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003867}
John McCall5c32be02010-08-24 20:38:10 +00003868
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003869/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3870/// of the expression From to 'id'.
John Wiegley01296292011-04-08 18:41:53 +00003871ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003872 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003873 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003874 if (!ICS.isBad())
3875 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003876 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003877}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003880/// enumeration type.
3881///
3882/// This routine will attempt to convert an expression of class type to an
3883/// integral or enumeration type, if that class type only has a single
3884/// conversion to an integral or enumeration type.
3885///
Douglas Gregor4799d032010-06-30 00:20:43 +00003886/// \param Loc The source location of the construct that requires the
3887/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003888///
Douglas Gregor4799d032010-06-30 00:20:43 +00003889/// \param FromE The expression we're converting from.
3890///
3891/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3892/// have integral or enumeration type.
3893///
3894/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3895/// incomplete class type.
3896///
3897/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3898/// explicit conversion function (because no implicit conversion functions
3899/// were available). This is a recovery mode.
3900///
3901/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3902/// showing which conversion was picked.
3903///
3904/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3905/// conversion function that could convert to integral or enumeration type.
3906///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003908/// usable conversion function.
3909///
3910/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3911/// function, which may be an extension in this case.
3912///
3913/// \returns The expression, converted to an integral or enumeration type if
3914/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915ExprResult
John McCallb268a282010-08-23 23:25:46 +00003916Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003917 const PartialDiagnostic &NotIntDiag,
3918 const PartialDiagnostic &IncompleteDiag,
3919 const PartialDiagnostic &ExplicitConvDiag,
3920 const PartialDiagnostic &ExplicitConvNote,
3921 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003922 const PartialDiagnostic &AmbigNote,
3923 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003924 // We can't perform any more checking for type-dependent expressions.
3925 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003926 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003928 // If the expression already has integral or enumeration type, we're golden.
3929 QualType T = From->getType();
3930 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003931 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003932
3933 // FIXME: Check for missing '()' if T is a function type?
3934
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935 // 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 +00003936 // expression of integral or enumeration type.
3937 const RecordType *RecordTy = T->getAs<RecordType>();
3938 if (!RecordTy || !getLangOptions().CPlusPlus) {
3939 Diag(Loc, NotIntDiag)
3940 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003941 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003944 // We must have a complete class type.
3945 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003946 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003947
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003948 // Look for a conversion to an integral or enumeration type.
3949 UnresolvedSet<4> ViableConversions;
3950 UnresolvedSet<4> ExplicitConversions;
3951 const UnresolvedSetImpl *Conversions
3952 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003954 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955 E = Conversions->end();
3956 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003957 ++I) {
3958 if (CXXConversionDecl *Conversion
3959 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3960 if (Conversion->getConversionType().getNonReferenceType()
3961 ->isIntegralOrEnumerationType()) {
3962 if (Conversion->isExplicit())
3963 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3964 else
3965 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3966 }
3967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003969 switch (ViableConversions.size()) {
3970 case 0:
3971 if (ExplicitConversions.size() == 1) {
3972 DeclAccessPair Found = ExplicitConversions[0];
3973 CXXConversionDecl *Conversion
3974 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003975
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003976 // The user probably meant to invoke the given explicit
3977 // conversion; use it.
3978 QualType ConvTy
3979 = Conversion->getConversionType().getNonReferenceType();
3980 std::string TypeStr;
3981 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003982
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003983 Diag(Loc, ExplicitConvDiag)
3984 << T << ConvTy
3985 << FixItHint::CreateInsertion(From->getLocStart(),
3986 "static_cast<" + TypeStr + ">(")
3987 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3988 ")");
3989 Diag(Conversion->getLocation(), ExplicitConvNote)
3990 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991
3992 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003993 // explicit conversion function.
3994 if (isSFINAEContext())
3995 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003996
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003997 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003998 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3999 if (Result.isInvalid())
4000 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001
Douglas Gregor668443e2011-01-20 00:18:04 +00004002 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004005 // We'll complain below about a non-integral condition type.
4006 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004007
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004008 case 1: {
4009 // Apply this conversion.
4010 DeclAccessPair Found = ViableConversions[0];
4011 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004012
Douglas Gregor4799d032010-06-30 00:20:43 +00004013 CXXConversionDecl *Conversion
4014 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4015 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004017 if (ConvDiag.getDiagID()) {
4018 if (isSFINAEContext())
4019 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020
Douglas Gregor4799d032010-06-30 00:20:43 +00004021 Diag(Loc, ConvDiag)
4022 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024
Douglas Gregor668443e2011-01-20 00:18:04 +00004025 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004026 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00004027 if (Result.isInvalid())
4028 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004029
Douglas Gregor668443e2011-01-20 00:18:04 +00004030 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004031 break;
4032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004034 default:
4035 Diag(Loc, AmbigDiag)
4036 << T << From->getSourceRange();
4037 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4038 CXXConversionDecl *Conv
4039 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4040 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4041 Diag(Conv->getLocation(), AmbigNote)
4042 << ConvTy->isEnumeralType() << ConvTy;
4043 }
John McCallb268a282010-08-23 23:25:46 +00004044 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004046
Douglas Gregor5823da32010-06-29 23:25:20 +00004047 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004048 Diag(Loc, NotIntDiag)
4049 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004050
John McCallb268a282010-08-23 23:25:46 +00004051 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004052}
4053
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004054/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004055/// candidate functions, using the given function call arguments. If
4056/// @p SuppressUserConversions, then don't allow user-defined
4057/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004058///
4059/// \para PartialOverloading true if we are performing "partial" overloading
4060/// based on an incomplete set of function arguments. This feature is used by
4061/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004062void
4063Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004064 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004065 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004066 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004067 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004068 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004069 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004070 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004071 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004072 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004073 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004074
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004075 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004076 if (!isa<CXXConstructorDecl>(Method)) {
4077 // If we get here, it's because we're calling a member function
4078 // that is named without a member access expression (e.g.,
4079 // "this->f") that was either written explicitly or created
4080 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004081 // function, e.g., X::f(). We use an empty type for the implied
4082 // object argument (C++ [over.call.func]p3), and the acting context
4083 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004084 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004085 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004086 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004087 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004088 return;
4089 }
4090 // We treat a constructor like a non-member function, since its object
4091 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004092 }
4093
Douglas Gregorff7028a2009-11-13 23:59:09 +00004094 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004095 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004096
Douglas Gregor27381f32009-11-23 12:27:39 +00004097 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004098 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004099
Douglas Gregorffe14e32009-11-14 01:20:54 +00004100 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4101 // C++ [class.copy]p3:
4102 // A member function template is never instantiated to perform the copy
4103 // of a class object to an object of its class type.
4104 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004106 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004107 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4108 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004109 return;
4110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004112 // Add this candidate
4113 CandidateSet.push_back(OverloadCandidate());
4114 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004115 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004116 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004117 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004118 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004119 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004120 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004122 unsigned NumArgsInProto = Proto->getNumArgs();
4123
4124 // (C++ 13.3.2p2): A candidate function having fewer than m
4125 // parameters is viable only if it has an ellipsis in its parameter
4126 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004128 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004129 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004130 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004131 return;
4132 }
4133
4134 // (C++ 13.3.2p2): A candidate function having more than m parameters
4135 // is viable only if the (m+1)st parameter has a default argument
4136 // (8.3.6). For the purposes of overload resolution, the
4137 // parameter list is truncated on the right, so that there are
4138 // exactly m parameters.
4139 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004140 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004141 // Not enough arguments.
4142 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004143 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004144 return;
4145 }
4146
4147 // Determine the implicit conversion sequences for each of the
4148 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004149 Candidate.Conversions.resize(NumArgs);
4150 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4151 if (ArgIdx < NumArgsInProto) {
4152 // (C++ 13.3.2p3): for F to be a viable function, there shall
4153 // exist for each argument an implicit conversion sequence
4154 // (13.3.3.1) that converts that argument to the corresponding
4155 // parameter of F.
4156 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004157 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004158 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004160 /*InOverloadResolution=*/true,
4161 /*AllowObjCWritebackConversion=*/
4162 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004163 if (Candidate.Conversions[ArgIdx].isBad()) {
4164 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004165 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004166 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004167 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004168 } else {
4169 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4170 // argument for which there is no corresponding parameter is
4171 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004172 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004173 }
4174 }
4175}
4176
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004177/// \brief Add all of the function declarations in the given function set to
4178/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004179void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004180 Expr **Args, unsigned NumArgs,
4181 OverloadCandidateSet& CandidateSet,
4182 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004183 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004184 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4185 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004186 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004187 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004188 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004189 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004191 CandidateSet, SuppressUserConversions);
4192 else
John McCalla0296f72010-03-19 07:35:19 +00004193 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004194 SuppressUserConversions);
4195 } else {
John McCalla0296f72010-03-19 07:35:19 +00004196 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004197 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4198 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004199 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004200 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004201 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004203 Args[0]->Classify(Context),
4204 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004205 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004206 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004207 else
John McCalla0296f72010-03-19 07:35:19 +00004208 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004209 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004210 Args, NumArgs, CandidateSet,
4211 SuppressUserConversions);
4212 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004213 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004214}
4215
John McCallf0f1cf02009-11-17 07:50:12 +00004216/// AddMethodCandidate - Adds a named decl (which is some kind of
4217/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004218void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004219 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004220 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004221 Expr **Args, unsigned NumArgs,
4222 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004223 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004224 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004225 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004226
4227 if (isa<UsingShadowDecl>(Decl))
4228 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
John McCallf0f1cf02009-11-17 07:50:12 +00004230 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4231 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4232 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004233 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4234 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004235 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004236 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004237 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004238 } else {
John McCalla0296f72010-03-19 07:35:19 +00004239 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004240 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004241 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004242 }
4243}
4244
Douglas Gregor436424c2008-11-18 23:14:02 +00004245/// AddMethodCandidate - Adds the given C++ member function to the set
4246/// of candidate functions, using the given function call arguments
4247/// and the object argument (@c Object). For example, in a call
4248/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4249/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4250/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004251/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004252void
John McCalla0296f72010-03-19 07:35:19 +00004253Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004254 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004255 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004256 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004257 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004258 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004259 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004260 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004261 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004262 assert(!isa<CXXConstructorDecl>(Method) &&
4263 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004264
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004265 if (!CandidateSet.isNewCandidate(Method))
4266 return;
4267
Douglas Gregor27381f32009-11-23 12:27:39 +00004268 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004269 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004270
Douglas Gregor436424c2008-11-18 23:14:02 +00004271 // Add this candidate
4272 CandidateSet.push_back(OverloadCandidate());
4273 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004274 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004275 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004276 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004277 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004278 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004279
4280 unsigned NumArgsInProto = Proto->getNumArgs();
4281
4282 // (C++ 13.3.2p2): A candidate function having fewer than m
4283 // parameters is viable only if it has an ellipsis in its parameter
4284 // list (8.3.5).
4285 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4286 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004287 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004288 return;
4289 }
4290
4291 // (C++ 13.3.2p2): A candidate function having more than m parameters
4292 // is viable only if the (m+1)st parameter has a default argument
4293 // (8.3.6). For the purposes of overload resolution, the
4294 // parameter list is truncated on the right, so that there are
4295 // exactly m parameters.
4296 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4297 if (NumArgs < MinRequiredArgs) {
4298 // Not enough arguments.
4299 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004300 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004301 return;
4302 }
4303
4304 Candidate.Viable = true;
4305 Candidate.Conversions.resize(NumArgs + 1);
4306
John McCall6e9f8f62009-12-03 04:06:58 +00004307 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004308 // The implicit object argument is ignored.
4309 Candidate.IgnoreObjectArgument = true;
4310 else {
4311 // Determine the implicit conversion sequence for the object
4312 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004313 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004314 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4315 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004316 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004317 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004318 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004319 return;
4320 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004321 }
4322
4323 // Determine the implicit conversion sequences for each of the
4324 // arguments.
4325 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4326 if (ArgIdx < NumArgsInProto) {
4327 // (C++ 13.3.2p3): for F to be a viable function, there shall
4328 // exist for each argument an implicit conversion sequence
4329 // (13.3.3.1) that converts that argument to the corresponding
4330 // parameter of F.
4331 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004332 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004333 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004335 /*InOverloadResolution=*/true,
4336 /*AllowObjCWritebackConversion=*/
4337 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004338 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004339 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004340 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004341 break;
4342 }
4343 } else {
4344 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4345 // argument for which there is no corresponding parameter is
4346 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004347 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004348 }
4349 }
4350}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Douglas Gregor97628d62009-08-21 00:16:32 +00004352/// \brief Add a C++ member function template as a candidate to the candidate
4353/// set, using template argument deduction to produce an appropriate member
4354/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004355void
Douglas Gregor97628d62009-08-21 00:16:32 +00004356Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004357 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004358 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004359 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004360 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004361 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004362 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004363 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004364 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004365 if (!CandidateSet.isNewCandidate(MethodTmpl))
4366 return;
4367
Douglas Gregor97628d62009-08-21 00:16:32 +00004368 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004369 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004370 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004371 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004372 // candidate functions in the usual way.113) A given name can refer to one
4373 // or more function templates and also to a set of overloaded non-template
4374 // functions. In such a case, the candidate functions generated from each
4375 // function template are combined with the set of non-template candidate
4376 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004377 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004378 FunctionDecl *Specialization = 0;
4379 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004380 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004381 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004382 CandidateSet.push_back(OverloadCandidate());
4383 OverloadCandidate &Candidate = CandidateSet.back();
4384 Candidate.FoundDecl = FoundDecl;
4385 Candidate.Function = MethodTmpl->getTemplatedDecl();
4386 Candidate.Viable = false;
4387 Candidate.FailureKind = ovl_fail_bad_deduction;
4388 Candidate.IsSurrogate = false;
4389 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004390 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004392 Info);
4393 return;
4394 }
Mike Stump11289f42009-09-09 15:08:12 +00004395
Douglas Gregor97628d62009-08-21 00:16:32 +00004396 // Add the function template specialization produced by template argument
4397 // deduction as a candidate.
4398 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004399 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004400 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004401 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004402 ActingContext, ObjectType, ObjectClassification,
4403 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004404}
4405
Douglas Gregor05155d82009-08-21 23:19:43 +00004406/// \brief Add a C++ function template specialization as a candidate
4407/// in the candidate set, using template argument deduction to produce
4408/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004409void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004410Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004411 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004412 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004413 Expr **Args, unsigned NumArgs,
4414 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004415 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004416 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4417 return;
4418
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004419 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004420 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004421 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004422 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004423 // candidate functions in the usual way.113) A given name can refer to one
4424 // or more function templates and also to a set of overloaded non-template
4425 // functions. In such a case, the candidate functions generated from each
4426 // function template are combined with the set of non-template candidate
4427 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004428 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004429 FunctionDecl *Specialization = 0;
4430 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004431 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004432 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004433 CandidateSet.push_back(OverloadCandidate());
4434 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004435 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004436 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4437 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004438 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004439 Candidate.IsSurrogate = false;
4440 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004441 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004443 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004444 return;
4445 }
Mike Stump11289f42009-09-09 15:08:12 +00004446
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004447 // Add the function template specialization produced by template argument
4448 // deduction as a candidate.
4449 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004450 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004451 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004452}
Mike Stump11289f42009-09-09 15:08:12 +00004453
Douglas Gregora1f013e2008-11-07 22:36:19 +00004454/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004455/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004456/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004457/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004458/// (which may or may not be the same type as the type that the
4459/// conversion function produces).
4460void
4461Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004462 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004463 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004464 Expr *From, QualType ToType,
4465 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004466 assert(!Conversion->getDescribedFunctionTemplate() &&
4467 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004468 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004469 if (!CandidateSet.isNewCandidate(Conversion))
4470 return;
4471
Douglas Gregor27381f32009-11-23 12:27:39 +00004472 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004473 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004474
Douglas Gregora1f013e2008-11-07 22:36:19 +00004475 // Add this candidate
4476 CandidateSet.push_back(OverloadCandidate());
4477 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004478 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004479 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004480 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004481 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004482 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004483 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004484 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004485 Candidate.Viable = true;
4486 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004487 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004488
Douglas Gregor6affc782010-08-19 15:37:02 +00004489 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004490 // For conversion functions, the function is considered to be a member of
4491 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004492 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004493 //
4494 // Determine the implicit conversion sequence for the implicit
4495 // object parameter.
4496 QualType ImplicitParamType = From->getType();
4497 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4498 ImplicitParamType = FromPtrType->getPointeeType();
4499 CXXRecordDecl *ConversionContext
4500 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004502 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503 = TryObjectArgumentInitialization(*this, From->getType(),
4504 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004505 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
John McCall0d1da222010-01-12 00:44:57 +00004507 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004508 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004509 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004510 return;
4511 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004512
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004514 // derived to base as such conversions are given Conversion Rank. They only
4515 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4516 QualType FromCanon
4517 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4518 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4519 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4520 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004521 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004522 return;
4523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004524
Douglas Gregora1f013e2008-11-07 22:36:19 +00004525 // To determine what the conversion from the result of calling the
4526 // conversion function to the type we're eventually trying to
4527 // convert to (ToType), we need to synthesize a call to the
4528 // conversion function and attempt copy initialization from it. This
4529 // makes sure that we get the right semantics with respect to
4530 // lvalues/rvalues and the type. Fortunately, we can allocate this
4531 // call on the stack and we don't need its arguments to be
4532 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004533 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004534 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004535 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4536 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004537 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004538 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004539
Richard Smith48d24642011-07-13 22:53:21 +00004540 QualType ConversionType = Conversion->getConversionType();
4541 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004542 Candidate.Viable = false;
4543 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4544 return;
4545 }
4546
Richard Smith48d24642011-07-13 22:53:21 +00004547 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004548
Mike Stump11289f42009-09-09 15:08:12 +00004549 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004550 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4551 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004552 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004553 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004554 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004555 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004556 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004557 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004558 /*InOverloadResolution=*/false,
4559 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004560
John McCall0d1da222010-01-12 00:44:57 +00004561 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004562 case ImplicitConversionSequence::StandardConversion:
4563 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004565 // C++ [over.ics.user]p3:
4566 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004568 // shall have exact match rank.
4569 if (Conversion->getPrimaryTemplate() &&
4570 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4571 Candidate.Viable = false;
4572 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574
Douglas Gregorcba72b12011-01-21 05:18:22 +00004575 // C++0x [dcl.init.ref]p5:
4576 // In the second case, if the reference is an rvalue reference and
4577 // the second standard conversion sequence of the user-defined
4578 // conversion sequence includes an lvalue-to-rvalue conversion, the
4579 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004581 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4582 Candidate.Viable = false;
4583 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4584 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004585 break;
4586
4587 case ImplicitConversionSequence::BadConversion:
4588 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004589 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004590 break;
4591
4592 default:
Mike Stump11289f42009-09-09 15:08:12 +00004593 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004594 "Can only end up with a standard conversion sequence or failure");
4595 }
4596}
4597
Douglas Gregor05155d82009-08-21 23:19:43 +00004598/// \brief Adds a conversion function template specialization
4599/// candidate to the overload set, using template argument deduction
4600/// to deduce the template arguments of the conversion function
4601/// template from the type that we are converting to (C++
4602/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004603void
Douglas Gregor05155d82009-08-21 23:19:43 +00004604Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004605 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004606 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004607 Expr *From, QualType ToType,
4608 OverloadCandidateSet &CandidateSet) {
4609 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4610 "Only conversion function templates permitted here");
4611
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004612 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4613 return;
4614
John McCallbc077cf2010-02-08 23:07:23 +00004615 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004616 CXXConversionDecl *Specialization = 0;
4617 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004618 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004619 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004620 CandidateSet.push_back(OverloadCandidate());
4621 OverloadCandidate &Candidate = CandidateSet.back();
4622 Candidate.FoundDecl = FoundDecl;
4623 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4624 Candidate.Viable = false;
4625 Candidate.FailureKind = ovl_fail_bad_deduction;
4626 Candidate.IsSurrogate = false;
4627 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004628 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004630 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004631 return;
4632 }
Mike Stump11289f42009-09-09 15:08:12 +00004633
Douglas Gregor05155d82009-08-21 23:19:43 +00004634 // Add the conversion function template specialization produced by
4635 // template argument deduction as a candidate.
4636 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004637 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004638 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004639}
4640
Douglas Gregorab7897a2008-11-19 22:57:39 +00004641/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4642/// converts the given @c Object to a function pointer via the
4643/// conversion function @c Conversion, and then attempts to call it
4644/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4645/// the type of function that we'll eventually be calling.
4646void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004647 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004648 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004649 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004650 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004651 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004652 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004653 if (!CandidateSet.isNewCandidate(Conversion))
4654 return;
4655
Douglas Gregor27381f32009-11-23 12:27:39 +00004656 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004657 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004658
Douglas Gregorab7897a2008-11-19 22:57:39 +00004659 CandidateSet.push_back(OverloadCandidate());
4660 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004661 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004662 Candidate.Function = 0;
4663 Candidate.Surrogate = Conversion;
4664 Candidate.Viable = true;
4665 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004666 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004667 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004668 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004669
4670 // Determine the implicit conversion sequence for the implicit
4671 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004672 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004674 Object->Classify(Context),
4675 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004676 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004677 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004678 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004679 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004680 return;
4681 }
4682
4683 // The first conversion is actually a user-defined conversion whose
4684 // first conversion is ObjectInit's standard conversion (which is
4685 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004686 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004687 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004688 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004689 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004690 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004691 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004692 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004693 = Candidate.Conversions[0].UserDefined.Before;
4694 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4695
Mike Stump11289f42009-09-09 15:08:12 +00004696 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004697 unsigned NumArgsInProto = Proto->getNumArgs();
4698
4699 // (C++ 13.3.2p2): A candidate function having fewer than m
4700 // parameters is viable only if it has an ellipsis in its parameter
4701 // list (8.3.5).
4702 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4703 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004704 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004705 return;
4706 }
4707
4708 // Function types don't have any default arguments, so just check if
4709 // we have enough arguments.
4710 if (NumArgs < NumArgsInProto) {
4711 // Not enough arguments.
4712 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004713 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004714 return;
4715 }
4716
4717 // Determine the implicit conversion sequences for each of the
4718 // arguments.
4719 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4720 if (ArgIdx < NumArgsInProto) {
4721 // (C++ 13.3.2p3): for F to be a viable function, there shall
4722 // exist for each argument an implicit conversion sequence
4723 // (13.3.3.1) that converts that argument to the corresponding
4724 // parameter of F.
4725 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004726 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004727 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004728 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00004729 /*InOverloadResolution=*/false,
4730 /*AllowObjCWritebackConversion=*/
4731 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004732 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004733 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004734 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004735 break;
4736 }
4737 } else {
4738 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4739 // argument for which there is no corresponding parameter is
4740 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004741 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004742 }
4743 }
4744}
4745
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004746/// \brief Add overload candidates for overloaded operators that are
4747/// member functions.
4748///
4749/// Add the overloaded operator candidates that are member functions
4750/// for the operator Op that was used in an operator expression such
4751/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4752/// CandidateSet will store the added overload candidates. (C++
4753/// [over.match.oper]).
4754void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4755 SourceLocation OpLoc,
4756 Expr **Args, unsigned NumArgs,
4757 OverloadCandidateSet& CandidateSet,
4758 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004759 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4760
4761 // C++ [over.match.oper]p3:
4762 // For a unary operator @ with an operand of a type whose
4763 // cv-unqualified version is T1, and for a binary operator @ with
4764 // a left operand of a type whose cv-unqualified version is T1 and
4765 // a right operand of a type whose cv-unqualified version is T2,
4766 // three sets of candidate functions, designated member
4767 // candidates, non-member candidates and built-in candidates, are
4768 // constructed as follows:
4769 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004770
4771 // -- If T1 is a class type, the set of member candidates is the
4772 // result of the qualified lookup of T1::operator@
4773 // (13.3.1.1.1); otherwise, the set of member candidates is
4774 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004775 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004776 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004777 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004778 return;
Mike Stump11289f42009-09-09 15:08:12 +00004779
John McCall27b18f82009-11-17 02:14:36 +00004780 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4781 LookupQualifiedName(Operators, T1Rec->getDecl());
4782 Operators.suppressDiagnostics();
4783
Mike Stump11289f42009-09-09 15:08:12 +00004784 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004785 OperEnd = Operators.end();
4786 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004787 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004788 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004789 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004790 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004791 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004792 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004793}
4794
Douglas Gregora11693b2008-11-12 17:17:38 +00004795/// AddBuiltinCandidate - Add a candidate for a built-in
4796/// operator. ResultTy and ParamTys are the result and parameter types
4797/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004798/// arguments being passed to the candidate. IsAssignmentOperator
4799/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004800/// operator. NumContextualBoolArguments is the number of arguments
4801/// (at the beginning of the argument list) that will be contextually
4802/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004803void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004804 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004805 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004806 bool IsAssignmentOperator,
4807 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004808 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004809 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004810
Douglas Gregora11693b2008-11-12 17:17:38 +00004811 // Add this candidate
4812 CandidateSet.push_back(OverloadCandidate());
4813 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004814 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004815 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004816 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004817 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004818 Candidate.BuiltinTypes.ResultTy = ResultTy;
4819 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4820 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4821
4822 // Determine the implicit conversion sequences for each of the
4823 // arguments.
4824 Candidate.Viable = true;
4825 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004826 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004827 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004828 // C++ [over.match.oper]p4:
4829 // For the built-in assignment operators, conversions of the
4830 // left operand are restricted as follows:
4831 // -- no temporaries are introduced to hold the left operand, and
4832 // -- no user-defined conversions are applied to the left
4833 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004834 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004835 //
4836 // We block these conversions by turning off user-defined
4837 // conversions, since that is the only way that initialization of
4838 // a reference to a non-class type can occur from something that
4839 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004840 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004841 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004842 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004843 Candidate.Conversions[ArgIdx]
4844 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004845 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004846 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004847 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004848 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00004849 /*InOverloadResolution=*/false,
4850 /*AllowObjCWritebackConversion=*/
4851 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004852 }
John McCall0d1da222010-01-12 00:44:57 +00004853 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004854 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004855 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004856 break;
4857 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004858 }
4859}
4860
4861/// BuiltinCandidateTypeSet - A set of types that will be used for the
4862/// candidate operator functions for built-in operators (C++
4863/// [over.built]). The types are separated into pointer types and
4864/// enumeration types.
4865class BuiltinCandidateTypeSet {
4866 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004867 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004868
4869 /// PointerTypes - The set of pointer types that will be used in the
4870 /// built-in candidates.
4871 TypeSet PointerTypes;
4872
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004873 /// MemberPointerTypes - The set of member pointer types that will be
4874 /// used in the built-in candidates.
4875 TypeSet MemberPointerTypes;
4876
Douglas Gregora11693b2008-11-12 17:17:38 +00004877 /// EnumerationTypes - The set of enumeration types that will be
4878 /// used in the built-in candidates.
4879 TypeSet EnumerationTypes;
4880
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004882 /// candidates.
4883 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004884
4885 /// \brief A flag indicating non-record types are viable candidates
4886 bool HasNonRecordTypes;
4887
4888 /// \brief A flag indicating whether either arithmetic or enumeration types
4889 /// were present in the candidate set.
4890 bool HasArithmeticOrEnumeralTypes;
4891
Douglas Gregor80af3132011-05-21 23:15:46 +00004892 /// \brief A flag indicating whether the nullptr type was present in the
4893 /// candidate set.
4894 bool HasNullPtrType;
4895
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004896 /// Sema - The semantic analysis instance where we are building the
4897 /// candidate type set.
4898 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004899
Douglas Gregora11693b2008-11-12 17:17:38 +00004900 /// Context - The AST context in which we will build the type sets.
4901 ASTContext &Context;
4902
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004903 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4904 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004905 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004906
4907public:
4908 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004909 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004910
Mike Stump11289f42009-09-09 15:08:12 +00004911 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004912 : HasNonRecordTypes(false),
4913 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00004914 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00004915 SemaRef(SemaRef),
4916 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004917
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004919 SourceLocation Loc,
4920 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004921 bool AllowExplicitConversions,
4922 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004923
4924 /// pointer_begin - First pointer type found;
4925 iterator pointer_begin() { return PointerTypes.begin(); }
4926
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004927 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004928 iterator pointer_end() { return PointerTypes.end(); }
4929
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004930 /// member_pointer_begin - First member pointer type found;
4931 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4932
4933 /// member_pointer_end - Past the last member pointer type found;
4934 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4935
Douglas Gregora11693b2008-11-12 17:17:38 +00004936 /// enumeration_begin - First enumeration type found;
4937 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4938
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004939 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004940 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004941
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004942 iterator vector_begin() { return VectorTypes.begin(); }
4943 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004944
4945 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4946 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00004947 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004948};
4949
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004950/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004951/// the set of pointer types along with any more-qualified variants of
4952/// that type. For example, if @p Ty is "int const *", this routine
4953/// will add "int const *", "int const volatile *", "int const
4954/// restrict *", and "int const volatile restrict *" to the set of
4955/// pointer types. Returns true if the add of @p Ty itself succeeded,
4956/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004957///
4958/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004959bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004960BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4961 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004962
Douglas Gregora11693b2008-11-12 17:17:38 +00004963 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004964 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004965 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004967 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004968 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004969 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004970 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004971 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004972 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004973 buildObjCPtr = true;
4974 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004975 else
4976 assert(false && "type was not a pointer type!");
4977 }
4978 else
4979 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Sebastian Redl4990a632009-11-18 20:39:26 +00004981 // Don't add qualified variants of arrays. For one, they're not allowed
4982 // (the qualifier would sink to the element type), and for another, the
4983 // only overload situation where it matters is subscript or pointer +- int,
4984 // and those shouldn't have qualifier variants anyway.
4985 if (PointeeTy->isArrayType())
4986 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004987 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004988 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004989 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004990 bool hasVolatile = VisibleQuals.hasVolatile();
4991 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004992
John McCall8ccfcb52009-09-24 19:53:00 +00004993 // Iterate through all strict supersets of BaseCVR.
4994 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4995 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004996 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4997 // in the types.
4998 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4999 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005000 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005001 if (!buildObjCPtr)
5002 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5003 else
5004 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005005 }
5006
5007 return true;
5008}
5009
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005010/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5011/// to the set of pointer types along with any more-qualified variants of
5012/// that type. For example, if @p Ty is "int const *", this routine
5013/// will add "int const *", "int const volatile *", "int const
5014/// restrict *", and "int const volatile restrict *" to the set of
5015/// pointer types. Returns true if the add of @p Ty itself succeeded,
5016/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005017///
5018/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005019bool
5020BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5021 QualType Ty) {
5022 // Insert this type.
5023 if (!MemberPointerTypes.insert(Ty))
5024 return false;
5025
John McCall8ccfcb52009-09-24 19:53:00 +00005026 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5027 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005028
John McCall8ccfcb52009-09-24 19:53:00 +00005029 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005030 // Don't add qualified variants of arrays. For one, they're not allowed
5031 // (the qualifier would sink to the element type), and for another, the
5032 // only overload situation where it matters is subscript or pointer +- int,
5033 // and those shouldn't have qualifier variants anyway.
5034 if (PointeeTy->isArrayType())
5035 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005036 const Type *ClassTy = PointerTy->getClass();
5037
5038 // Iterate through all strict supersets of the pointee type's CVR
5039 // qualifiers.
5040 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5041 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5042 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043
John McCall8ccfcb52009-09-24 19:53:00 +00005044 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005045 MemberPointerTypes.insert(
5046 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005047 }
5048
5049 return true;
5050}
5051
Douglas Gregora11693b2008-11-12 17:17:38 +00005052/// AddTypesConvertedFrom - Add each of the types to which the type @p
5053/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005054/// primarily interested in pointer types and enumeration types. We also
5055/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005056/// AllowUserConversions is true if we should look at the conversion
5057/// functions of a class type, and AllowExplicitConversions if we
5058/// should also include the explicit conversion functions of a class
5059/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005060void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005061BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005062 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005063 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005064 bool AllowExplicitConversions,
5065 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005066 // Only deal with canonical types.
5067 Ty = Context.getCanonicalType(Ty);
5068
5069 // Look through reference types; they aren't part of the type of an
5070 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005071 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005072 Ty = RefTy->getPointeeType();
5073
John McCall33ddac02011-01-19 10:06:00 +00005074 // If we're dealing with an array type, decay to the pointer.
5075 if (Ty->isArrayType())
5076 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5077
5078 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005079 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005080
Chandler Carruth00a38332010-12-13 01:44:01 +00005081 // Flag if we ever add a non-record type.
5082 const RecordType *TyRec = Ty->getAs<RecordType>();
5083 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5084
Chandler Carruth00a38332010-12-13 01:44:01 +00005085 // Flag if we encounter an arithmetic type.
5086 HasArithmeticOrEnumeralTypes =
5087 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5088
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005089 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5090 PointerTypes.insert(Ty);
5091 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005092 // Insert our type, and its more-qualified variants, into the set
5093 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005094 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005095 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005096 } else if (Ty->isMemberPointerType()) {
5097 // Member pointers are far easier, since the pointee can't be converted.
5098 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5099 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005100 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005101 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005102 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005103 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005104 // We treat vector types as arithmetic types in many contexts as an
5105 // extension.
5106 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005107 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005108 } else if (Ty->isNullPtrType()) {
5109 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005110 } else if (AllowUserConversions && TyRec) {
5111 // No conversion functions in incomplete types.
5112 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5113 return;
Mike Stump11289f42009-09-09 15:08:12 +00005114
Chandler Carruth00a38332010-12-13 01:44:01 +00005115 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5116 const UnresolvedSetImpl *Conversions
5117 = ClassDecl->getVisibleConversionFunctions();
5118 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5119 E = Conversions->end(); I != E; ++I) {
5120 NamedDecl *D = I.getDecl();
5121 if (isa<UsingShadowDecl>(D))
5122 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005123
Chandler Carruth00a38332010-12-13 01:44:01 +00005124 // Skip conversion function templates; they don't tell us anything
5125 // about which builtin types we can convert to.
5126 if (isa<FunctionTemplateDecl>(D))
5127 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005128
Chandler Carruth00a38332010-12-13 01:44:01 +00005129 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5130 if (AllowExplicitConversions || !Conv->isExplicit()) {
5131 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5132 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005133 }
5134 }
5135 }
5136}
5137
Douglas Gregor84605ae2009-08-24 13:43:27 +00005138/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5139/// the volatile- and non-volatile-qualified assignment operators for the
5140/// given type to the candidate set.
5141static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5142 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005143 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005144 unsigned NumArgs,
5145 OverloadCandidateSet &CandidateSet) {
5146 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005147
Douglas Gregor84605ae2009-08-24 13:43:27 +00005148 // T& operator=(T&, T)
5149 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5150 ParamTypes[1] = T;
5151 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5152 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005153
Douglas Gregor84605ae2009-08-24 13:43:27 +00005154 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5155 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005156 ParamTypes[0]
5157 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005158 ParamTypes[1] = T;
5159 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005160 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005161 }
5162}
Mike Stump11289f42009-09-09 15:08:12 +00005163
Sebastian Redl1054fae2009-10-25 17:03:50 +00005164/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5165/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005166static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5167 Qualifiers VRQuals;
5168 const RecordType *TyRec;
5169 if (const MemberPointerType *RHSMPType =
5170 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005171 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005172 else
5173 TyRec = ArgExpr->getType()->getAs<RecordType>();
5174 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005175 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005176 VRQuals.addVolatile();
5177 VRQuals.addRestrict();
5178 return VRQuals;
5179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005180
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005181 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005182 if (!ClassDecl->hasDefinition())
5183 return VRQuals;
5184
John McCallad371252010-01-20 00:46:10 +00005185 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005186 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005187
John McCallad371252010-01-20 00:46:10 +00005188 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005189 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005190 NamedDecl *D = I.getDecl();
5191 if (isa<UsingShadowDecl>(D))
5192 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5193 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005194 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5195 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5196 CanTy = ResTypeRef->getPointeeType();
5197 // Need to go down the pointer/mempointer chain and add qualifiers
5198 // as see them.
5199 bool done = false;
5200 while (!done) {
5201 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5202 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005204 CanTy->getAs<MemberPointerType>())
5205 CanTy = ResTypeMPtr->getPointeeType();
5206 else
5207 done = true;
5208 if (CanTy.isVolatileQualified())
5209 VRQuals.addVolatile();
5210 if (CanTy.isRestrictQualified())
5211 VRQuals.addRestrict();
5212 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5213 return VRQuals;
5214 }
5215 }
5216 }
5217 return VRQuals;
5218}
John McCall52872982010-11-13 05:51:15 +00005219
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005220namespace {
John McCall52872982010-11-13 05:51:15 +00005221
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005222/// \brief Helper class to manage the addition of builtin operator overload
5223/// candidates. It provides shared state and utility methods used throughout
5224/// the process, as well as a helper method to add each group of builtin
5225/// operator overloads from the standard to a candidate set.
5226class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005227 // Common instance state available to all overload candidate addition methods.
5228 Sema &S;
5229 Expr **Args;
5230 unsigned NumArgs;
5231 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005232 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005233 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
5234 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005235
Chandler Carruthc6586e52010-12-12 10:35:00 +00005236 // Define some constants used to index and iterate over the arithemetic types
5237 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005238 // The "promoted arithmetic types" are the arithmetic
5239 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005240 static const unsigned FirstIntegralType = 3;
5241 static const unsigned LastIntegralType = 18;
5242 static const unsigned FirstPromotedIntegralType = 3,
5243 LastPromotedIntegralType = 9;
5244 static const unsigned FirstPromotedArithmeticType = 0,
5245 LastPromotedArithmeticType = 9;
5246 static const unsigned NumArithmeticTypes = 18;
5247
Chandler Carruthc6586e52010-12-12 10:35:00 +00005248 /// \brief Get the canonical type for a given arithmetic type index.
5249 CanQualType getArithmeticType(unsigned index) {
5250 assert(index < NumArithmeticTypes);
5251 static CanQualType ASTContext::* const
5252 ArithmeticTypes[NumArithmeticTypes] = {
5253 // Start of promoted types.
5254 &ASTContext::FloatTy,
5255 &ASTContext::DoubleTy,
5256 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005257
Chandler Carruthc6586e52010-12-12 10:35:00 +00005258 // Start of integral types.
5259 &ASTContext::IntTy,
5260 &ASTContext::LongTy,
5261 &ASTContext::LongLongTy,
5262 &ASTContext::UnsignedIntTy,
5263 &ASTContext::UnsignedLongTy,
5264 &ASTContext::UnsignedLongLongTy,
5265 // End of promoted types.
5266
5267 &ASTContext::BoolTy,
5268 &ASTContext::CharTy,
5269 &ASTContext::WCharTy,
5270 &ASTContext::Char16Ty,
5271 &ASTContext::Char32Ty,
5272 &ASTContext::SignedCharTy,
5273 &ASTContext::ShortTy,
5274 &ASTContext::UnsignedCharTy,
5275 &ASTContext::UnsignedShortTy,
5276 // End of integral types.
5277 // FIXME: What about complex?
5278 };
5279 return S.Context.*ArithmeticTypes[index];
5280 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005281
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005282 /// \brief Gets the canonical type resulting from the usual arithemetic
5283 /// converions for the given arithmetic types.
5284 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5285 // Accelerator table for performing the usual arithmetic conversions.
5286 // The rules are basically:
5287 // - if either is floating-point, use the wider floating-point
5288 // - if same signedness, use the higher rank
5289 // - if same size, use unsigned of the higher rank
5290 // - use the larger type
5291 // These rules, together with the axiom that higher ranks are
5292 // never smaller, are sufficient to precompute all of these results
5293 // *except* when dealing with signed types of higher rank.
5294 // (we could precompute SLL x UI for all known platforms, but it's
5295 // better not to make any assumptions).
5296 enum PromotedType {
5297 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5298 };
5299 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5300 [LastPromotedArithmeticType] = {
5301 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5302 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5303 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5304 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5305 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5306 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5307 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5308 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5309 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5310 };
5311
5312 assert(L < LastPromotedArithmeticType);
5313 assert(R < LastPromotedArithmeticType);
5314 int Idx = ConversionsTable[L][R];
5315
5316 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005317 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005318
5319 // Slow path: we need to compare widths.
5320 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005321 CanQualType LT = getArithmeticType(L),
5322 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005323 unsigned LW = S.Context.getIntWidth(LT),
5324 RW = S.Context.getIntWidth(RT);
5325
5326 // If they're different widths, use the signed type.
5327 if (LW > RW) return LT;
5328 else if (LW < RW) return RT;
5329
5330 // Otherwise, use the unsigned type of the signed type's rank.
5331 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5332 assert(L == SLL || R == SLL);
5333 return S.Context.UnsignedLongLongTy;
5334 }
5335
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005336 /// \brief Helper method to factor out the common pattern of adding overloads
5337 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005338 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5339 bool HasVolatile) {
5340 QualType ParamTypes[2] = {
5341 S.Context.getLValueReferenceType(CandidateTy),
5342 S.Context.IntTy
5343 };
5344
5345 // Non-volatile version.
5346 if (NumArgs == 1)
5347 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5348 else
5349 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5350
5351 // Use a heuristic to reduce number of builtin candidates in the set:
5352 // add volatile version only if there are conversions to a volatile type.
5353 if (HasVolatile) {
5354 ParamTypes[0] =
5355 S.Context.getLValueReferenceType(
5356 S.Context.getVolatileType(CandidateTy));
5357 if (NumArgs == 1)
5358 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5359 else
5360 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5361 }
5362 }
5363
5364public:
5365 BuiltinOperatorOverloadBuilder(
5366 Sema &S, Expr **Args, unsigned NumArgs,
5367 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005368 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005369 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5370 OverloadCandidateSet &CandidateSet)
5371 : S(S), Args(Args), NumArgs(NumArgs),
5372 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005373 HasArithmeticOrEnumeralCandidateType(
5374 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005375 CandidateTypes(CandidateTypes),
5376 CandidateSet(CandidateSet) {
5377 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005378 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005379 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005380 assert(getArithmeticType(LastPromotedIntegralType - 1)
5381 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005382 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005383 assert(getArithmeticType(FirstPromotedArithmeticType)
5384 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005385 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005386 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5387 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005388 "Invalid last promoted arithmetic type");
5389 }
5390
5391 // C++ [over.built]p3:
5392 //
5393 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5394 // is either volatile or empty, there exist candidate operator
5395 // functions of the form
5396 //
5397 // VQ T& operator++(VQ T&);
5398 // T operator++(VQ T&, int);
5399 //
5400 // C++ [over.built]p4:
5401 //
5402 // For every pair (T, VQ), where T is an arithmetic type other
5403 // than bool, and VQ is either volatile or empty, there exist
5404 // candidate operator functions of the form
5405 //
5406 // VQ T& operator--(VQ T&);
5407 // T operator--(VQ T&, int);
5408 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005409 if (!HasArithmeticOrEnumeralCandidateType)
5410 return;
5411
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005412 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5413 Arith < NumArithmeticTypes; ++Arith) {
5414 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005415 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005416 VisibleTypeConversionsQuals.hasVolatile());
5417 }
5418 }
5419
5420 // C++ [over.built]p5:
5421 //
5422 // For every pair (T, VQ), where T is a cv-qualified or
5423 // cv-unqualified object type, and VQ is either volatile or
5424 // empty, there exist candidate operator functions of the form
5425 //
5426 // T*VQ& operator++(T*VQ&);
5427 // T*VQ& operator--(T*VQ&);
5428 // T* operator++(T*VQ&, int);
5429 // T* operator--(T*VQ&, int);
5430 void addPlusPlusMinusMinusPointerOverloads() {
5431 for (BuiltinCandidateTypeSet::iterator
5432 Ptr = CandidateTypes[0].pointer_begin(),
5433 PtrEnd = CandidateTypes[0].pointer_end();
5434 Ptr != PtrEnd; ++Ptr) {
5435 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005436 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005437 continue;
5438
5439 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5440 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5441 VisibleTypeConversionsQuals.hasVolatile()));
5442 }
5443 }
5444
5445 // C++ [over.built]p6:
5446 // For every cv-qualified or cv-unqualified object type T, there
5447 // exist candidate operator functions of the form
5448 //
5449 // T& operator*(T*);
5450 //
5451 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005452 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005453 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005454 // T& operator*(T*);
5455 void addUnaryStarPointerOverloads() {
5456 for (BuiltinCandidateTypeSet::iterator
5457 Ptr = CandidateTypes[0].pointer_begin(),
5458 PtrEnd = CandidateTypes[0].pointer_end();
5459 Ptr != PtrEnd; ++Ptr) {
5460 QualType ParamTy = *Ptr;
5461 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005462 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5463 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464
Douglas Gregor02824322011-01-26 19:30:28 +00005465 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5466 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5467 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005469 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5470 &ParamTy, Args, 1, CandidateSet);
5471 }
5472 }
5473
5474 // C++ [over.built]p9:
5475 // For every promoted arithmetic type T, there exist candidate
5476 // operator functions of the form
5477 //
5478 // T operator+(T);
5479 // T operator-(T);
5480 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005481 if (!HasArithmeticOrEnumeralCandidateType)
5482 return;
5483
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005484 for (unsigned Arith = FirstPromotedArithmeticType;
5485 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005486 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005487 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5488 }
5489
5490 // Extension: We also add these operators for vector types.
5491 for (BuiltinCandidateTypeSet::iterator
5492 Vec = CandidateTypes[0].vector_begin(),
5493 VecEnd = CandidateTypes[0].vector_end();
5494 Vec != VecEnd; ++Vec) {
5495 QualType VecTy = *Vec;
5496 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5497 }
5498 }
5499
5500 // C++ [over.built]p8:
5501 // For every type T, there exist candidate operator functions of
5502 // the form
5503 //
5504 // T* operator+(T*);
5505 void addUnaryPlusPointerOverloads() {
5506 for (BuiltinCandidateTypeSet::iterator
5507 Ptr = CandidateTypes[0].pointer_begin(),
5508 PtrEnd = CandidateTypes[0].pointer_end();
5509 Ptr != PtrEnd; ++Ptr) {
5510 QualType ParamTy = *Ptr;
5511 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5512 }
5513 }
5514
5515 // C++ [over.built]p10:
5516 // For every promoted integral type T, there exist candidate
5517 // operator functions of the form
5518 //
5519 // T operator~(T);
5520 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005521 if (!HasArithmeticOrEnumeralCandidateType)
5522 return;
5523
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005524 for (unsigned Int = FirstPromotedIntegralType;
5525 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005526 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005527 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5528 }
5529
5530 // Extension: We also add this operator for vector types.
5531 for (BuiltinCandidateTypeSet::iterator
5532 Vec = CandidateTypes[0].vector_begin(),
5533 VecEnd = CandidateTypes[0].vector_end();
5534 Vec != VecEnd; ++Vec) {
5535 QualType VecTy = *Vec;
5536 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5537 }
5538 }
5539
5540 // C++ [over.match.oper]p16:
5541 // For every pointer to member type T, there exist candidate operator
5542 // functions of the form
5543 //
5544 // bool operator==(T,T);
5545 // bool operator!=(T,T);
5546 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5547 /// Set of (canonical) types that we've already handled.
5548 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5549
5550 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5551 for (BuiltinCandidateTypeSet::iterator
5552 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5553 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5554 MemPtr != MemPtrEnd;
5555 ++MemPtr) {
5556 // Don't add the same builtin candidate twice.
5557 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5558 continue;
5559
5560 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5561 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5562 CandidateSet);
5563 }
5564 }
5565 }
5566
5567 // C++ [over.built]p15:
5568 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005569 // For every T, where T is an enumeration type, a pointer type, or
5570 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005571 //
5572 // bool operator<(T, T);
5573 // bool operator>(T, T);
5574 // bool operator<=(T, T);
5575 // bool operator>=(T, T);
5576 // bool operator==(T, T);
5577 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005578 void addRelationalPointerOrEnumeralOverloads() {
5579 // C++ [over.built]p1:
5580 // If there is a user-written candidate with the same name and parameter
5581 // types as a built-in candidate operator function, the built-in operator
5582 // function is hidden and is not included in the set of candidate
5583 // functions.
5584 //
5585 // The text is actually in a note, but if we don't implement it then we end
5586 // up with ambiguities when the user provides an overloaded operator for
5587 // an enumeration type. Note that only enumeration types have this problem,
5588 // so we track which enumeration types we've seen operators for. Also, the
5589 // only other overloaded operator with enumeration argumenst, operator=,
5590 // cannot be overloaded for enumeration types, so this is the only place
5591 // where we must suppress candidates like this.
5592 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5593 UserDefinedBinaryOperators;
5594
5595 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5596 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5597 CandidateTypes[ArgIdx].enumeration_end()) {
5598 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5599 CEnd = CandidateSet.end();
5600 C != CEnd; ++C) {
5601 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5602 continue;
5603
5604 QualType FirstParamType =
5605 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5606 QualType SecondParamType =
5607 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5608
5609 // Skip if either parameter isn't of enumeral type.
5610 if (!FirstParamType->isEnumeralType() ||
5611 !SecondParamType->isEnumeralType())
5612 continue;
5613
5614 // Add this operator to the set of known user-defined operators.
5615 UserDefinedBinaryOperators.insert(
5616 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5617 S.Context.getCanonicalType(SecondParamType)));
5618 }
5619 }
5620 }
5621
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005622 /// 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 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5628 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5629 Ptr != PtrEnd; ++Ptr) {
5630 // Don't add the same builtin candidate twice.
5631 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5632 continue;
5633
5634 QualType ParamTypes[2] = { *Ptr, *Ptr };
5635 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5636 CandidateSet);
5637 }
5638 for (BuiltinCandidateTypeSet::iterator
5639 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5640 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5641 Enum != EnumEnd; ++Enum) {
5642 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5643
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005644 // Don't add the same builtin candidate twice, or if a user defined
5645 // candidate exists.
5646 if (!AddedTypes.insert(CanonType) ||
5647 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5648 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005649 continue;
5650
5651 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005652 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5653 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005654 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005655
5656 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5657 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5658 if (AddedTypes.insert(NullPtrTy) &&
5659 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5660 NullPtrTy))) {
5661 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5662 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5663 CandidateSet);
5664 }
5665 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005666 }
5667 }
5668
5669 // C++ [over.built]p13:
5670 //
5671 // For every cv-qualified or cv-unqualified object type T
5672 // there exist candidate operator functions of the form
5673 //
5674 // T* operator+(T*, ptrdiff_t);
5675 // T& operator[](T*, ptrdiff_t); [BELOW]
5676 // T* operator-(T*, ptrdiff_t);
5677 // T* operator+(ptrdiff_t, T*);
5678 // T& operator[](ptrdiff_t, T*); [BELOW]
5679 //
5680 // C++ [over.built]p14:
5681 //
5682 // For every T, where T is a pointer to object type, there
5683 // exist candidate operator functions of the form
5684 //
5685 // ptrdiff_t operator-(T, T);
5686 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5687 /// Set of (canonical) types that we've already handled.
5688 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5689
5690 for (int Arg = 0; Arg < 2; ++Arg) {
5691 QualType AsymetricParamTypes[2] = {
5692 S.Context.getPointerDiffType(),
5693 S.Context.getPointerDiffType(),
5694 };
5695 for (BuiltinCandidateTypeSet::iterator
5696 Ptr = CandidateTypes[Arg].pointer_begin(),
5697 PtrEnd = CandidateTypes[Arg].pointer_end();
5698 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005699 QualType PointeeTy = (*Ptr)->getPointeeType();
5700 if (!PointeeTy->isObjectType())
5701 continue;
5702
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005703 AsymetricParamTypes[Arg] = *Ptr;
5704 if (Arg == 0 || Op == OO_Plus) {
5705 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5706 // T* operator+(ptrdiff_t, T*);
5707 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5708 CandidateSet);
5709 }
5710 if (Op == OO_Minus) {
5711 // ptrdiff_t operator-(T, T);
5712 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5713 continue;
5714
5715 QualType ParamTypes[2] = { *Ptr, *Ptr };
5716 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5717 Args, 2, CandidateSet);
5718 }
5719 }
5720 }
5721 }
5722
5723 // C++ [over.built]p12:
5724 //
5725 // For every pair of promoted arithmetic types L and R, there
5726 // exist candidate operator functions of the form
5727 //
5728 // LR operator*(L, R);
5729 // LR operator/(L, R);
5730 // LR operator+(L, R);
5731 // LR operator-(L, R);
5732 // bool operator<(L, R);
5733 // bool operator>(L, R);
5734 // bool operator<=(L, R);
5735 // bool operator>=(L, R);
5736 // bool operator==(L, R);
5737 // bool operator!=(L, R);
5738 //
5739 // where LR is the result of the usual arithmetic conversions
5740 // between types L and R.
5741 //
5742 // C++ [over.built]p24:
5743 //
5744 // For every pair of promoted arithmetic types L and R, there exist
5745 // candidate operator functions of the form
5746 //
5747 // LR operator?(bool, L, R);
5748 //
5749 // where LR is the result of the usual arithmetic conversions
5750 // between types L and R.
5751 // Our candidates ignore the first parameter.
5752 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005753 if (!HasArithmeticOrEnumeralCandidateType)
5754 return;
5755
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005756 for (unsigned Left = FirstPromotedArithmeticType;
5757 Left < LastPromotedArithmeticType; ++Left) {
5758 for (unsigned Right = FirstPromotedArithmeticType;
5759 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005760 QualType LandR[2] = { getArithmeticType(Left),
5761 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005762 QualType Result =
5763 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005764 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005765 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5766 }
5767 }
5768
5769 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5770 // conditional operator for vector types.
5771 for (BuiltinCandidateTypeSet::iterator
5772 Vec1 = CandidateTypes[0].vector_begin(),
5773 Vec1End = CandidateTypes[0].vector_end();
5774 Vec1 != Vec1End; ++Vec1) {
5775 for (BuiltinCandidateTypeSet::iterator
5776 Vec2 = CandidateTypes[1].vector_begin(),
5777 Vec2End = CandidateTypes[1].vector_end();
5778 Vec2 != Vec2End; ++Vec2) {
5779 QualType LandR[2] = { *Vec1, *Vec2 };
5780 QualType Result = S.Context.BoolTy;
5781 if (!isComparison) {
5782 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5783 Result = *Vec1;
5784 else
5785 Result = *Vec2;
5786 }
5787
5788 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5789 }
5790 }
5791 }
5792
5793 // C++ [over.built]p17:
5794 //
5795 // For every pair of promoted integral types L and R, there
5796 // exist candidate operator functions of the form
5797 //
5798 // LR operator%(L, R);
5799 // LR operator&(L, R);
5800 // LR operator^(L, R);
5801 // LR operator|(L, R);
5802 // L operator<<(L, R);
5803 // L operator>>(L, R);
5804 //
5805 // where LR is the result of the usual arithmetic conversions
5806 // between types L and R.
5807 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005808 if (!HasArithmeticOrEnumeralCandidateType)
5809 return;
5810
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005811 for (unsigned Left = FirstPromotedIntegralType;
5812 Left < LastPromotedIntegralType; ++Left) {
5813 for (unsigned Right = FirstPromotedIntegralType;
5814 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005815 QualType LandR[2] = { getArithmeticType(Left),
5816 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005817 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5818 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005819 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005820 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5821 }
5822 }
5823 }
5824
5825 // C++ [over.built]p20:
5826 //
5827 // For every pair (T, VQ), where T is an enumeration or
5828 // pointer to member type and VQ is either volatile or
5829 // empty, there exist candidate operator functions of the form
5830 //
5831 // VQ T& operator=(VQ T&, T);
5832 void addAssignmentMemberPointerOrEnumeralOverloads() {
5833 /// Set of (canonical) types that we've already handled.
5834 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5835
5836 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5837 for (BuiltinCandidateTypeSet::iterator
5838 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5839 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5840 Enum != EnumEnd; ++Enum) {
5841 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5842 continue;
5843
5844 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5845 CandidateSet);
5846 }
5847
5848 for (BuiltinCandidateTypeSet::iterator
5849 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5850 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5851 MemPtr != MemPtrEnd; ++MemPtr) {
5852 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5853 continue;
5854
5855 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5856 CandidateSet);
5857 }
5858 }
5859 }
5860
5861 // C++ [over.built]p19:
5862 //
5863 // For every pair (T, VQ), where T is any type and VQ is either
5864 // volatile or empty, there exist candidate operator functions
5865 // of the form
5866 //
5867 // T*VQ& operator=(T*VQ&, T*);
5868 //
5869 // C++ [over.built]p21:
5870 //
5871 // For every pair (T, VQ), where T is a cv-qualified or
5872 // cv-unqualified object type and VQ is either volatile or
5873 // empty, there exist candidate operator functions of the form
5874 //
5875 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5876 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5877 void addAssignmentPointerOverloads(bool isEqualOp) {
5878 /// Set of (canonical) types that we've already handled.
5879 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5880
5881 for (BuiltinCandidateTypeSet::iterator
5882 Ptr = CandidateTypes[0].pointer_begin(),
5883 PtrEnd = CandidateTypes[0].pointer_end();
5884 Ptr != PtrEnd; ++Ptr) {
5885 // If this is operator=, keep track of the builtin candidates we added.
5886 if (isEqualOp)
5887 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005888 else if (!(*Ptr)->getPointeeType()->isObjectType())
5889 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005890
5891 // non-volatile version
5892 QualType ParamTypes[2] = {
5893 S.Context.getLValueReferenceType(*Ptr),
5894 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5895 };
5896 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5897 /*IsAssigmentOperator=*/ isEqualOp);
5898
5899 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5900 VisibleTypeConversionsQuals.hasVolatile()) {
5901 // volatile version
5902 ParamTypes[0] =
5903 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5904 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5905 /*IsAssigmentOperator=*/isEqualOp);
5906 }
5907 }
5908
5909 if (isEqualOp) {
5910 for (BuiltinCandidateTypeSet::iterator
5911 Ptr = CandidateTypes[1].pointer_begin(),
5912 PtrEnd = CandidateTypes[1].pointer_end();
5913 Ptr != PtrEnd; ++Ptr) {
5914 // Make sure we don't add the same candidate twice.
5915 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5916 continue;
5917
Chandler Carruth8e543b32010-12-12 08:17:55 +00005918 QualType ParamTypes[2] = {
5919 S.Context.getLValueReferenceType(*Ptr),
5920 *Ptr,
5921 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005922
5923 // non-volatile version
5924 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5925 /*IsAssigmentOperator=*/true);
5926
5927 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5928 VisibleTypeConversionsQuals.hasVolatile()) {
5929 // volatile version
5930 ParamTypes[0] =
5931 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005932 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5933 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005934 }
5935 }
5936 }
5937 }
5938
5939 // C++ [over.built]p18:
5940 //
5941 // For every triple (L, VQ, R), where L is an arithmetic type,
5942 // VQ is either volatile or empty, and R is a promoted
5943 // arithmetic type, there exist candidate operator functions of
5944 // the form
5945 //
5946 // VQ L& operator=(VQ L&, R);
5947 // VQ L& operator*=(VQ L&, R);
5948 // VQ L& operator/=(VQ L&, R);
5949 // VQ L& operator+=(VQ L&, R);
5950 // VQ L& operator-=(VQ L&, R);
5951 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005952 if (!HasArithmeticOrEnumeralCandidateType)
5953 return;
5954
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005955 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5956 for (unsigned Right = FirstPromotedArithmeticType;
5957 Right < LastPromotedArithmeticType; ++Right) {
5958 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005959 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005960
5961 // Add this built-in operator as a candidate (VQ is empty).
5962 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005963 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005964 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5965 /*IsAssigmentOperator=*/isEqualOp);
5966
5967 // Add this built-in operator as a candidate (VQ is 'volatile').
5968 if (VisibleTypeConversionsQuals.hasVolatile()) {
5969 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005970 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005971 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005972 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5973 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005974 /*IsAssigmentOperator=*/isEqualOp);
5975 }
5976 }
5977 }
5978
5979 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5980 for (BuiltinCandidateTypeSet::iterator
5981 Vec1 = CandidateTypes[0].vector_begin(),
5982 Vec1End = CandidateTypes[0].vector_end();
5983 Vec1 != Vec1End; ++Vec1) {
5984 for (BuiltinCandidateTypeSet::iterator
5985 Vec2 = CandidateTypes[1].vector_begin(),
5986 Vec2End = CandidateTypes[1].vector_end();
5987 Vec2 != Vec2End; ++Vec2) {
5988 QualType ParamTypes[2];
5989 ParamTypes[1] = *Vec2;
5990 // Add this built-in operator as a candidate (VQ is empty).
5991 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5993 /*IsAssigmentOperator=*/isEqualOp);
5994
5995 // Add this built-in operator as a candidate (VQ is 'volatile').
5996 if (VisibleTypeConversionsQuals.hasVolatile()) {
5997 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5998 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005999 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6000 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006001 /*IsAssigmentOperator=*/isEqualOp);
6002 }
6003 }
6004 }
6005 }
6006
6007 // C++ [over.built]p22:
6008 //
6009 // For every triple (L, VQ, R), where L is an integral type, VQ
6010 // is either volatile or empty, and R is a promoted integral
6011 // type, there exist candidate operator functions of the form
6012 //
6013 // VQ L& operator%=(VQ L&, R);
6014 // VQ L& operator<<=(VQ L&, R);
6015 // VQ L& operator>>=(VQ L&, R);
6016 // VQ L& operator&=(VQ L&, R);
6017 // VQ L& operator^=(VQ L&, R);
6018 // VQ L& operator|=(VQ L&, R);
6019 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006020 if (!HasArithmeticOrEnumeralCandidateType)
6021 return;
6022
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006023 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6024 for (unsigned Right = FirstPromotedIntegralType;
6025 Right < LastPromotedIntegralType; ++Right) {
6026 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006027 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006028
6029 // Add this built-in operator as a candidate (VQ is empty).
6030 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006031 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006032 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6033 if (VisibleTypeConversionsQuals.hasVolatile()) {
6034 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006035 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006036 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6037 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6038 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6039 CandidateSet);
6040 }
6041 }
6042 }
6043 }
6044
6045 // C++ [over.operator]p23:
6046 //
6047 // There also exist candidate operator functions of the form
6048 //
6049 // bool operator!(bool);
6050 // bool operator&&(bool, bool);
6051 // bool operator||(bool, bool);
6052 void addExclaimOverload() {
6053 QualType ParamTy = S.Context.BoolTy;
6054 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6055 /*IsAssignmentOperator=*/false,
6056 /*NumContextualBoolArguments=*/1);
6057 }
6058 void addAmpAmpOrPipePipeOverload() {
6059 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6060 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6061 /*IsAssignmentOperator=*/false,
6062 /*NumContextualBoolArguments=*/2);
6063 }
6064
6065 // C++ [over.built]p13:
6066 //
6067 // For every cv-qualified or cv-unqualified object type T there
6068 // exist candidate operator functions of the form
6069 //
6070 // T* operator+(T*, ptrdiff_t); [ABOVE]
6071 // T& operator[](T*, ptrdiff_t);
6072 // T* operator-(T*, ptrdiff_t); [ABOVE]
6073 // T* operator+(ptrdiff_t, T*); [ABOVE]
6074 // T& operator[](ptrdiff_t, T*);
6075 void addSubscriptOverloads() {
6076 for (BuiltinCandidateTypeSet::iterator
6077 Ptr = CandidateTypes[0].pointer_begin(),
6078 PtrEnd = CandidateTypes[0].pointer_end();
6079 Ptr != PtrEnd; ++Ptr) {
6080 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6081 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006082 if (!PointeeType->isObjectType())
6083 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006084
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006085 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6086
6087 // T& operator[](T*, ptrdiff_t)
6088 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6089 }
6090
6091 for (BuiltinCandidateTypeSet::iterator
6092 Ptr = CandidateTypes[1].pointer_begin(),
6093 PtrEnd = CandidateTypes[1].pointer_end();
6094 Ptr != PtrEnd; ++Ptr) {
6095 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6096 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006097 if (!PointeeType->isObjectType())
6098 continue;
6099
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006100 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6101
6102 // T& operator[](ptrdiff_t, T*)
6103 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6104 }
6105 }
6106
6107 // C++ [over.built]p11:
6108 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6109 // C1 is the same type as C2 or is a derived class of C2, T is an object
6110 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6111 // there exist candidate operator functions of the form
6112 //
6113 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6114 //
6115 // where CV12 is the union of CV1 and CV2.
6116 void addArrowStarOverloads() {
6117 for (BuiltinCandidateTypeSet::iterator
6118 Ptr = CandidateTypes[0].pointer_begin(),
6119 PtrEnd = CandidateTypes[0].pointer_end();
6120 Ptr != PtrEnd; ++Ptr) {
6121 QualType C1Ty = (*Ptr);
6122 QualType C1;
6123 QualifierCollector Q1;
6124 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6125 if (!isa<RecordType>(C1))
6126 continue;
6127 // heuristic to reduce number of builtin candidates in the set.
6128 // Add volatile/restrict version only if there are conversions to a
6129 // volatile/restrict type.
6130 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6131 continue;
6132 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6133 continue;
6134 for (BuiltinCandidateTypeSet::iterator
6135 MemPtr = CandidateTypes[1].member_pointer_begin(),
6136 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6137 MemPtr != MemPtrEnd; ++MemPtr) {
6138 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6139 QualType C2 = QualType(mptr->getClass(), 0);
6140 C2 = C2.getUnqualifiedType();
6141 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6142 break;
6143 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6144 // build CV12 T&
6145 QualType T = mptr->getPointeeType();
6146 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6147 T.isVolatileQualified())
6148 continue;
6149 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6150 T.isRestrictQualified())
6151 continue;
6152 T = Q1.apply(S.Context, T);
6153 QualType ResultTy = S.Context.getLValueReferenceType(T);
6154 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6155 }
6156 }
6157 }
6158
6159 // Note that we don't consider the first argument, since it has been
6160 // contextually converted to bool long ago. The candidates below are
6161 // therefore added as binary.
6162 //
6163 // C++ [over.built]p25:
6164 // For every type T, where T is a pointer, pointer-to-member, or scoped
6165 // enumeration type, there exist candidate operator functions of the form
6166 //
6167 // T operator?(bool, T, T);
6168 //
6169 void addConditionalOperatorOverloads() {
6170 /// Set of (canonical) types that we've already handled.
6171 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6172
6173 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6174 for (BuiltinCandidateTypeSet::iterator
6175 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6176 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6177 Ptr != PtrEnd; ++Ptr) {
6178 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6179 continue;
6180
6181 QualType ParamTypes[2] = { *Ptr, *Ptr };
6182 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6183 }
6184
6185 for (BuiltinCandidateTypeSet::iterator
6186 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6187 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6188 MemPtr != MemPtrEnd; ++MemPtr) {
6189 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6190 continue;
6191
6192 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6193 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6194 }
6195
6196 if (S.getLangOptions().CPlusPlus0x) {
6197 for (BuiltinCandidateTypeSet::iterator
6198 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6199 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6200 Enum != EnumEnd; ++Enum) {
6201 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6202 continue;
6203
6204 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6205 continue;
6206
6207 QualType ParamTypes[2] = { *Enum, *Enum };
6208 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6209 }
6210 }
6211 }
6212 }
6213};
6214
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006215} // end anonymous namespace
6216
6217/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6218/// operator overloads to the candidate set (C++ [over.built]), based
6219/// on the operator @p Op and the arguments given. For example, if the
6220/// operator is a binary '+', this routine might add "int
6221/// operator+(int, int)" to cover integer addition.
6222void
6223Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6224 SourceLocation OpLoc,
6225 Expr **Args, unsigned NumArgs,
6226 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006227 // Find all of the types that the arguments can convert to, but only
6228 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006229 // that make use of these types. Also record whether we encounter non-record
6230 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006231 Qualifiers VisibleTypeConversionsQuals;
6232 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006233 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6234 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006235
6236 bool HasNonRecordCandidateType = false;
6237 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006238 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
6239 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6240 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6241 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6242 OpLoc,
6243 true,
6244 (Op == OO_Exclaim ||
6245 Op == OO_AmpAmp ||
6246 Op == OO_PipePipe),
6247 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006248 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6249 CandidateTypes[ArgIdx].hasNonRecordTypes();
6250 HasArithmeticOrEnumeralCandidateType =
6251 HasArithmeticOrEnumeralCandidateType ||
6252 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006253 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006254
Chandler Carruth00a38332010-12-13 01:44:01 +00006255 // Exit early when no non-record types have been added to the candidate set
6256 // for any of the arguments to the operator.
6257 if (!HasNonRecordCandidateType)
6258 return;
6259
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006260 // Setup an object to manage the common state for building overloads.
6261 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6262 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006263 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006264 CandidateTypes, CandidateSet);
6265
6266 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006267 switch (Op) {
6268 case OO_None:
6269 case NUM_OVERLOADED_OPERATORS:
6270 assert(false && "Expected an overloaded operator");
6271 break;
6272
Chandler Carruth5184de02010-12-12 08:51:33 +00006273 case OO_New:
6274 case OO_Delete:
6275 case OO_Array_New:
6276 case OO_Array_Delete:
6277 case OO_Call:
6278 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6279 break;
6280
6281 case OO_Comma:
6282 case OO_Arrow:
6283 // C++ [over.match.oper]p3:
6284 // -- For the operator ',', the unary operator '&', or the
6285 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006286 break;
6287
6288 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006289 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006290 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006291 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006292
6293 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006294 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006295 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006296 } else {
6297 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6298 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6299 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006300 break;
6301
Chandler Carruth5184de02010-12-12 08:51:33 +00006302 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006303 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006304 OpBuilder.addUnaryStarPointerOverloads();
6305 else
6306 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6307 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006308
Chandler Carruth5184de02010-12-12 08:51:33 +00006309 case OO_Slash:
6310 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006311 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006312
6313 case OO_PlusPlus:
6314 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006315 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6316 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006317 break;
6318
Douglas Gregor84605ae2009-08-24 13:43:27 +00006319 case OO_EqualEqual:
6320 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006321 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006322 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006323
Douglas Gregora11693b2008-11-12 17:17:38 +00006324 case OO_Less:
6325 case OO_Greater:
6326 case OO_LessEqual:
6327 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006328 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006329 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6330 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006331
Douglas Gregora11693b2008-11-12 17:17:38 +00006332 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006333 case OO_Caret:
6334 case OO_Pipe:
6335 case OO_LessLess:
6336 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006337 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006338 break;
6339
Chandler Carruth5184de02010-12-12 08:51:33 +00006340 case OO_Amp: // '&' is either unary or binary
6341 if (NumArgs == 1)
6342 // C++ [over.match.oper]p3:
6343 // -- For the operator ',', the unary operator '&', or the
6344 // operator '->', the built-in candidates set is empty.
6345 break;
6346
6347 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6348 break;
6349
6350 case OO_Tilde:
6351 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6352 break;
6353
Douglas Gregora11693b2008-11-12 17:17:38 +00006354 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006355 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006356 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006357
6358 case OO_PlusEqual:
6359 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006360 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006361 // Fall through.
6362
6363 case OO_StarEqual:
6364 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006365 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006366 break;
6367
6368 case OO_PercentEqual:
6369 case OO_LessLessEqual:
6370 case OO_GreaterGreaterEqual:
6371 case OO_AmpEqual:
6372 case OO_CaretEqual:
6373 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006374 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006375 break;
6376
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006377 case OO_Exclaim:
6378 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006379 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006380
Douglas Gregora11693b2008-11-12 17:17:38 +00006381 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006382 case OO_PipePipe:
6383 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006384 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006385
6386 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006387 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006388 break;
6389
6390 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006391 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006392 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006393
6394 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006395 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006396 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6397 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006398 }
6399}
6400
Douglas Gregore254f902009-02-04 00:32:51 +00006401/// \brief Add function candidates found via argument-dependent lookup
6402/// to the set of overloading candidates.
6403///
6404/// This routine performs argument-dependent name lookup based on the
6405/// given function name (which may also be an operator name) and adds
6406/// all of the overload candidates found by ADL to the overload
6407/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006408void
Douglas Gregore254f902009-02-04 00:32:51 +00006409Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006410 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006411 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006412 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006413 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006414 bool PartialOverloading,
6415 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006416 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006417
John McCall91f61fc2010-01-26 06:04:06 +00006418 // FIXME: This approach for uniquing ADL results (and removing
6419 // redundant candidates from the set) relies on pointer-equality,
6420 // which means we need to key off the canonical decl. However,
6421 // always going back to the canonical decl might not get us the
6422 // right set of default arguments. What default arguments are
6423 // we supposed to consider on ADL candidates, anyway?
6424
Douglas Gregorcabea402009-09-22 15:41:20 +00006425 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006426 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6427 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006428
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006429 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006430 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6431 CandEnd = CandidateSet.end();
6432 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006433 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006434 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006435 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006436 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006437 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006438
6439 // For each of the ADL candidates we found, add it to the overload
6440 // set.
John McCall8fe68082010-01-26 07:16:45 +00006441 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006442 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006443 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006444 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006445 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006446
John McCalla0296f72010-03-19 07:35:19 +00006447 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006448 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006449 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006450 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006451 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006452 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006453 }
Douglas Gregore254f902009-02-04 00:32:51 +00006454}
6455
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006456/// isBetterOverloadCandidate - Determines whether the first overload
6457/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006458bool
John McCall5c32be02010-08-24 20:38:10 +00006459isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006460 const OverloadCandidate &Cand1,
6461 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006462 SourceLocation Loc,
6463 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006464 // Define viable functions to be better candidates than non-viable
6465 // functions.
6466 if (!Cand2.Viable)
6467 return Cand1.Viable;
6468 else if (!Cand1.Viable)
6469 return false;
6470
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006471 // C++ [over.match.best]p1:
6472 //
6473 // -- if F is a static member function, ICS1(F) is defined such
6474 // that ICS1(F) is neither better nor worse than ICS1(G) for
6475 // any function G, and, symmetrically, ICS1(G) is neither
6476 // better nor worse than ICS1(F).
6477 unsigned StartArg = 0;
6478 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6479 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006480
Douglas Gregord3cb3562009-07-07 23:38:56 +00006481 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006482 // A viable function F1 is defined to be a better function than another
6483 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006484 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006485 unsigned NumArgs = Cand1.Conversions.size();
6486 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6487 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006488 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006489 switch (CompareImplicitConversionSequences(S,
6490 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006491 Cand2.Conversions[ArgIdx])) {
6492 case ImplicitConversionSequence::Better:
6493 // Cand1 has a better conversion sequence.
6494 HasBetterConversion = true;
6495 break;
6496
6497 case ImplicitConversionSequence::Worse:
6498 // Cand1 can't be better than Cand2.
6499 return false;
6500
6501 case ImplicitConversionSequence::Indistinguishable:
6502 // Do nothing.
6503 break;
6504 }
6505 }
6506
Mike Stump11289f42009-09-09 15:08:12 +00006507 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006508 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006509 if (HasBetterConversion)
6510 return true;
6511
Mike Stump11289f42009-09-09 15:08:12 +00006512 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006513 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006514 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006515 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6516 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006517
6518 // -- F1 and F2 are function template specializations, and the function
6519 // template for F1 is more specialized than the template for F2
6520 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006521 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006522 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006523 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006524 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006525 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6526 Cand2.Function->getPrimaryTemplate(),
6527 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006528 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006529 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006530 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006531 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006533
Douglas Gregora1f013e2008-11-07 22:36:19 +00006534 // -- the context is an initialization by user-defined conversion
6535 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6536 // from the return type of F1 to the destination type (i.e.,
6537 // the type of the entity being initialized) is a better
6538 // conversion sequence than the standard conversion sequence
6539 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006540 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006541 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006542 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006543 switch (CompareStandardConversionSequences(S,
6544 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006545 Cand2.FinalConversion)) {
6546 case ImplicitConversionSequence::Better:
6547 // Cand1 has a better conversion sequence.
6548 return true;
6549
6550 case ImplicitConversionSequence::Worse:
6551 // Cand1 can't be better than Cand2.
6552 return false;
6553
6554 case ImplicitConversionSequence::Indistinguishable:
6555 // Do nothing
6556 break;
6557 }
6558 }
6559
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006560 return false;
6561}
6562
Mike Stump11289f42009-09-09 15:08:12 +00006563/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006564/// within an overload candidate set.
6565///
6566/// \param CandidateSet the set of candidate functions.
6567///
6568/// \param Loc the location of the function name (or operator symbol) for
6569/// which overload resolution occurs.
6570///
Mike Stump11289f42009-09-09 15:08:12 +00006571/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006572/// function, Best points to the candidate function found.
6573///
6574/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006575OverloadingResult
6576OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006577 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006578 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006579 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006580 Best = end();
6581 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6582 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006583 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006584 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006585 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006586 }
6587
6588 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006589 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006590 return OR_No_Viable_Function;
6591
6592 // Make sure that this function is better than every other viable
6593 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006594 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006595 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006596 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006597 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006598 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006599 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006600 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006601 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006602 }
Mike Stump11289f42009-09-09 15:08:12 +00006603
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006604 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006605 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006606 (Best->Function->isDeleted() ||
6607 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006608 return OR_Deleted;
6609
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006610 return OR_Success;
6611}
6612
John McCall53262c92010-01-12 02:15:36 +00006613namespace {
6614
6615enum OverloadCandidateKind {
6616 oc_function,
6617 oc_method,
6618 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006619 oc_function_template,
6620 oc_method_template,
6621 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006622 oc_implicit_default_constructor,
6623 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006624 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006625 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006626 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006627 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006628};
6629
John McCalle1ac8d12010-01-13 00:25:19 +00006630OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6631 FunctionDecl *Fn,
6632 std::string &Description) {
6633 bool isTemplate = false;
6634
6635 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6636 isTemplate = true;
6637 Description = S.getTemplateArgumentBindingsText(
6638 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6639 }
John McCallfd0b2f82010-01-06 09:43:14 +00006640
6641 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006642 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006643 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006644
Sebastian Redl08905022011-02-05 19:23:19 +00006645 if (Ctor->getInheritedConstructor())
6646 return oc_implicit_inherited_constructor;
6647
Alexis Hunt119c10e2011-05-25 23:16:36 +00006648 if (Ctor->isDefaultConstructor())
6649 return oc_implicit_default_constructor;
6650
6651 if (Ctor->isMoveConstructor())
6652 return oc_implicit_move_constructor;
6653
6654 assert(Ctor->isCopyConstructor() &&
6655 "unexpected sort of implicit constructor");
6656 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006657 }
6658
6659 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6660 // This actually gets spelled 'candidate function' for now, but
6661 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006662 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006663 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006664
Alexis Hunt119c10e2011-05-25 23:16:36 +00006665 if (Meth->isMoveAssignmentOperator())
6666 return oc_implicit_move_assignment;
6667
Douglas Gregorec3bec02010-09-27 22:37:28 +00006668 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006669 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006670 return oc_implicit_copy_assignment;
6671 }
6672
John McCalle1ac8d12010-01-13 00:25:19 +00006673 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006674}
6675
Sebastian Redl08905022011-02-05 19:23:19 +00006676void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6677 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6678 if (!Ctor) return;
6679
6680 Ctor = Ctor->getInheritedConstructor();
6681 if (!Ctor) return;
6682
6683 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6684}
6685
John McCall53262c92010-01-12 02:15:36 +00006686} // end anonymous namespace
6687
6688// Notes the location of an overload candidate.
6689void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006690 std::string FnDesc;
6691 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6692 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6693 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006694 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006695}
6696
Douglas Gregorb491ed32011-02-19 21:32:49 +00006697//Notes the location of all overload candidates designated through
6698// OverloadedExpr
6699void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6700 assert(OverloadedExpr->getType() == Context.OverloadTy);
6701
6702 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6703 OverloadExpr *OvlExpr = Ovl.Expression;
6704
6705 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6706 IEnd = OvlExpr->decls_end();
6707 I != IEnd; ++I) {
6708 if (FunctionTemplateDecl *FunTmpl =
6709 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6710 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6711 } else if (FunctionDecl *Fun
6712 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6713 NoteOverloadCandidate(Fun);
6714 }
6715 }
6716}
6717
John McCall0d1da222010-01-12 00:44:57 +00006718/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6719/// "lead" diagnostic; it will be given two arguments, the source and
6720/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006721void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6722 Sema &S,
6723 SourceLocation CaretLoc,
6724 const PartialDiagnostic &PDiag) const {
6725 S.Diag(CaretLoc, PDiag)
6726 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006727 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006728 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6729 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006730 }
John McCall12f97bc2010-01-08 04:41:39 +00006731}
6732
John McCall0d1da222010-01-12 00:44:57 +00006733namespace {
6734
John McCall6a61b522010-01-13 09:16:55 +00006735void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6736 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6737 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006738 assert(Cand->Function && "for now, candidate must be a function");
6739 FunctionDecl *Fn = Cand->Function;
6740
6741 // There's a conversion slot for the object argument if this is a
6742 // non-constructor method. Note that 'I' corresponds the
6743 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006744 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006745 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006746 if (I == 0)
6747 isObjectArgument = true;
6748 else
6749 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006750 }
6751
John McCalle1ac8d12010-01-13 00:25:19 +00006752 std::string FnDesc;
6753 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6754
John McCall6a61b522010-01-13 09:16:55 +00006755 Expr *FromExpr = Conv.Bad.FromExpr;
6756 QualType FromTy = Conv.Bad.getFromType();
6757 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006758
John McCallfb7ad0f2010-02-02 02:42:52 +00006759 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006760 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006761 Expr *E = FromExpr->IgnoreParens();
6762 if (isa<UnaryOperator>(E))
6763 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006764 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006765
6766 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6767 << (unsigned) FnKind << FnDesc
6768 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6769 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006770 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006771 return;
6772 }
6773
John McCall6d174642010-01-23 08:10:49 +00006774 // Do some hand-waving analysis to see if the non-viability is due
6775 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006776 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6777 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6778 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6779 CToTy = RT->getPointeeType();
6780 else {
6781 // TODO: detect and diagnose the full richness of const mismatches.
6782 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6783 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6784 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6785 }
6786
6787 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6788 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6789 // It is dumb that we have to do this here.
6790 while (isa<ArrayType>(CFromTy))
6791 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6792 while (isa<ArrayType>(CToTy))
6793 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6794
6795 Qualifiers FromQs = CFromTy.getQualifiers();
6796 Qualifiers ToQs = CToTy.getQualifiers();
6797
6798 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6799 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6800 << (unsigned) FnKind << FnDesc
6801 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6802 << FromTy
6803 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6804 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006805 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006806 return;
6807 }
6808
John McCall31168b02011-06-15 23:02:42 +00006809 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006810 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00006811 << (unsigned) FnKind << FnDesc
6812 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6813 << FromTy
6814 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6815 << (unsigned) isObjectArgument << I+1;
6816 MaybeEmitInheritedConstructorNote(S, Fn);
6817 return;
6818 }
6819
Douglas Gregoraec25842011-04-26 23:16:46 +00006820 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6821 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6822 << (unsigned) FnKind << FnDesc
6823 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6824 << FromTy
6825 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6826 << (unsigned) isObjectArgument << I+1;
6827 MaybeEmitInheritedConstructorNote(S, Fn);
6828 return;
6829 }
6830
John McCall47000992010-01-14 03:28:57 +00006831 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6832 assert(CVR && "unexpected qualifiers mismatch");
6833
6834 if (isObjectArgument) {
6835 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6836 << (unsigned) FnKind << FnDesc
6837 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6838 << FromTy << (CVR - 1);
6839 } else {
6840 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6841 << (unsigned) FnKind << FnDesc
6842 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6843 << FromTy << (CVR - 1) << I+1;
6844 }
Sebastian Redl08905022011-02-05 19:23:19 +00006845 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006846 return;
6847 }
6848
John McCall6d174642010-01-23 08:10:49 +00006849 // Diagnose references or pointers to incomplete types differently,
6850 // since it's far from impossible that the incompleteness triggered
6851 // the failure.
6852 QualType TempFromTy = FromTy.getNonReferenceType();
6853 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6854 TempFromTy = PTy->getPointeeType();
6855 if (TempFromTy->isIncompleteType()) {
6856 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6857 << (unsigned) FnKind << FnDesc
6858 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6859 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006860 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006861 return;
6862 }
6863
Douglas Gregor56f2e342010-06-30 23:01:39 +00006864 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006865 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006866 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6867 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6868 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6869 FromPtrTy->getPointeeType()) &&
6870 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6871 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006872 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006873 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006874 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006875 }
6876 } else if (const ObjCObjectPointerType *FromPtrTy
6877 = FromTy->getAs<ObjCObjectPointerType>()) {
6878 if (const ObjCObjectPointerType *ToPtrTy
6879 = ToTy->getAs<ObjCObjectPointerType>())
6880 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6881 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6882 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6883 FromPtrTy->getPointeeType()) &&
6884 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006885 BaseToDerivedConversion = 2;
6886 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6887 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6888 !FromTy->isIncompleteType() &&
6889 !ToRefTy->getPointeeType()->isIncompleteType() &&
6890 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6891 BaseToDerivedConversion = 3;
6892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006893
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006894 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006895 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006896 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006897 << (unsigned) FnKind << FnDesc
6898 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006899 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006901 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006902 return;
6903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006904
John McCall47000992010-01-14 03:28:57 +00006905 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006906 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6907 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006908 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006909 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006910 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006911}
6912
6913void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6914 unsigned NumFormalArgs) {
6915 // TODO: treat calls to a missing default constructor as a special case
6916
6917 FunctionDecl *Fn = Cand->Function;
6918 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6919
6920 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006921
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00006922 // With invalid overloaded operators, it's possible that we think we
6923 // have an arity mismatch when it fact it looks like we have the
6924 // right number of arguments, because only overloaded operators have
6925 // the weird behavior of overloading member and non-member functions.
6926 // Just don't report anything.
6927 if (Fn->isInvalidDecl() &&
6928 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6929 return;
6930
John McCall6a61b522010-01-13 09:16:55 +00006931 // at least / at most / exactly
6932 unsigned mode, modeCount;
6933 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006934 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6935 (Cand->FailureKind == ovl_fail_bad_deduction &&
6936 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006938 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006939 mode = 0; // "at least"
6940 else
6941 mode = 2; // "exactly"
6942 modeCount = MinParams;
6943 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006944 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6945 (Cand->FailureKind == ovl_fail_bad_deduction &&
6946 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006947 if (MinParams != FnTy->getNumArgs())
6948 mode = 1; // "at most"
6949 else
6950 mode = 2; // "exactly"
6951 modeCount = FnTy->getNumArgs();
6952 }
6953
6954 std::string Description;
6955 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6956
6957 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006958 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006959 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006960 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006961}
6962
John McCall8b9ed552010-02-01 18:53:26 +00006963/// Diagnose a failed template-argument deduction.
6964void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6965 Expr **Args, unsigned NumArgs) {
6966 FunctionDecl *Fn = Cand->Function; // pattern
6967
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006968 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006969 NamedDecl *ParamD;
6970 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6971 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6972 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006973 switch (Cand->DeductionFailure.Result) {
6974 case Sema::TDK_Success:
6975 llvm_unreachable("TDK_success while diagnosing bad deduction");
6976
6977 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006978 assert(ParamD && "no parameter found for incomplete deduction result");
6979 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6980 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006981 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006982 return;
6983 }
6984
John McCall42d7d192010-08-05 09:05:08 +00006985 case Sema::TDK_Underqualified: {
6986 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6987 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6988
6989 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6990
6991 // Param will have been canonicalized, but it should just be a
6992 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006993 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006994 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006995 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006996 assert(S.Context.hasSameType(Param, NonCanonParam));
6997
6998 // Arg has also been canonicalized, but there's nothing we can do
6999 // about that. It also doesn't matter as much, because it won't
7000 // have any template parameters in it (because deduction isn't
7001 // done on dependent types).
7002 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7003
7004 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7005 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007006 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007007 return;
7008 }
7009
7010 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007011 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007012 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007013 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007014 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007015 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007016 which = 1;
7017 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007018 which = 2;
7019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007020
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007021 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007023 << *Cand->DeductionFailure.getFirstArg()
7024 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007025 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007026 return;
7027 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007028
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007029 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007030 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007031 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007032 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007033 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7034 << ParamD->getDeclName();
7035 else {
7036 int index = 0;
7037 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7038 index = TTP->getIndex();
7039 else if (NonTypeTemplateParmDecl *NTTP
7040 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7041 index = NTTP->getIndex();
7042 else
7043 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007044 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007045 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7046 << (index + 1);
7047 }
Sebastian Redl08905022011-02-05 19:23:19 +00007048 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007049 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007050
Douglas Gregor02eb4832010-05-08 18:13:28 +00007051 case Sema::TDK_TooManyArguments:
7052 case Sema::TDK_TooFewArguments:
7053 DiagnoseArityMismatch(S, Cand, NumArgs);
7054 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007055
7056 case Sema::TDK_InstantiationDepth:
7057 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007058 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007059 return;
7060
7061 case Sema::TDK_SubstitutionFailure: {
7062 std::string ArgString;
7063 if (TemplateArgumentList *Args
7064 = Cand->DeductionFailure.getTemplateArgumentList())
7065 ArgString = S.getTemplateArgumentBindingsText(
7066 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7067 *Args);
7068 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7069 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007070 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007071 return;
7072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007073
John McCall8b9ed552010-02-01 18:53:26 +00007074 // TODO: diagnose these individually, then kill off
7075 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007076 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007077 case Sema::TDK_FailedOverloadResolution:
7078 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007079 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007080 return;
7081 }
7082}
7083
7084/// Generates a 'note' diagnostic for an overload candidate. We've
7085/// already generated a primary error at the call site.
7086///
7087/// It really does need to be a single diagnostic with its caret
7088/// pointed at the candidate declaration. Yes, this creates some
7089/// major challenges of technical writing. Yes, this makes pointing
7090/// out problems with specific arguments quite awkward. It's still
7091/// better than generating twenty screens of text for every failed
7092/// overload.
7093///
7094/// It would be great to be able to express per-candidate problems
7095/// more richly for those diagnostic clients that cared, but we'd
7096/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007097void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7098 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007099 FunctionDecl *Fn = Cand->Function;
7100
John McCall12f97bc2010-01-08 04:41:39 +00007101 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007102 if (Cand->Viable && (Fn->isDeleted() ||
7103 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007104 std::string FnDesc;
7105 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007106
7107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007108 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007109 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007110 return;
John McCall12f97bc2010-01-08 04:41:39 +00007111 }
7112
John McCalle1ac8d12010-01-13 00:25:19 +00007113 // We don't really have anything else to say about viable candidates.
7114 if (Cand->Viable) {
7115 S.NoteOverloadCandidate(Fn);
7116 return;
7117 }
John McCall0d1da222010-01-12 00:44:57 +00007118
John McCall6a61b522010-01-13 09:16:55 +00007119 switch (Cand->FailureKind) {
7120 case ovl_fail_too_many_arguments:
7121 case ovl_fail_too_few_arguments:
7122 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007123
John McCall6a61b522010-01-13 09:16:55 +00007124 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007125 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7126
John McCallfe796dd2010-01-23 05:17:32 +00007127 case ovl_fail_trivial_conversion:
7128 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007129 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007130 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007131
John McCall65eb8792010-02-25 01:37:24 +00007132 case ovl_fail_bad_conversion: {
7133 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7134 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007135 if (Cand->Conversions[I].isBad())
7136 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007137
John McCall6a61b522010-01-13 09:16:55 +00007138 // FIXME: this currently happens when we're called from SemaInit
7139 // when user-conversion overload fails. Figure out how to handle
7140 // those conditions and diagnose them well.
7141 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007142 }
John McCall65eb8792010-02-25 01:37:24 +00007143 }
John McCalld3224162010-01-08 00:58:21 +00007144}
7145
7146void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7147 // Desugar the type of the surrogate down to a function type,
7148 // retaining as many typedefs as possible while still showing
7149 // the function type (and, therefore, its parameter types).
7150 QualType FnType = Cand->Surrogate->getConversionType();
7151 bool isLValueReference = false;
7152 bool isRValueReference = false;
7153 bool isPointer = false;
7154 if (const LValueReferenceType *FnTypeRef =
7155 FnType->getAs<LValueReferenceType>()) {
7156 FnType = FnTypeRef->getPointeeType();
7157 isLValueReference = true;
7158 } else if (const RValueReferenceType *FnTypeRef =
7159 FnType->getAs<RValueReferenceType>()) {
7160 FnType = FnTypeRef->getPointeeType();
7161 isRValueReference = true;
7162 }
7163 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7164 FnType = FnTypePtr->getPointeeType();
7165 isPointer = true;
7166 }
7167 // Desugar down to a function type.
7168 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7169 // Reconstruct the pointer/reference as appropriate.
7170 if (isPointer) FnType = S.Context.getPointerType(FnType);
7171 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7172 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7173
7174 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7175 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007176 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007177}
7178
7179void NoteBuiltinOperatorCandidate(Sema &S,
7180 const char *Opc,
7181 SourceLocation OpLoc,
7182 OverloadCandidate *Cand) {
7183 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7184 std::string TypeStr("operator");
7185 TypeStr += Opc;
7186 TypeStr += "(";
7187 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7188 if (Cand->Conversions.size() == 1) {
7189 TypeStr += ")";
7190 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7191 } else {
7192 TypeStr += ", ";
7193 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7194 TypeStr += ")";
7195 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7196 }
7197}
7198
7199void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7200 OverloadCandidate *Cand) {
7201 unsigned NoOperands = Cand->Conversions.size();
7202 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7203 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007204 if (ICS.isBad()) break; // all meaningless after first invalid
7205 if (!ICS.isAmbiguous()) continue;
7206
John McCall5c32be02010-08-24 20:38:10 +00007207 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007208 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007209 }
7210}
7211
John McCall3712d9e2010-01-15 23:32:50 +00007212SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7213 if (Cand->Function)
7214 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007215 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007216 return Cand->Surrogate->getLocation();
7217 return SourceLocation();
7218}
7219
John McCallad2587a2010-01-12 00:48:53 +00007220struct CompareOverloadCandidatesForDisplay {
7221 Sema &S;
7222 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007223
7224 bool operator()(const OverloadCandidate *L,
7225 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007226 // Fast-path this check.
7227 if (L == R) return false;
7228
John McCall12f97bc2010-01-08 04:41:39 +00007229 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007230 if (L->Viable) {
7231 if (!R->Viable) return true;
7232
7233 // TODO: introduce a tri-valued comparison for overload
7234 // candidates. Would be more worthwhile if we had a sort
7235 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007236 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7237 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007238 } else if (R->Viable)
7239 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007240
John McCall3712d9e2010-01-15 23:32:50 +00007241 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007242
John McCall3712d9e2010-01-15 23:32:50 +00007243 // Criteria by which we can sort non-viable candidates:
7244 if (!L->Viable) {
7245 // 1. Arity mismatches come after other candidates.
7246 if (L->FailureKind == ovl_fail_too_many_arguments ||
7247 L->FailureKind == ovl_fail_too_few_arguments)
7248 return false;
7249 if (R->FailureKind == ovl_fail_too_many_arguments ||
7250 R->FailureKind == ovl_fail_too_few_arguments)
7251 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007252
John McCallfe796dd2010-01-23 05:17:32 +00007253 // 2. Bad conversions come first and are ordered by the number
7254 // of bad conversions and quality of good conversions.
7255 if (L->FailureKind == ovl_fail_bad_conversion) {
7256 if (R->FailureKind != ovl_fail_bad_conversion)
7257 return true;
7258
7259 // If there's any ordering between the defined conversions...
7260 // FIXME: this might not be transitive.
7261 assert(L->Conversions.size() == R->Conversions.size());
7262
7263 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007264 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7265 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007266 switch (CompareImplicitConversionSequences(S,
7267 L->Conversions[I],
7268 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007269 case ImplicitConversionSequence::Better:
7270 leftBetter++;
7271 break;
7272
7273 case ImplicitConversionSequence::Worse:
7274 leftBetter--;
7275 break;
7276
7277 case ImplicitConversionSequence::Indistinguishable:
7278 break;
7279 }
7280 }
7281 if (leftBetter > 0) return true;
7282 if (leftBetter < 0) return false;
7283
7284 } else if (R->FailureKind == ovl_fail_bad_conversion)
7285 return false;
7286
John McCall3712d9e2010-01-15 23:32:50 +00007287 // TODO: others?
7288 }
7289
7290 // Sort everything else by location.
7291 SourceLocation LLoc = GetLocationForCandidate(L);
7292 SourceLocation RLoc = GetLocationForCandidate(R);
7293
7294 // Put candidates without locations (e.g. builtins) at the end.
7295 if (LLoc.isInvalid()) return false;
7296 if (RLoc.isInvalid()) return true;
7297
7298 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007299 }
7300};
7301
John McCallfe796dd2010-01-23 05:17:32 +00007302/// CompleteNonViableCandidate - Normally, overload resolution only
7303/// computes up to the first
7304void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7305 Expr **Args, unsigned NumArgs) {
7306 assert(!Cand->Viable);
7307
7308 // Don't do anything on failures other than bad conversion.
7309 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7310
7311 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007312 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007313 unsigned ConvCount = Cand->Conversions.size();
7314 while (true) {
7315 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7316 ConvIdx++;
7317 if (Cand->Conversions[ConvIdx - 1].isBad())
7318 break;
7319 }
7320
7321 if (ConvIdx == ConvCount)
7322 return;
7323
John McCall65eb8792010-02-25 01:37:24 +00007324 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7325 "remaining conversion is initialized?");
7326
Douglas Gregoradc7a702010-04-16 17:45:54 +00007327 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007328 // operation somehow.
7329 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007330
7331 const FunctionProtoType* Proto;
7332 unsigned ArgIdx = ConvIdx;
7333
7334 if (Cand->IsSurrogate) {
7335 QualType ConvType
7336 = Cand->Surrogate->getConversionType().getNonReferenceType();
7337 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7338 ConvType = ConvPtrType->getPointeeType();
7339 Proto = ConvType->getAs<FunctionProtoType>();
7340 ArgIdx--;
7341 } else if (Cand->Function) {
7342 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7343 if (isa<CXXMethodDecl>(Cand->Function) &&
7344 !isa<CXXConstructorDecl>(Cand->Function))
7345 ArgIdx--;
7346 } else {
7347 // Builtin binary operator with a bad first conversion.
7348 assert(ConvCount <= 3);
7349 for (; ConvIdx != ConvCount; ++ConvIdx)
7350 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007351 = TryCopyInitialization(S, Args[ConvIdx],
7352 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007353 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007354 /*InOverloadResolution*/ true,
7355 /*AllowObjCWritebackConversion=*/
7356 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007357 return;
7358 }
7359
7360 // Fill in the rest of the conversions.
7361 unsigned NumArgsInProto = Proto->getNumArgs();
7362 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7363 if (ArgIdx < NumArgsInProto)
7364 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007365 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007366 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007367 /*InOverloadResolution=*/true,
7368 /*AllowObjCWritebackConversion=*/
7369 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007370 else
7371 Cand->Conversions[ConvIdx].setEllipsis();
7372 }
7373}
7374
John McCalld3224162010-01-08 00:58:21 +00007375} // end anonymous namespace
7376
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007377/// PrintOverloadCandidates - When overload resolution fails, prints
7378/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007379/// set.
John McCall5c32be02010-08-24 20:38:10 +00007380void OverloadCandidateSet::NoteCandidates(Sema &S,
7381 OverloadCandidateDisplayKind OCD,
7382 Expr **Args, unsigned NumArgs,
7383 const char *Opc,
7384 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007385 // Sort the candidates by viability and position. Sorting directly would
7386 // be prohibitive, so we make a set of pointers and sort those.
7387 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007388 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7389 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007390 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007391 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007392 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007393 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007394 if (Cand->Function || Cand->IsSurrogate)
7395 Cands.push_back(Cand);
7396 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7397 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007398 }
7399 }
7400
John McCallad2587a2010-01-12 00:48:53 +00007401 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007402 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007403
John McCall0d1da222010-01-12 00:44:57 +00007404 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007405
John McCall12f97bc2010-01-08 04:41:39 +00007406 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007407 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007408 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007409 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7410 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007411
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007412 // Set an arbitrary limit on the number of candidate functions we'll spam
7413 // the user with. FIXME: This limit should depend on details of the
7414 // candidate list.
7415 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7416 break;
7417 }
7418 ++CandsShown;
7419
John McCalld3224162010-01-08 00:58:21 +00007420 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007421 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007422 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007423 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007424 else {
7425 assert(Cand->Viable &&
7426 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007427 // Generally we only see ambiguities including viable builtin
7428 // operators if overload resolution got screwed up by an
7429 // ambiguous user-defined conversion.
7430 //
7431 // FIXME: It's quite possible for different conversions to see
7432 // different ambiguities, though.
7433 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007434 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007435 ReportedAmbiguousConversions = true;
7436 }
John McCalld3224162010-01-08 00:58:21 +00007437
John McCall0d1da222010-01-12 00:44:57 +00007438 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007439 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007440 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007441 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007442
7443 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007444 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007445}
7446
Douglas Gregorb491ed32011-02-19 21:32:49 +00007447// [PossiblyAFunctionType] --> [Return]
7448// NonFunctionType --> NonFunctionType
7449// R (A) --> R(A)
7450// R (*)(A) --> R (A)
7451// R (&)(A) --> R (A)
7452// R (S::*)(A) --> R (A)
7453QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7454 QualType Ret = PossiblyAFunctionType;
7455 if (const PointerType *ToTypePtr =
7456 PossiblyAFunctionType->getAs<PointerType>())
7457 Ret = ToTypePtr->getPointeeType();
7458 else if (const ReferenceType *ToTypeRef =
7459 PossiblyAFunctionType->getAs<ReferenceType>())
7460 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007461 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007462 PossiblyAFunctionType->getAs<MemberPointerType>())
7463 Ret = MemTypePtr->getPointeeType();
7464 Ret =
7465 Context.getCanonicalType(Ret).getUnqualifiedType();
7466 return Ret;
7467}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007468
Douglas Gregorb491ed32011-02-19 21:32:49 +00007469// A helper class to help with address of function resolution
7470// - allows us to avoid passing around all those ugly parameters
7471class AddressOfFunctionResolver
7472{
7473 Sema& S;
7474 Expr* SourceExpr;
7475 const QualType& TargetType;
7476 QualType TargetFunctionType; // Extracted function type from target type
7477
7478 bool Complain;
7479 //DeclAccessPair& ResultFunctionAccessPair;
7480 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007481
Douglas Gregorb491ed32011-02-19 21:32:49 +00007482 bool TargetTypeIsNonStaticMemberFunction;
7483 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007484
Douglas Gregorb491ed32011-02-19 21:32:49 +00007485 OverloadExpr::FindResult OvlExprInfo;
7486 OverloadExpr *OvlExpr;
7487 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007488 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007489
Douglas Gregorb491ed32011-02-19 21:32:49 +00007490public:
7491 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7492 const QualType& TargetType, bool Complain)
7493 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7494 Complain(Complain), Context(S.getASTContext()),
7495 TargetTypeIsNonStaticMemberFunction(
7496 !!TargetType->getAs<MemberPointerType>()),
7497 FoundNonTemplateFunction(false),
7498 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7499 OvlExpr(OvlExprInfo.Expression)
7500 {
7501 ExtractUnqualifiedFunctionTypeFromTargetType();
7502
7503 if (!TargetFunctionType->isFunctionType()) {
7504 if (OvlExpr->hasExplicitTemplateArgs()) {
7505 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007506 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007507 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007508
7509 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7510 if (!Method->isStatic()) {
7511 // If the target type is a non-function type and the function
7512 // found is a non-static member function, pretend as if that was
7513 // the target, it's the only possible type to end up with.
7514 TargetTypeIsNonStaticMemberFunction = true;
7515
7516 // And skip adding the function if its not in the proper form.
7517 // We'll diagnose this due to an empty set of functions.
7518 if (!OvlExprInfo.HasFormOfMemberPointer)
7519 return;
7520 }
7521 }
7522
Douglas Gregorb491ed32011-02-19 21:32:49 +00007523 Matches.push_back(std::make_pair(dap,Fn));
7524 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007525 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007526 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007527 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007528
7529 if (OvlExpr->hasExplicitTemplateArgs())
7530 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007531
Douglas Gregorb491ed32011-02-19 21:32:49 +00007532 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7533 // C++ [over.over]p4:
7534 // If more than one function is selected, [...]
7535 if (Matches.size() > 1) {
7536 if (FoundNonTemplateFunction)
7537 EliminateAllTemplateMatches();
7538 else
7539 EliminateAllExceptMostSpecializedTemplate();
7540 }
7541 }
7542 }
7543
7544private:
7545 bool isTargetTypeAFunction() const {
7546 return TargetFunctionType->isFunctionType();
7547 }
7548
7549 // [ToType] [Return]
7550
7551 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7552 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7553 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7554 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7555 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7556 }
7557
7558 // return true if any matching specializations were found
7559 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7560 const DeclAccessPair& CurAccessFunPair) {
7561 if (CXXMethodDecl *Method
7562 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7563 // Skip non-static function templates when converting to pointer, and
7564 // static when converting to member pointer.
7565 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7566 return false;
7567 }
7568 else if (TargetTypeIsNonStaticMemberFunction)
7569 return false;
7570
7571 // C++ [over.over]p2:
7572 // If the name is a function template, template argument deduction is
7573 // done (14.8.2.2), and if the argument deduction succeeds, the
7574 // resulting template argument list is used to generate a single
7575 // function template specialization, which is added to the set of
7576 // overloaded functions considered.
7577 FunctionDecl *Specialization = 0;
7578 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7579 if (Sema::TemplateDeductionResult Result
7580 = S.DeduceTemplateArguments(FunctionTemplate,
7581 &OvlExplicitTemplateArgs,
7582 TargetFunctionType, Specialization,
7583 Info)) {
7584 // FIXME: make a note of the failed deduction for diagnostics.
7585 (void)Result;
7586 return false;
7587 }
7588
7589 // Template argument deduction ensures that we have an exact match.
7590 // This function template specicalization works.
7591 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7592 assert(TargetFunctionType
7593 == Context.getCanonicalType(Specialization->getType()));
7594 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7595 return true;
7596 }
7597
7598 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7599 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007600 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007601 // Skip non-static functions when converting to pointer, and static
7602 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007603 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7604 return false;
7605 }
7606 else if (TargetTypeIsNonStaticMemberFunction)
7607 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007608
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007609 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007610 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007611 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7612 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00007613 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7614 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007615 Matches.push_back(std::make_pair(CurAccessFunPair,
7616 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007617 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007618 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007619 }
Mike Stump11289f42009-09-09 15:08:12 +00007620 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007621
7622 return false;
7623 }
7624
7625 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7626 bool Ret = false;
7627
7628 // If the overload expression doesn't have the form of a pointer to
7629 // member, don't try to convert it to a pointer-to-member type.
7630 if (IsInvalidFormOfPointerToMemberFunction())
7631 return false;
7632
7633 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7634 E = OvlExpr->decls_end();
7635 I != E; ++I) {
7636 // Look through any using declarations to find the underlying function.
7637 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7638
7639 // C++ [over.over]p3:
7640 // Non-member functions and static member functions match
7641 // targets of type "pointer-to-function" or "reference-to-function."
7642 // Nonstatic member functions match targets of
7643 // type "pointer-to-member-function."
7644 // Note that according to DR 247, the containing class does not matter.
7645 if (FunctionTemplateDecl *FunctionTemplate
7646 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7647 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7648 Ret = true;
7649 }
7650 // If we have explicit template arguments supplied, skip non-templates.
7651 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7652 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7653 Ret = true;
7654 }
7655 assert(Ret || Matches.empty());
7656 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007657 }
7658
Douglas Gregorb491ed32011-02-19 21:32:49 +00007659 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007660 // [...] and any given function template specialization F1 is
7661 // eliminated if the set contains a second function template
7662 // specialization whose function template is more specialized
7663 // than the function template of F1 according to the partial
7664 // ordering rules of 14.5.5.2.
7665
7666 // The algorithm specified above is quadratic. We instead use a
7667 // two-pass algorithm (similar to the one used to identify the
7668 // best viable function in an overload set) that identifies the
7669 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007670
7671 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7672 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7673 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007674
John McCall58cc69d2010-01-27 01:50:18 +00007675 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007676 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7677 TPOC_Other, 0, SourceExpr->getLocStart(),
7678 S.PDiag(),
7679 S.PDiag(diag::err_addr_ovl_ambiguous)
7680 << Matches[0].second->getDeclName(),
7681 S.PDiag(diag::note_ovl_candidate)
7682 << (unsigned) oc_function_template,
7683 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007684
Douglas Gregorb491ed32011-02-19 21:32:49 +00007685 if (Result != MatchesCopy.end()) {
7686 // Make it the first and only element
7687 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7688 Matches[0].second = cast<FunctionDecl>(*Result);
7689 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007690 }
7691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007692
Douglas Gregorb491ed32011-02-19 21:32:49 +00007693 void EliminateAllTemplateMatches() {
7694 // [...] any function template specializations in the set are
7695 // eliminated if the set also contains a non-template function, [...]
7696 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7697 if (Matches[I].second->getPrimaryTemplate() == 0)
7698 ++I;
7699 else {
7700 Matches[I] = Matches[--N];
7701 Matches.set_size(N);
7702 }
7703 }
7704 }
7705
7706public:
7707 void ComplainNoMatchesFound() const {
7708 assert(Matches.empty());
7709 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7710 << OvlExpr->getName() << TargetFunctionType
7711 << OvlExpr->getSourceRange();
7712 S.NoteAllOverloadCandidates(OvlExpr);
7713 }
7714
7715 bool IsInvalidFormOfPointerToMemberFunction() const {
7716 return TargetTypeIsNonStaticMemberFunction &&
7717 !OvlExprInfo.HasFormOfMemberPointer;
7718 }
7719
7720 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7721 // TODO: Should we condition this on whether any functions might
7722 // have matched, or is it more appropriate to do that in callers?
7723 // TODO: a fixit wouldn't hurt.
7724 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7725 << TargetType << OvlExpr->getSourceRange();
7726 }
7727
7728 void ComplainOfInvalidConversion() const {
7729 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7730 << OvlExpr->getName() << TargetType;
7731 }
7732
7733 void ComplainMultipleMatchesFound() const {
7734 assert(Matches.size() > 1);
7735 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7736 << OvlExpr->getName()
7737 << OvlExpr->getSourceRange();
7738 S.NoteAllOverloadCandidates(OvlExpr);
7739 }
7740
7741 int getNumMatches() const { return Matches.size(); }
7742
7743 FunctionDecl* getMatchingFunctionDecl() const {
7744 if (Matches.size() != 1) return 0;
7745 return Matches[0].second;
7746 }
7747
7748 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7749 if (Matches.size() != 1) return 0;
7750 return &Matches[0].first;
7751 }
7752};
7753
7754/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7755/// an overloaded function (C++ [over.over]), where @p From is an
7756/// expression with overloaded function type and @p ToType is the type
7757/// we're trying to resolve to. For example:
7758///
7759/// @code
7760/// int f(double);
7761/// int f(int);
7762///
7763/// int (*pfd)(double) = f; // selects f(double)
7764/// @endcode
7765///
7766/// This routine returns the resulting FunctionDecl if it could be
7767/// resolved, and NULL otherwise. When @p Complain is true, this
7768/// routine will emit diagnostics if there is an error.
7769FunctionDecl *
7770Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7771 bool Complain,
7772 DeclAccessPair &FoundResult) {
7773
7774 assert(AddressOfExpr->getType() == Context.OverloadTy);
7775
7776 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7777 int NumMatches = Resolver.getNumMatches();
7778 FunctionDecl* Fn = 0;
7779 if ( NumMatches == 0 && Complain) {
7780 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7781 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7782 else
7783 Resolver.ComplainNoMatchesFound();
7784 }
7785 else if (NumMatches > 1 && Complain)
7786 Resolver.ComplainMultipleMatchesFound();
7787 else if (NumMatches == 1) {
7788 Fn = Resolver.getMatchingFunctionDecl();
7789 assert(Fn);
7790 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7791 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007792 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007793 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007794 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007795
7796 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007797}
7798
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007799/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007800/// resolve that overloaded function expression down to a single function.
7801///
7802/// This routine can only resolve template-ids that refer to a single function
7803/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007804/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007805/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00007806FunctionDecl *
7807Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7808 bool Complain,
7809 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007810 // C++ [over.over]p1:
7811 // [...] [Note: any redundant set of parentheses surrounding the
7812 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007813 // C++ [over.over]p1:
7814 // [...] The overloaded function name can be preceded by the &
7815 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007816
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007817 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00007818 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007819 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007820
7821 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00007822 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007823
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007824 // Look through all of the overloaded functions, searching for one
7825 // whose type matches exactly.
7826 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007827 for (UnresolvedSetIterator I = ovl->decls_begin(),
7828 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007829 // C++0x [temp.arg.explicit]p3:
7830 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007831 // where deduction is not done, if a template argument list is
7832 // specified and it, along with any default template arguments,
7833 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007834 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007835 FunctionTemplateDecl *FunctionTemplate
7836 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007837
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007838 // C++ [over.over]p2:
7839 // If the name is a function template, template argument deduction is
7840 // done (14.8.2.2), and if the argument deduction succeeds, the
7841 // resulting template argument list is used to generate a single
7842 // function template specialization, which is added to the set of
7843 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007844 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007845 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007846 if (TemplateDeductionResult Result
7847 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7848 Specialization, Info)) {
7849 // FIXME: make a note of the failed deduction for diagnostics.
7850 (void)Result;
7851 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007852 }
7853
John McCall0009fcc2011-04-26 20:42:42 +00007854 assert(Specialization && "no specialization and no error?");
7855
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007856 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007857 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007858 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00007859 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7860 << ovl->getName();
7861 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007862 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007863 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00007864 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007865
John McCall0009fcc2011-04-26 20:42:42 +00007866 Matched = Specialization;
7867 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007869
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007870 return Matched;
7871}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007872
Douglas Gregor1beec452011-03-12 01:48:56 +00007873
7874
7875
7876// Resolve and fix an overloaded expression that
7877// can be resolved because it identifies a single function
7878// template specialization
7879// Last three arguments should only be supplied if Complain = true
7880ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00007881 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00007882 const SourceRange& OpRangeForComplaining,
7883 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00007884 unsigned DiagIDForComplaining) {
7885 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00007886
John McCall0009fcc2011-04-26 20:42:42 +00007887 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00007888
John McCall0009fcc2011-04-26 20:42:42 +00007889 DeclAccessPair found;
7890 ExprResult SingleFunctionExpression;
7891 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7892 ovl.Expression, /*complain*/ false, &found)) {
7893 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7894 return ExprError();
7895
7896 // It is only correct to resolve to an instance method if we're
7897 // resolving a form that's permitted to be a pointer to member.
7898 // Otherwise we'll end up making a bound member expression, which
7899 // is illegal in all the contexts we resolve like this.
7900 if (!ovl.HasFormOfMemberPointer &&
7901 isa<CXXMethodDecl>(fn) &&
7902 cast<CXXMethodDecl>(fn)->isInstance()) {
7903 if (complain) {
7904 Diag(ovl.Expression->getExprLoc(),
7905 diag::err_invalid_use_of_bound_member_func)
7906 << ovl.Expression->getSourceRange();
7907 // TODO: I believe we only end up here if there's a mix of
7908 // static and non-static candidates (otherwise the expression
7909 // would have 'bound member' type, not 'overload' type).
7910 // Ideally we would note which candidate was chosen and why
7911 // the static candidates were rejected.
7912 }
7913
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007914 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00007915 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007916
John McCall0009fcc2011-04-26 20:42:42 +00007917 // Fix the expresion to refer to 'fn'.
7918 SingleFunctionExpression =
7919 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7920
7921 // If desired, do function-to-pointer decay.
7922 if (doFunctionPointerConverion)
7923 SingleFunctionExpression =
7924 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7925 }
7926
7927 if (!SingleFunctionExpression.isUsable()) {
7928 if (complain) {
7929 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7930 << ovl.Expression->getName()
7931 << DestTypeForComplaining
7932 << OpRangeForComplaining
7933 << ovl.Expression->getQualifierLoc().getSourceRange();
7934 NoteAllOverloadCandidates(SrcExpr);
7935 }
7936 return ExprError();
7937 }
7938
7939 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00007940}
7941
Douglas Gregorcabea402009-09-22 15:41:20 +00007942/// \brief Add a single candidate to the overload set.
7943static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007944 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007945 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007946 Expr **Args, unsigned NumArgs,
7947 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00007948 bool PartialOverloading,
7949 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00007950 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007951 if (isa<UsingShadowDecl>(Callee))
7952 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7953
Douglas Gregorcabea402009-09-22 15:41:20 +00007954 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00007955 if (ExplicitTemplateArgs) {
7956 assert(!KnownValid && "Explicit template arguments?");
7957 return;
7958 }
John McCalla0296f72010-03-19 07:35:19 +00007959 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007960 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007961 return;
John McCalld14a8642009-11-21 08:51:07 +00007962 }
7963
7964 if (FunctionTemplateDecl *FuncTemplate
7965 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007966 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7967 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007968 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007969 return;
7970 }
7971
Richard Smith95ce4f62011-06-26 22:19:54 +00007972 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00007973}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007974
Douglas Gregorcabea402009-09-22 15:41:20 +00007975/// \brief Add the overload candidates named by callee and/or found by argument
7976/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007977void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007978 Expr **Args, unsigned NumArgs,
7979 OverloadCandidateSet &CandidateSet,
7980 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007981
7982#ifndef NDEBUG
7983 // Verify that ArgumentDependentLookup is consistent with the rules
7984 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007985 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007986 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7987 // and let Y be the lookup set produced by argument dependent
7988 // lookup (defined as follows). If X contains
7989 //
7990 // -- a declaration of a class member, or
7991 //
7992 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007993 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007994 //
7995 // -- a declaration that is neither a function or a function
7996 // template
7997 //
7998 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007999
John McCall57500772009-12-16 12:17:52 +00008000 if (ULE->requiresADL()) {
8001 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8002 E = ULE->decls_end(); I != E; ++I) {
8003 assert(!(*I)->getDeclContext()->isRecord());
8004 assert(isa<UsingShadowDecl>(*I) ||
8005 !(*I)->getDeclContext()->isFunctionOrMethod());
8006 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008007 }
8008 }
8009#endif
8010
John McCall57500772009-12-16 12:17:52 +00008011 // It would be nice to avoid this copy.
8012 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008013 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008014 if (ULE->hasExplicitTemplateArgs()) {
8015 ULE->copyTemplateArgumentsInto(TABuffer);
8016 ExplicitTemplateArgs = &TABuffer;
8017 }
8018
8019 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8020 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008021 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008022 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008023 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008024
John McCall57500772009-12-16 12:17:52 +00008025 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008026 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8027 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008028 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008029 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008030 PartialOverloading,
8031 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008032}
John McCalld681c392009-12-16 08:11:27 +00008033
Richard Smith998a5912011-06-05 22:42:48 +00008034/// Attempt to recover from an ill-formed use of a non-dependent name in a
8035/// template, where the non-dependent name was declared after the template
8036/// was defined. This is common in code written for a compilers which do not
8037/// correctly implement two-stage name lookup.
8038///
8039/// Returns true if a viable candidate was found and a diagnostic was issued.
8040static bool
8041DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8042 const CXXScopeSpec &SS, LookupResult &R,
8043 TemplateArgumentListInfo *ExplicitTemplateArgs,
8044 Expr **Args, unsigned NumArgs) {
8045 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8046 return false;
8047
8048 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8049 SemaRef.LookupQualifiedName(R, DC);
8050
8051 if (!R.empty()) {
8052 R.suppressDiagnostics();
8053
8054 if (isa<CXXRecordDecl>(DC)) {
8055 // Don't diagnose names we find in classes; we get much better
8056 // diagnostics for these from DiagnoseEmptyLookup.
8057 R.clear();
8058 return false;
8059 }
8060
8061 OverloadCandidateSet Candidates(FnLoc);
8062 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8063 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8064 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008065 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008066
8067 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008068 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008069 // No viable functions. Don't bother the user with notes for functions
8070 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008071 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008072 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008073 }
Richard Smith998a5912011-06-05 22:42:48 +00008074
8075 // Find the namespaces where ADL would have looked, and suggest
8076 // declaring the function there instead.
8077 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8078 Sema::AssociatedClassSet AssociatedClasses;
8079 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8080 AssociatedNamespaces,
8081 AssociatedClasses);
8082 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008083 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008084 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008085 for (Sema::AssociatedNamespaceSet::iterator
8086 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008087 end = AssociatedNamespaces.end(); it != end; ++it) {
8088 if (!Std->Encloses(*it))
8089 SuggestedNamespaces.insert(*it);
8090 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008091 } else {
8092 // Lacking the 'std::' namespace, use all of the associated namespaces.
8093 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008094 }
8095
8096 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8097 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008098 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008099 SemaRef.Diag(Best->Function->getLocation(),
8100 diag::note_not_found_by_two_phase_lookup)
8101 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008102 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008103 SemaRef.Diag(Best->Function->getLocation(),
8104 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008105 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008106 } else {
8107 // FIXME: It would be useful to list the associated namespaces here,
8108 // but the diagnostics infrastructure doesn't provide a way to produce
8109 // a localized representation of a list of items.
8110 SemaRef.Diag(Best->Function->getLocation(),
8111 diag::note_not_found_by_two_phase_lookup)
8112 << R.getLookupName() << 2;
8113 }
8114
8115 // Try to recover by calling this function.
8116 return true;
8117 }
8118
8119 R.clear();
8120 }
8121
8122 return false;
8123}
8124
8125/// Attempt to recover from ill-formed use of a non-dependent operator in a
8126/// template, where the non-dependent operator was declared after the template
8127/// was defined.
8128///
8129/// Returns true if a viable candidate was found and a diagnostic was issued.
8130static bool
8131DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8132 SourceLocation OpLoc,
8133 Expr **Args, unsigned NumArgs) {
8134 DeclarationName OpName =
8135 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8136 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8137 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8138 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8139}
8140
John McCalld681c392009-12-16 08:11:27 +00008141/// Attempts to recover from a call where no functions were found.
8142///
8143/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008144static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008145BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008146 UnresolvedLookupExpr *ULE,
8147 SourceLocation LParenLoc,
8148 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008149 SourceLocation RParenLoc,
8150 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008151
8152 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008153 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008154
John McCall57500772009-12-16 12:17:52 +00008155 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008156 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008157 if (ULE->hasExplicitTemplateArgs()) {
8158 ULE->copyTemplateArgumentsInto(TABuffer);
8159 ExplicitTemplateArgs = &TABuffer;
8160 }
8161
John McCalld681c392009-12-16 08:11:27 +00008162 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8163 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008164 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8165 ExplicitTemplateArgs, Args, NumArgs) &&
8166 (!EmptyLookup ||
8167 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression)))
John McCallfaf5fb42010-08-26 23:41:50 +00008168 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008169
John McCall57500772009-12-16 12:17:52 +00008170 assert(!R.empty() && "lookup results empty despite recovery");
8171
8172 // Build an implicit member call if appropriate. Just drop the
8173 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008174 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008175 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008176 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8177 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008178 else if (ExplicitTemplateArgs)
8179 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8180 else
8181 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8182
8183 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008184 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008185
8186 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008187 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008188 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008189 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008190 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008191}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008192
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008193/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008194/// (which eventually refers to the declaration Func) and the call
8195/// arguments Args/NumArgs, attempt to resolve the function call down
8196/// to a specific function. If overload resolution succeeds, returns
8197/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008198/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008199/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008200ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008201Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008202 SourceLocation LParenLoc,
8203 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008204 SourceLocation RParenLoc,
8205 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008206#ifndef NDEBUG
8207 if (ULE->requiresADL()) {
8208 // To do ADL, we must have found an unqualified name.
8209 assert(!ULE->getQualifier() && "qualified name with ADL");
8210
8211 // We don't perform ADL for implicit declarations of builtins.
8212 // Verify that this was correctly set up.
8213 FunctionDecl *F;
8214 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8215 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8216 F->getBuiltinID() && F->isImplicit())
8217 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008218
John McCall57500772009-12-16 12:17:52 +00008219 // We don't perform ADL in C.
8220 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008221 } else
8222 assert(!ULE->isStdAssociatedNamespace() &&
8223 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008224#endif
8225
John McCallbc077cf2010-02-08 23:07:23 +00008226 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008227
John McCall57500772009-12-16 12:17:52 +00008228 // Add the functions denoted by the callee to the set of candidate
8229 // functions, including those from argument-dependent lookup.
8230 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008231
8232 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008233 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8234 // out if it fails.
John McCall57500772009-12-16 12:17:52 +00008235 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008236 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008237 RParenLoc, /*EmptyLookup=*/true);
John McCalld681c392009-12-16 08:11:27 +00008238
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008239 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008240 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008241 case OR_Success: {
8242 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008243 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008244 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008245 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8246 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008247 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008248 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8249 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008250 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008251
Richard Smith998a5912011-06-05 22:42:48 +00008252 case OR_No_Viable_Function: {
8253 // Try to recover by looking for viable functions which the user might
8254 // have meant to call.
8255 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8256 Args, NumArgs, RParenLoc,
8257 /*EmptyLookup=*/false);
8258 if (!Recovery.isInvalid())
8259 return Recovery;
8260
Chris Lattner45d9d602009-02-17 07:29:20 +00008261 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008262 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008263 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008264 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008265 break;
Richard Smith998a5912011-06-05 22:42:48 +00008266 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008267
8268 case OR_Ambiguous:
8269 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008270 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008271 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008272 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008273
8274 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008275 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008276 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8277 << Best->Function->isDeleted()
8278 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008279 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008280 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008281 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8282 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008283 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008284 }
8285
Douglas Gregorb412e172010-07-25 18:17:45 +00008286 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008287 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008288}
8289
John McCall4c4c1df2010-01-26 03:27:55 +00008290static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008291 return Functions.size() > 1 ||
8292 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8293}
8294
Douglas Gregor084d8552009-03-13 23:49:33 +00008295/// \brief Create a unary operation that may resolve to an overloaded
8296/// operator.
8297///
8298/// \param OpLoc The location of the operator itself (e.g., '*').
8299///
8300/// \param OpcIn The UnaryOperator::Opcode that describes this
8301/// operator.
8302///
8303/// \param Functions The set of non-member functions that will be
8304/// considered by overload resolution. The caller needs to build this
8305/// set based on the context using, e.g.,
8306/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8307/// set should not contain any member functions; those will be added
8308/// by CreateOverloadedUnaryOp().
8309///
8310/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008311ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008312Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8313 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008314 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008315 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008316
8317 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8318 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8319 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008320 // TODO: provide better source location info.
8321 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008322
John Wiegley01296292011-04-08 18:41:53 +00008323 if (Input->getObjectKind() == OK_ObjCProperty) {
8324 ExprResult Result = ConvertPropertyForRValue(Input);
8325 if (Result.isInvalid())
8326 return ExprError();
8327 Input = Result.take();
8328 }
John McCalle26a8722010-12-04 08:14:53 +00008329
Douglas Gregor084d8552009-03-13 23:49:33 +00008330 Expr *Args[2] = { Input, 0 };
8331 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008332
Douglas Gregor084d8552009-03-13 23:49:33 +00008333 // For post-increment and post-decrement, add the implicit '0' as
8334 // the second argument, so that we know this is a post-increment or
8335 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008336 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008337 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008338 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8339 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008340 NumArgs = 2;
8341 }
8342
8343 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008344 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008345 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008346 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008347 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008348 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008349 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008350
John McCall58cc69d2010-01-27 01:50:18 +00008351 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008352 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008353 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008354 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008355 /*ADL*/ true, IsOverloaded(Fns),
8356 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008357 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008358 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008359 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008360 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008361 OpLoc));
8362 }
8363
8364 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008365 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008366
8367 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008368 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008369
8370 // Add operator candidates that are member functions.
8371 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8372
John McCall4c4c1df2010-01-26 03:27:55 +00008373 // Add candidates from ADL.
8374 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008375 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008376 /*ExplicitTemplateArgs*/ 0,
8377 CandidateSet);
8378
Douglas Gregor084d8552009-03-13 23:49:33 +00008379 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008380 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008381
8382 // Perform overload resolution.
8383 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008384 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008385 case OR_Success: {
8386 // We found a built-in operator or an overloaded operator.
8387 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008388
Douglas Gregor084d8552009-03-13 23:49:33 +00008389 if (FnDecl) {
8390 // We matched an overloaded operator. Build a call to that
8391 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008392
Chandler Carruth30141632011-02-25 19:41:05 +00008393 MarkDeclarationReferenced(OpLoc, FnDecl);
8394
Douglas Gregor084d8552009-03-13 23:49:33 +00008395 // Convert the arguments.
8396 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008397 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008398
John Wiegley01296292011-04-08 18:41:53 +00008399 ExprResult InputRes =
8400 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8401 Best->FoundDecl, Method);
8402 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008403 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008404 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008405 } else {
8406 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008407 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008408 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008409 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008410 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008411 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008412 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008413 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008414 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008415 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008416 }
8417
John McCall4fa0d5f2010-05-06 18:15:07 +00008418 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8419
John McCall7decc9e2010-11-18 06:31:45 +00008420 // Determine the result type.
8421 QualType ResultTy = FnDecl->getResultType();
8422 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8423 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008424
Douglas Gregor084d8552009-03-13 23:49:33 +00008425 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008426 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8427 if (FnExpr.isInvalid())
8428 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008429
Eli Friedman030eee42009-11-18 03:58:17 +00008430 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008431 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008432 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008433 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008434
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008435 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008436 FnDecl))
8437 return ExprError();
8438
John McCallb268a282010-08-23 23:25:46 +00008439 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008440 } else {
8441 // We matched a built-in operator. Convert the arguments, then
8442 // break out so that we will build the appropriate built-in
8443 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008444 ExprResult InputRes =
8445 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8446 Best->Conversions[0], AA_Passing);
8447 if (InputRes.isInvalid())
8448 return ExprError();
8449 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008450 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008451 }
John Wiegley01296292011-04-08 18:41:53 +00008452 }
8453
8454 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008455 // This is an erroneous use of an operator which can be overloaded by
8456 // a non-member function. Check for non-member operators which were
8457 // defined too late to be candidates.
8458 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8459 // FIXME: Recover by calling the found function.
8460 return ExprError();
8461
John Wiegley01296292011-04-08 18:41:53 +00008462 // No viable function; fall through to handling this as a
8463 // built-in operator, which will produce an error message for us.
8464 break;
8465
8466 case OR_Ambiguous:
8467 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8468 << UnaryOperator::getOpcodeStr(Opc)
8469 << Input->getType()
8470 << Input->getSourceRange();
8471 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8472 Args, NumArgs,
8473 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8474 return ExprError();
8475
8476 case OR_Deleted:
8477 Diag(OpLoc, diag::err_ovl_deleted_oper)
8478 << Best->Function->isDeleted()
8479 << UnaryOperator::getOpcodeStr(Opc)
8480 << getDeletedOrUnavailableSuffix(Best->Function)
8481 << Input->getSourceRange();
8482 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8483 return ExprError();
8484 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008485
8486 // Either we found no viable overloaded operator or we matched a
8487 // built-in operator. In either case, fall through to trying to
8488 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008489 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008490}
8491
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008492/// \brief Create a binary operation that may resolve to an overloaded
8493/// operator.
8494///
8495/// \param OpLoc The location of the operator itself (e.g., '+').
8496///
8497/// \param OpcIn The BinaryOperator::Opcode that describes this
8498/// operator.
8499///
8500/// \param Functions The set of non-member functions that will be
8501/// considered by overload resolution. The caller needs to build this
8502/// set based on the context using, e.g.,
8503/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8504/// set should not contain any member functions; those will be added
8505/// by CreateOverloadedBinOp().
8506///
8507/// \param LHS Left-hand argument.
8508/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008509ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008510Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008511 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008512 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008513 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008514 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008515 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008516
8517 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8518 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8519 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8520
8521 // If either side is type-dependent, create an appropriate dependent
8522 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008523 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008524 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008525 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008526 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008527 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008528 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008529 Context.DependentTy,
8530 VK_RValue, OK_Ordinary,
8531 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008532
Douglas Gregor5287f092009-11-05 00:51:44 +00008533 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8534 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008535 VK_LValue,
8536 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008537 Context.DependentTy,
8538 Context.DependentTy,
8539 OpLoc));
8540 }
John McCall4c4c1df2010-01-26 03:27:55 +00008541
8542 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008543 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008544 // TODO: provide better source location info in DNLoc component.
8545 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008546 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008547 = UnresolvedLookupExpr::Create(Context, NamingClass,
8548 NestedNameSpecifierLoc(), OpNameInfo,
8549 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008550 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008551 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008552 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008553 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008554 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008555 OpLoc));
8556 }
8557
John McCalle26a8722010-12-04 08:14:53 +00008558 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008559 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8560 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8561 if (Result.isInvalid())
8562 return ExprError();
8563 Args[1] = Result.take();
8564 }
John McCalle26a8722010-12-04 08:14:53 +00008565
8566 // The LHS is more complicated.
8567 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8568
8569 // There's a tension for assignment operators between primitive
8570 // property assignment and the overloaded operators.
8571 if (BinaryOperator::isAssignmentOp(Opc)) {
8572 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8573
8574 // Is the property "logically" settable?
8575 bool Settable = (PRE->isExplicitProperty() ||
8576 PRE->getImplicitPropertySetter());
8577
8578 // To avoid gratuitously inventing semantics, use the primitive
8579 // unless it isn't. Thoughts in case we ever really care:
8580 // - If the property isn't logically settable, we have to
8581 // load and hope.
8582 // - If the property is settable and this is simple assignment,
8583 // we really should use the primitive.
8584 // - If the property is settable, then we could try overloading
8585 // on a generic lvalue of the appropriate type; if it works
8586 // out to a builtin candidate, we would do that same operation
8587 // on the property, and otherwise just error.
8588 if (Settable)
8589 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8590 }
8591
John Wiegley01296292011-04-08 18:41:53 +00008592 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8593 if (Result.isInvalid())
8594 return ExprError();
8595 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008596 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008597
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008598 // If this is the assignment operator, we only perform overload resolution
8599 // if the left-hand side is a class or enumeration type. This is actually
8600 // a hack. The standard requires that we do overload resolution between the
8601 // various built-in candidates, but as DR507 points out, this can lead to
8602 // problems. So we do it this way, which pretty much follows what GCC does.
8603 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008604 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008605 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008606
John McCalle26a8722010-12-04 08:14:53 +00008607 // If this is the .* operator, which is not overloadable, just
8608 // create a built-in binary operator.
8609 if (Opc == BO_PtrMemD)
8610 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8611
Douglas Gregor084d8552009-03-13 23:49:33 +00008612 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008613 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008614
8615 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008616 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008617
8618 // Add operator candidates that are member functions.
8619 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8620
John McCall4c4c1df2010-01-26 03:27:55 +00008621 // Add candidates from ADL.
8622 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8623 Args, 2,
8624 /*ExplicitTemplateArgs*/ 0,
8625 CandidateSet);
8626
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008627 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008628 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008629
8630 // Perform overload resolution.
8631 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008632 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008633 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008634 // We found a built-in operator or an overloaded operator.
8635 FunctionDecl *FnDecl = Best->Function;
8636
8637 if (FnDecl) {
8638 // We matched an overloaded operator. Build a call to that
8639 // operator.
8640
Chandler Carruth30141632011-02-25 19:41:05 +00008641 MarkDeclarationReferenced(OpLoc, FnDecl);
8642
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008643 // Convert the arguments.
8644 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008645 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008646 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008647
Chandler Carruth8e543b32010-12-12 08:17:55 +00008648 ExprResult Arg1 =
8649 PerformCopyInitialization(
8650 InitializedEntity::InitializeParameter(Context,
8651 FnDecl->getParamDecl(0)),
8652 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008653 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008654 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008655
John Wiegley01296292011-04-08 18:41:53 +00008656 ExprResult Arg0 =
8657 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8658 Best->FoundDecl, Method);
8659 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008660 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008661 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008662 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008663 } else {
8664 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008665 ExprResult Arg0 = PerformCopyInitialization(
8666 InitializedEntity::InitializeParameter(Context,
8667 FnDecl->getParamDecl(0)),
8668 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008669 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008670 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008671
Chandler Carruth8e543b32010-12-12 08:17:55 +00008672 ExprResult Arg1 =
8673 PerformCopyInitialization(
8674 InitializedEntity::InitializeParameter(Context,
8675 FnDecl->getParamDecl(1)),
8676 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008677 if (Arg1.isInvalid())
8678 return ExprError();
8679 Args[0] = LHS = Arg0.takeAs<Expr>();
8680 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008681 }
8682
John McCall4fa0d5f2010-05-06 18:15:07 +00008683 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8684
John McCall7decc9e2010-11-18 06:31:45 +00008685 // Determine the result type.
8686 QualType ResultTy = FnDecl->getResultType();
8687 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8688 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008689
8690 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008691 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8692 if (FnExpr.isInvalid())
8693 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008694
John McCallb268a282010-08-23 23:25:46 +00008695 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008696 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008697 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008698
8699 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008700 FnDecl))
8701 return ExprError();
8702
John McCallb268a282010-08-23 23:25:46 +00008703 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008704 } else {
8705 // We matched a built-in operator. Convert the arguments, then
8706 // break out so that we will build the appropriate built-in
8707 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008708 ExprResult ArgsRes0 =
8709 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8710 Best->Conversions[0], AA_Passing);
8711 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008712 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008713 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008714
John Wiegley01296292011-04-08 18:41:53 +00008715 ExprResult ArgsRes1 =
8716 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8717 Best->Conversions[1], AA_Passing);
8718 if (ArgsRes1.isInvalid())
8719 return ExprError();
8720 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008721 break;
8722 }
8723 }
8724
Douglas Gregor66950a32009-09-30 21:46:01 +00008725 case OR_No_Viable_Function: {
8726 // C++ [over.match.oper]p9:
8727 // If the operator is the operator , [...] and there are no
8728 // viable functions, then the operator is assumed to be the
8729 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008730 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008731 break;
8732
Chandler Carruth8e543b32010-12-12 08:17:55 +00008733 // For class as left operand for assignment or compound assigment
8734 // operator do not fall through to handling in built-in, but report that
8735 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008736 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008737 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008738 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008739 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8740 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008741 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008742 } else {
Richard Smith998a5912011-06-05 22:42:48 +00008743 // This is an erroneous use of an operator which can be overloaded by
8744 // a non-member function. Check for non-member operators which were
8745 // defined too late to be candidates.
8746 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8747 // FIXME: Recover by calling the found function.
8748 return ExprError();
8749
Douglas Gregor66950a32009-09-30 21:46:01 +00008750 // No viable function; try to create a built-in operation, which will
8751 // produce an error. Then, show the non-viable candidates.
8752 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008754 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008755 "C++ binary operator overloading is missing candidates!");
8756 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008757 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8758 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008759 return move(Result);
8760 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008761
8762 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008763 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008764 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008765 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008766 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008767 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8768 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008769 return ExprError();
8770
8771 case OR_Deleted:
8772 Diag(OpLoc, diag::err_ovl_deleted_oper)
8773 << Best->Function->isDeleted()
8774 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008775 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008776 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008777 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008778 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008779 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008780
Douglas Gregor66950a32009-09-30 21:46:01 +00008781 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008782 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008783}
8784
John McCalldadc5752010-08-24 06:29:42 +00008785ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008786Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8787 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008788 Expr *Base, Expr *Idx) {
8789 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008790 DeclarationName OpName =
8791 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8792
8793 // If either side is type-dependent, create an appropriate dependent
8794 // expression.
8795 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8796
John McCall58cc69d2010-01-27 01:50:18 +00008797 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008798 // CHECKME: no 'operator' keyword?
8799 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8800 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008801 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008802 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008803 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008804 /*ADL*/ true, /*Overloaded*/ false,
8805 UnresolvedSetIterator(),
8806 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008807 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008808
Sebastian Redladba46e2009-10-29 20:17:01 +00008809 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8810 Args, 2,
8811 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008812 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008813 RLoc));
8814 }
8815
John Wiegley01296292011-04-08 18:41:53 +00008816 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8817 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8818 if (Result.isInvalid())
8819 return ExprError();
8820 Args[0] = Result.take();
8821 }
8822 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8823 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8824 if (Result.isInvalid())
8825 return ExprError();
8826 Args[1] = Result.take();
8827 }
John McCalle26a8722010-12-04 08:14:53 +00008828
Sebastian Redladba46e2009-10-29 20:17:01 +00008829 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008830 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008831
8832 // Subscript can only be overloaded as a member function.
8833
8834 // Add operator candidates that are member functions.
8835 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8836
8837 // Add builtin operator candidates.
8838 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8839
8840 // Perform overload resolution.
8841 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008842 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008843 case OR_Success: {
8844 // We found a built-in operator or an overloaded operator.
8845 FunctionDecl *FnDecl = Best->Function;
8846
8847 if (FnDecl) {
8848 // We matched an overloaded operator. Build a call to that
8849 // operator.
8850
Chandler Carruth30141632011-02-25 19:41:05 +00008851 MarkDeclarationReferenced(LLoc, FnDecl);
8852
John McCalla0296f72010-03-19 07:35:19 +00008853 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008854 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008855
Sebastian Redladba46e2009-10-29 20:17:01 +00008856 // Convert the arguments.
8857 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00008858 ExprResult Arg0 =
8859 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8860 Best->FoundDecl, Method);
8861 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008862 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008863 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008864
Anders Carlssona68e51e2010-01-29 18:37:50 +00008865 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008866 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008867 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008868 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008869 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008870 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008871 Owned(Args[1]));
8872 if (InputInit.isInvalid())
8873 return ExprError();
8874
8875 Args[1] = InputInit.takeAs<Expr>();
8876
Sebastian Redladba46e2009-10-29 20:17:01 +00008877 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008878 QualType ResultTy = FnDecl->getResultType();
8879 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8880 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008881
8882 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00008883 DeclarationNameLoc LocInfo;
8884 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
8885 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
8886 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00008887 if (FnExpr.isInvalid())
8888 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008889
John McCallb268a282010-08-23 23:25:46 +00008890 CXXOperatorCallExpr *TheCall =
8891 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00008892 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008893 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008894
John McCallb268a282010-08-23 23:25:46 +00008895 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008896 FnDecl))
8897 return ExprError();
8898
John McCallb268a282010-08-23 23:25:46 +00008899 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008900 } else {
8901 // We matched a built-in operator. Convert the arguments, then
8902 // break out so that we will build the appropriate built-in
8903 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008904 ExprResult ArgsRes0 =
8905 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8906 Best->Conversions[0], AA_Passing);
8907 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008908 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008909 Args[0] = ArgsRes0.take();
8910
8911 ExprResult ArgsRes1 =
8912 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8913 Best->Conversions[1], AA_Passing);
8914 if (ArgsRes1.isInvalid())
8915 return ExprError();
8916 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008917
8918 break;
8919 }
8920 }
8921
8922 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008923 if (CandidateSet.empty())
8924 Diag(LLoc, diag::err_ovl_no_oper)
8925 << Args[0]->getType() << /*subscript*/ 0
8926 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8927 else
8928 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8929 << Args[0]->getType()
8930 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008931 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8932 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008933 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008934 }
8935
8936 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008937 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008938 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008939 << Args[0]->getType() << Args[1]->getType()
8940 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008941 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8942 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008943 return ExprError();
8944
8945 case OR_Deleted:
8946 Diag(LLoc, diag::err_ovl_deleted_oper)
8947 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008948 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00008949 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008950 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8951 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008952 return ExprError();
8953 }
8954
8955 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008956 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008957}
8958
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008959/// BuildCallToMemberFunction - Build a call to a member
8960/// function. MemExpr is the expression that refers to the member
8961/// function (and includes the object parameter), Args/NumArgs are the
8962/// arguments to the function call (not including the object
8963/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00008964/// expression refers to a non-static member function or an overloaded
8965/// member function.
John McCalldadc5752010-08-24 06:29:42 +00008966ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008967Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8968 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008969 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00008970 assert(MemExprE->getType() == Context.BoundMemberTy ||
8971 MemExprE->getType() == Context.OverloadTy);
8972
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008973 // Dig out the member expression. This holds both the object
8974 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008975 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008976
John McCall0009fcc2011-04-26 20:42:42 +00008977 // Determine whether this is a call to a pointer-to-member function.
8978 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
8979 assert(op->getType() == Context.BoundMemberTy);
8980 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
8981
8982 QualType fnType =
8983 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
8984
8985 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
8986 QualType resultType = proto->getCallResultType(Context);
8987 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
8988
8989 // Check that the object type isn't more qualified than the
8990 // member function we're calling.
8991 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
8992
8993 QualType objectType = op->getLHS()->getType();
8994 if (op->getOpcode() == BO_PtrMemI)
8995 objectType = objectType->castAs<PointerType>()->getPointeeType();
8996 Qualifiers objectQuals = objectType.getQualifiers();
8997
8998 Qualifiers difference = objectQuals - funcQuals;
8999 difference.removeObjCGCAttr();
9000 difference.removeAddressSpace();
9001 if (difference) {
9002 std::string qualsString = difference.getAsString();
9003 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9004 << fnType.getUnqualifiedType()
9005 << qualsString
9006 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9007 }
9008
9009 CXXMemberCallExpr *call
9010 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9011 resultType, valueKind, RParenLoc);
9012
9013 if (CheckCallReturnType(proto->getResultType(),
9014 op->getRHS()->getSourceRange().getBegin(),
9015 call, 0))
9016 return ExprError();
9017
9018 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9019 return ExprError();
9020
9021 return MaybeBindToTemporary(call);
9022 }
9023
John McCall10eae182009-11-30 22:42:35 +00009024 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009025 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009026 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009027 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009028 if (isa<MemberExpr>(NakedMemExpr)) {
9029 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009030 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009031 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009032 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00009033 } else {
9034 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009035 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009036
John McCall6e9f8f62009-12-03 04:06:58 +00009037 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009038 Expr::Classification ObjectClassification
9039 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9040 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009041
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009042 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009043 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009044
John McCall2d74de92009-12-01 22:10:20 +00009045 // FIXME: avoid copy.
9046 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9047 if (UnresExpr->hasExplicitTemplateArgs()) {
9048 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9049 TemplateArgs = &TemplateArgsBuffer;
9050 }
9051
John McCall10eae182009-11-30 22:42:35 +00009052 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9053 E = UnresExpr->decls_end(); I != E; ++I) {
9054
John McCall6e9f8f62009-12-03 04:06:58 +00009055 NamedDecl *Func = *I;
9056 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9057 if (isa<UsingShadowDecl>(Func))
9058 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9059
Douglas Gregor02824322011-01-26 19:30:28 +00009060
Francois Pichet64225792011-01-18 05:04:39 +00009061 // Microsoft supports direct constructor calls.
9062 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
9063 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9064 CandidateSet);
9065 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009066 // If explicit template arguments were provided, we can't call a
9067 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009068 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009069 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009070
John McCalla0296f72010-03-19 07:35:19 +00009071 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009072 ObjectClassification,
9073 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009074 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009075 } else {
John McCall10eae182009-11-30 22:42:35 +00009076 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009077 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009078 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009079 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009080 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009081 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009082 }
Mike Stump11289f42009-09-09 15:08:12 +00009083
John McCall10eae182009-11-30 22:42:35 +00009084 DeclarationName DeclName = UnresExpr->getMemberName();
9085
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009086 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009087 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009088 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009089 case OR_Success:
9090 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009091 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009092 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009093 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009094 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009095 break;
9096
9097 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009098 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009099 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009100 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009101 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009102 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009103 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009104
9105 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009106 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009107 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009108 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009109 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009110 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009111
9112 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009113 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009114 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009115 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009116 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009117 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009118 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009119 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009120 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009121 }
9122
John McCall16df1e52010-03-30 21:47:33 +00009123 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009124
John McCall2d74de92009-12-01 22:10:20 +00009125 // If overload resolution picked a static member, build a
9126 // non-member call based on that function.
9127 if (Method->isStatic()) {
9128 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9129 Args, NumArgs, RParenLoc);
9130 }
9131
John McCall10eae182009-11-30 22:42:35 +00009132 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009133 }
9134
John McCall7decc9e2010-11-18 06:31:45 +00009135 QualType ResultType = Method->getResultType();
9136 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9137 ResultType = ResultType.getNonLValueExprType(Context);
9138
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009139 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009140 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009141 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009142 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009143
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009144 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009145 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009146 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009147 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009148
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009149 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009150 // We only need to do this if there was actually an overload; otherwise
9151 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009152 if (!Method->isStatic()) {
9153 ExprResult ObjectArg =
9154 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9155 FoundDecl, Method);
9156 if (ObjectArg.isInvalid())
9157 return ExprError();
9158 MemExpr->setBase(ObjectArg.take());
9159 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009160
9161 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009162 const FunctionProtoType *Proto =
9163 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009164 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009165 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009166 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009167
John McCallb268a282010-08-23 23:25:46 +00009168 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009169 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009170
Anders Carlsson47061ee2011-05-06 14:25:31 +00009171 if ((isa<CXXConstructorDecl>(CurContext) ||
9172 isa<CXXDestructorDecl>(CurContext)) &&
9173 TheCall->getMethodDecl()->isPure()) {
9174 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9175
Chandler Carruth59259262011-06-27 08:31:58 +00009176 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009177 Diag(MemExpr->getLocStart(),
9178 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9179 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9180 << MD->getParent()->getDeclName();
9181
9182 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009183 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009184 }
John McCallb268a282010-08-23 23:25:46 +00009185 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009186}
9187
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009188/// BuildCallToObjectOfClassType - Build a call to an object of class
9189/// type (C++ [over.call.object]), which can end up invoking an
9190/// overloaded function call operator (@c operator()) or performing a
9191/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009192ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009193Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009194 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009195 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009196 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00009197 ExprResult Object = Owned(Obj);
9198 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9199 Object = ConvertPropertyForRValue(Object.take());
9200 if (Object.isInvalid())
9201 return ExprError();
9202 }
John McCalle26a8722010-12-04 08:14:53 +00009203
John Wiegley01296292011-04-08 18:41:53 +00009204 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9205 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009206
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009207 // C++ [over.call.object]p1:
9208 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009209 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009210 // candidate functions includes at least the function call
9211 // operators of T. The function call operators of T are obtained by
9212 // ordinary lookup of the name operator() in the context of
9213 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009214 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009215 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009216
John Wiegley01296292011-04-08 18:41:53 +00009217 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009218 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009219 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009220 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009221
John McCall27b18f82009-11-17 02:14:36 +00009222 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9223 LookupQualifiedName(R, Record->getDecl());
9224 R.suppressDiagnostics();
9225
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009226 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009227 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009228 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9229 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009230 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009231 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009232
Douglas Gregorab7897a2008-11-19 22:57:39 +00009233 // C++ [over.call.object]p2:
9234 // In addition, for each conversion function declared in T of the
9235 // form
9236 //
9237 // operator conversion-type-id () cv-qualifier;
9238 //
9239 // where cv-qualifier is the same cv-qualification as, or a
9240 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009241 // denotes the type "pointer to function of (P1,...,Pn) returning
9242 // R", or the type "reference to pointer to function of
9243 // (P1,...,Pn) returning R", or the type "reference to function
9244 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009245 // is also considered as a candidate function. Similarly,
9246 // surrogate call functions are added to the set of candidate
9247 // functions for each conversion function declared in an
9248 // accessible base class provided the function is not hidden
9249 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009250 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009251 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009252 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009253 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009254 NamedDecl *D = *I;
9255 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9256 if (isa<UsingShadowDecl>(D))
9257 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009258
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009259 // Skip over templated conversion functions; they aren't
9260 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009261 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009262 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009263
John McCall6e9f8f62009-12-03 04:06:58 +00009264 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00009265
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009266 // Strip the reference type (if any) and then the pointer type (if
9267 // any) to get down to what might be a function type.
9268 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9269 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9270 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00009271
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009272 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00009273 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John Wiegley01296292011-04-08 18:41:53 +00009274 Object.get(), Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009275 }
Mike Stump11289f42009-09-09 15:08:12 +00009276
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009277 // Perform overload resolution.
9278 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009279 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009280 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009281 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009282 // Overload resolution succeeded; we'll build the appropriate call
9283 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009284 break;
9285
9286 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009287 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009288 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9289 << Object.get()->getType() << /*call*/ 1
9290 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009291 else
John Wiegley01296292011-04-08 18:41:53 +00009292 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009293 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009294 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009295 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009296 break;
9297
9298 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009299 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009300 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009301 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009302 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009303 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009304
9305 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009306 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009307 diag::err_ovl_deleted_object_call)
9308 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009309 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009310 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009311 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009312 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009313 break;
Mike Stump11289f42009-09-09 15:08:12 +00009314 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009315
Douglas Gregorb412e172010-07-25 18:17:45 +00009316 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009317 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009318
Douglas Gregorab7897a2008-11-19 22:57:39 +00009319 if (Best->Function == 0) {
9320 // Since there is no function declaration, this is one of the
9321 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009322 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009323 = cast<CXXConversionDecl>(
9324 Best->Conversions[0].UserDefined.ConversionFunction);
9325
John Wiegley01296292011-04-08 18:41:53 +00009326 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009327 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009328
Douglas Gregorab7897a2008-11-19 22:57:39 +00009329 // We selected one of the surrogate functions that converts the
9330 // object parameter to a function pointer. Perform the conversion
9331 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009332
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009333 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009334 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00009335 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00009336 if (Call.isInvalid())
9337 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009338
Douglas Gregor668443e2011-01-20 00:18:04 +00009339 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009340 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009341 }
9342
Chandler Carruth30141632011-02-25 19:41:05 +00009343 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009344 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009345 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009346
Douglas Gregorab7897a2008-11-19 22:57:39 +00009347 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9348 // that calls this method, using Object for the implicit object
9349 // parameter and passing along the remaining arguments.
9350 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009351 const FunctionProtoType *Proto =
9352 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009353
9354 unsigned NumArgsInProto = Proto->getNumArgs();
9355 unsigned NumArgsToCheck = NumArgs;
9356
9357 // Build the full argument list for the method call (the
9358 // implicit object parameter is placed at the beginning of the
9359 // list).
9360 Expr **MethodArgs;
9361 if (NumArgs < NumArgsInProto) {
9362 NumArgsToCheck = NumArgsInProto;
9363 MethodArgs = new Expr*[NumArgsInProto + 1];
9364 } else {
9365 MethodArgs = new Expr*[NumArgs + 1];
9366 }
John Wiegley01296292011-04-08 18:41:53 +00009367 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009368 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9369 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009370
John Wiegley01296292011-04-08 18:41:53 +00009371 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9372 if (NewFn.isInvalid())
9373 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009374
9375 // Once we've built TheCall, all of the expressions are properly
9376 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009377 QualType ResultTy = Method->getResultType();
9378 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9379 ResultTy = ResultTy.getNonLValueExprType(Context);
9380
John McCallb268a282010-08-23 23:25:46 +00009381 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009382 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009383 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009384 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009385 delete [] MethodArgs;
9386
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009387 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009388 Method))
9389 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009390
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009391 // We may have default arguments. If so, we need to allocate more
9392 // slots in the call for them.
9393 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009394 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009395 else if (NumArgs > NumArgsInProto)
9396 NumArgsToCheck = NumArgsInProto;
9397
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009398 bool IsError = false;
9399
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009400 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009401 ExprResult ObjRes =
9402 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9403 Best->FoundDecl, Method);
9404 if (ObjRes.isInvalid())
9405 IsError = true;
9406 else
9407 Object = move(ObjRes);
9408 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009409
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009410 // Check the argument types.
9411 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009412 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009413 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009414 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009415
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009416 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009417
John McCalldadc5752010-08-24 06:29:42 +00009418 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009419 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009420 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009421 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009422 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009423
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009424 IsError |= InputInit.isInvalid();
9425 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009426 } else {
John McCalldadc5752010-08-24 06:29:42 +00009427 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009428 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9429 if (DefArg.isInvalid()) {
9430 IsError = true;
9431 break;
9432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009433
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009434 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009435 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009436
9437 TheCall->setArg(i + 1, Arg);
9438 }
9439
9440 // If this is a variadic call, handle args passed through "...".
9441 if (Proto->isVariadic()) {
9442 // Promote the arguments (C99 6.5.2.2p7).
9443 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009444 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9445 IsError |= Arg.isInvalid();
9446 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009447 }
9448 }
9449
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009450 if (IsError) return true;
9451
John McCallb268a282010-08-23 23:25:46 +00009452 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009453 return true;
9454
John McCalle172be52010-08-24 06:09:16 +00009455 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009456}
9457
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009458/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009459/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009460/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009461ExprResult
John McCallb268a282010-08-23 23:25:46 +00009462Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009463 assert(Base->getType()->isRecordType() &&
9464 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009465
John Wiegley01296292011-04-08 18:41:53 +00009466 if (Base->getObjectKind() == OK_ObjCProperty) {
9467 ExprResult Result = ConvertPropertyForRValue(Base);
9468 if (Result.isInvalid())
9469 return ExprError();
9470 Base = Result.take();
9471 }
John McCalle26a8722010-12-04 08:14:53 +00009472
John McCallbc077cf2010-02-08 23:07:23 +00009473 SourceLocation Loc = Base->getExprLoc();
9474
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009475 // C++ [over.ref]p1:
9476 //
9477 // [...] An expression x->m is interpreted as (x.operator->())->m
9478 // for a class object x of type T if T::operator->() exists and if
9479 // the operator is selected as the best match function by the
9480 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009481 DeclarationName OpName =
9482 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009483 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009484 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009485
John McCallbc077cf2010-02-08 23:07:23 +00009486 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009487 PDiag(diag::err_typecheck_incomplete_tag)
9488 << Base->getSourceRange()))
9489 return ExprError();
9490
John McCall27b18f82009-11-17 02:14:36 +00009491 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9492 LookupQualifiedName(R, BaseRecord->getDecl());
9493 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009494
9495 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009496 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009497 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9498 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009499 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009500
9501 // Perform overload resolution.
9502 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009503 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009504 case OR_Success:
9505 // Overload resolution succeeded; we'll build the call below.
9506 break;
9507
9508 case OR_No_Viable_Function:
9509 if (CandidateSet.empty())
9510 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009511 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009512 else
9513 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009514 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009515 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009516 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009517
9518 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009519 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9520 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009521 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009522 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009523
9524 case OR_Deleted:
9525 Diag(OpLoc, diag::err_ovl_deleted_oper)
9526 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009527 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009528 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009529 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009530 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009531 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009532 }
9533
Chandler Carruth30141632011-02-25 19:41:05 +00009534 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009535 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009536 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009537
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009538 // Convert the object parameter.
9539 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009540 ExprResult BaseResult =
9541 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9542 Best->FoundDecl, Method);
9543 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009544 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009545 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009546
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009547 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009548 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9549 if (FnExpr.isInvalid())
9550 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009551
John McCall7decc9e2010-11-18 06:31:45 +00009552 QualType ResultTy = Method->getResultType();
9553 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9554 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009555 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009556 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009557 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009558
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009559 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009560 Method))
9561 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009562
9563 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009564}
9565
Douglas Gregorcd695e52008-11-10 20:40:00 +00009566/// FixOverloadedFunctionReference - E is an expression that refers to
9567/// a C++ overloaded function (possibly with some parentheses and
9568/// perhaps a '&' around it). We have resolved the overloaded function
9569/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009570/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009571Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009572 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009573 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009574 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9575 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009576 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009577 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009578
Douglas Gregor51c538b2009-11-20 19:42:02 +00009579 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009580 }
9581
Douglas Gregor51c538b2009-11-20 19:42:02 +00009582 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009583 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9584 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009585 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009586 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009587 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009588 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009589 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009590 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009591
9592 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009593 ICE->getCastKind(),
9594 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009595 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009596 }
9597
Douglas Gregor51c538b2009-11-20 19:42:02 +00009598 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009599 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009600 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009601 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9602 if (Method->isStatic()) {
9603 // Do nothing: static member functions aren't any different
9604 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009605 } else {
John McCalle66edc12009-11-24 19:00:30 +00009606 // Fix the sub expression, which really has to be an
9607 // UnresolvedLookupExpr holding an overloaded member function
9608 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009609 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9610 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009611 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009612 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009613
John McCalld14a8642009-11-21 08:51:07 +00009614 assert(isa<DeclRefExpr>(SubExpr)
9615 && "fixed to something other than a decl ref");
9616 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9617 && "fixed to a member ref with no nested name qualifier");
9618
9619 // We have taken the address of a pointer to member
9620 // function. Perform the computation here so that we get the
9621 // appropriate pointer to member type.
9622 QualType ClassType
9623 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9624 QualType MemPtrType
9625 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9626
John McCall7decc9e2010-11-18 06:31:45 +00009627 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9628 VK_RValue, OK_Ordinary,
9629 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009630 }
9631 }
John McCall16df1e52010-03-30 21:47:33 +00009632 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9633 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009634 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009635 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009636
John McCalle3027922010-08-25 11:45:40 +00009637 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009638 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009639 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009640 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009641 }
John McCalld14a8642009-11-21 08:51:07 +00009642
9643 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009644 // FIXME: avoid copy.
9645 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009646 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009647 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9648 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009649 }
9650
John McCalld14a8642009-11-21 08:51:07 +00009651 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009652 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009653 Fn,
9654 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009655 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009656 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009657 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009658 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009659 }
9660
John McCall10eae182009-11-30 22:42:35 +00009661 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009662 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009663 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9664 if (MemExpr->hasExplicitTemplateArgs()) {
9665 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9666 TemplateArgs = &TemplateArgsBuffer;
9667 }
John McCall6b51f282009-11-23 01:53:49 +00009668
John McCall2d74de92009-12-01 22:10:20 +00009669 Expr *Base;
9670
John McCall7decc9e2010-11-18 06:31:45 +00009671 // If we're filling in a static method where we used to have an
9672 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009673 if (MemExpr->isImplicitAccess()) {
9674 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9675 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009676 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009677 Fn,
9678 MemExpr->getMemberLoc(),
9679 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009680 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009681 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009682 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009683 } else {
9684 SourceLocation Loc = MemExpr->getMemberLoc();
9685 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009686 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009687 Base = new (Context) CXXThisExpr(Loc,
9688 MemExpr->getBaseType(),
9689 /*isImplicit=*/true);
9690 }
John McCall2d74de92009-12-01 22:10:20 +00009691 } else
John McCallc3007a22010-10-26 07:05:15 +00009692 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009693
John McCall4adb38c2011-04-27 00:36:17 +00009694 ExprValueKind valueKind;
9695 QualType type;
9696 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9697 valueKind = VK_LValue;
9698 type = Fn->getType();
9699 } else {
9700 valueKind = VK_RValue;
9701 type = Context.BoundMemberTy;
9702 }
9703
John McCall2d74de92009-12-01 22:10:20 +00009704 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009705 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009706 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009707 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009708 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009709 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009710 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009711 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009713
John McCallc3007a22010-10-26 07:05:15 +00009714 llvm_unreachable("Invalid reference to overloaded function");
9715 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009716}
9717
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009718ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009719 DeclAccessPair Found,
9720 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009721 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009722}
9723
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009724} // end namespace clang